-
Notifications
You must be signed in to change notification settings - Fork 9.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature Request: terraform fmt applies sort to variables.tf and terraform.tfvars #12959
Comments
Disagree. |
Disagree x 2 |
We currently do this manually. While I agree with the dissenters, it would be excellent if this was an OPTION that could be enabled. |
I'm curious, this sounds like a great feature. Why the disagreement? |
I'd buy it. |
I found a script somewhere on the webs that got me really close to what I needed, so I pretty much lifted that dude's code and made some minor changes - and now have a really, really, naive (and yeah, totally hacky) script to take care of automatically sorting terraform variables files. See below, and please, if you have suggestions, I'd love for you to change the script and post back with what's more clever. I'll probably parameterize it so you pass the file you want sorted on the command line after calling the script. Tested on my own machine - works fine. Run at your own risk. WARNING - If you've got ANY commented lines, descriptions inside the variable braces, or empty braces without any content initialized as variables, this will break your stuff! This only works when your variables look exactly like:
|
Hi all! Thanks for the discussion here. This does seem like a reasonable helper-tool, though I'd be nervous about making it the default behavior for Sorting a hypothetical I could see us defining a "canonical sort" for a Terraform configuration file, such as:
This would allow us to then have a tool that applies this sort to arbitrary config files, as long as the input complies with certain expectations, such as doc comments appearing immediately before whatever they belong to and having no other "unattached" comments at the top-level of the file. (Much of the above ordering is arbitrary, just for illustration purposes; let's not bike-shed the specific ordering for the moment.) The ordering of Such a tool won't be a priority for us right now because we're in the middle of integrating a revamped config language parser and so this would end up needing to get rewritten against the new parser anyway, but once that's done we could think about how best to design a tool like this, how/whether it should integrate with In the mean time, having third-party tools to do this for subsets of valid Terraform configurations seems reasonable, with the caveat that they will probably need revision once the new configuration language parser is integrated since it includes new syntax elements that the current parser would choke on. |
This is indeed a very good discussion. I will remain in the camp that organizes variables and other resources in more logical groupings by function rather than a lexical sorting. I would rather dev time be spent on making the fmt subcommand more flexible, since I don't like how it does some things but others are great. It might meet certain requests if Ultimately I will also appreciate a greater amount of time spent on core and critical issues. |
Here's a slightly less dirty hack than the previously-presented bash script. #!/usr/bin/env python
# sort terraform variables
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()) |
@robinbowes - Well done. Thank you for this. Hell of a lot cleaner than what I'd ham-fistedly mashed together. |
This is old and closed but still found by Google searching. For anyone who stumbles on this, the Python code above works but will destroy any map variables you have. Change the pattern regex to this:
Example: Sure, there's probably a nicer / more optimal way but it works... |
Actually, this is probably the least hacky way to sort variables:
Or, if you prefer pipes:
|
Nice @robinbowes |
I would love to see this as a non-default option in |
At least with the versions of the libraries I tried this technique modifies and quotes the 'variable' so each one reads as "variable" in a .tf @robinbowes |
hcl2json doesn't support hcl2, so the fun workarounds are dead for me :( |
I updated @robinbowes script for python3, https://gist.github.com/sblack4/34d74f6a4a6df65eb8d6e563a5135111 > python sort_terraform_variables.py variables.tf > sorted_variables.tf
> mv sorted_variables.tf variables.tf |
|
It's cool and probably would be useful if I was handy in go but I need a quick fix. I ran it and here's an example output:
|
Try it with the |
Well, sorting parameters isn't good in my opinion. Some resources have a lot of them and I, personally, prefer to write them in the same order as described in documentation. So it's quicker to find any. |
"in my opinion", "I, personally, prefer" - the discussion here is about adding an option so those who do want sorting can have it if they choose. You are free to not use the option. |
Agree with Robin. As long as you aren't changing default behavior adding these features hurts no one that doesn't want to use them. It's just a matter of engineering time/priorities to write the code, and I very much understand those constraints. |
Totally agree as long as it's not a default behavior :) |
I came up achieving the goal of sorting |
JFYI: I've just extended the script to handle also some other types of TF resources (not only |
@yermulnik Excellent script and did exactly what I was looking for |
@Office-Manager Yeah, I see, I didn't think of such a use case. And it sounds reasonable. Thanks for the suggestion. I made a tiny update to the script (and published it) to ignore case for string operations in the block where sorting is done. Seemingly should not break something else 🤞 |
I agree with @apparentlymart - nothing can make super clear decisions on reformatting because it cant possibly know how to keep comments with the right variable/resource/module. Does a comment outside a variable/resource/module relate to the block above or the block below? or neither? or both? We just use a pre-commit githook to tell us if the sort order is not what we want, and then require the developer to do the work of fixing it up. The sort order we use for every type of block except locals is:
locals should not be sorted, because the order of locals attributes can affect functionality within a single locals block. We also then sort all resources / modules / datasources by class (data/resource/module) and then alphabetically by name. Anyway - TL;DR - githooks throwing out the commit worked better for us than auto-reformatting for above reasons. |
Auto sort for lists and object keys would be really helpful IMO (for sure optional, not default behavior). We have a lot of patterns where we use lists / objects to create module resources, and with those, for us, it's generally tidiest to request that those be sorted alphanumerically. |
Hi all, The goal of This issue is asking for something that is outside the intended scope of that command, in a few different ways:
For that reason, I don't think this is something we will add to Instead, this seems like a good opportunity for one or more third-party tools that can propose a more opinionated style that is considerably heavier than what The HCL API that Given all of the above, I'm going to close this issue. The Terraform team will not offer more opinionated formatting options built in, but we'd welcome folks in the community implementing additional tools if they have particular preferences beyond what Thanks for the discussion here! Although it didn't lead to a change, it has helped to clarify what is and isn't in scope for |
Does anyone know the name of such a tool? |
I migrated our users.auto.tfvars to users.auto.tfvars.json (via https://github.com/tmccombs/hcl2json) and run it through jq sort in CI. jq '.users |= sort_by(.name)' users.auto.tfvars.json > users.auto.tfvars.json.sorted
mv users.auto.tfvars.json.sorted users.auto.tfvars.json |
I prefer to add some meaningful prefix to variables so the sorting would match the logical grouping at the same time. |
I'm going to lock this issue because it has been closed for 30 days ⏳. This helps our maintainers find and focus on the active issues. |
It would be useful imho for terraform fmt to also do an alphabetical sort on variable definition files, namely variables.tf and terraform.tfvars.
The text was updated successfully, but these errors were encountered: