Skip to content

Instantly share code, notes, and snippets.

@pasdam
Created January 1, 2023 17:51
Show Gist options
  • Save pasdam/b89739c4fb2de5c1e369898a394458af to your computer and use it in GitHub Desktop.
Save pasdam/b89739c4fb2de5c1e369898a394458af to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
sort terraform variables
it's easy to do, just follow these steps:
python sort_terraform_variables.py variables.tf > sorted_variables.tf
mv sorted_variables.tf variables.tf
"""
from __future__ import print_function
import sys
import re
# this regex matches terraform variable definitions
# we capture the variable name so we can sort on it
pattern = r'(variable ")([^"]+)(" {[^{]+})'
def process(content):
# sort the content (a list of tuples) on the second item of the tuple
# (which is the variable name)
matches = sorted(re.findall(pattern, content), key=lambda x: x[1])
# iterate over the sorted list and output them
for match in matches:
print(''.join(map(str, match)))
# don't print the newline on the last item
if match != matches[-1]:
print()
# check if we're reading from stdin
if not sys.stdin.isatty():
stdin = sys.stdin.read()
if stdin:
process(stdin)
# process any filenames on the command line
for filename in sys.argv[1:]:
with open(filename) as f:
process(f.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment