Skip to content

Instantly share code, notes, and snippets.

@sblack4
Created May 18, 2020 16:25
Show Gist options
  • Save sblack4/34d74f6a4a6df65eb8d6e563a5135111 to your computer and use it in GitHub Desktop.
Save sblack4/34d74f6a4a6df65eb8d6e563a5135111 to your computer and use it in GitHub Desktop.
Sort Terraform Variables (taken from @robinbowes, https://github.com/hashicorp/terraform/issues/12959)
#!/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())
@mmyrtekbmj
Copy link

Great !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment