Skip to content

Instantly share code, notes, and snippets.

@iamsudip
Last active April 26, 2019 09:32
Show Gist options
  • Save iamsudip/c8e3a95e27c19cdc1e61c0d167617e4d to your computer and use it in GitHub Desktop.
Save iamsudip/c8e3a95e27c19cdc1e61c0d167617e4d to your computer and use it in GitHub Desktop.
Terraform Varible Extractor
#!/usr/bin/env python
# I use it by keeping it in /usr/local/bin as extract_tf_vars
# When I'm finished writing module I execute $ extract_tf_vars `pwd`
import os
import re
import sys
module_path = sys.argv[1]
regex = r"{var.[a-zA-Z_]+\}"
variables = []
for subdir, dirs, files in os.walk(module_path):
for f in files:
with open(f, 'r') as fp:
content = fp.read()
matches = re.finditer(regex, content, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
match = match.group()
match = match.replace('{var.', '').replace('}', '')
variables.append(match)
variables = list(set(variables))
variables.sort()
with open('variables.tf', 'w') as fp:
for variable in variables:
template = 'variable "%s" {\n description = ""\n}\n\n' % variable
fp.write(template)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment