Created
May 18, 2020 16:25
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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
Great !