pre-commit-terraform icon indicating copy to clipboard operation
pre-commit-terraform copied to clipboard

Hook to sort definition blocks in HCL files

Open yermulnik opened this issue 2 years ago β€’ 4 comments

What problem are you facing?

A while ago ~before orcs groundlessly and treacherously come against Ukraine~ while I was poking around some TF issue I stumbled upon this thread about sorting Terraform files and created a tiny AWK script to achieve the goal of sorting definition blocks in .tf files.

And now I had a thought that someone may find it useful and may want to create a pre-commit-terraform hook to benefit from it (I don't actually heavily use either and thus I'm not sure I'd be able to allocate some reasonable amount of time for this). So if there are any volunteers to pick this task up, I'd be happy to assist as much as time permits.

Thanks in advance for the contribution and effort πŸ™‡πŸ»

How could pre-commit-terraform help solve your problem?

Sorting definition blocks in *.tf files may make your code more beautiful and clear. Or may not 😏

yermulnik avatar Nov 04 '22 17:11 yermulnik

That pretty much looks like the current terraform_docs realization, jfyi. So will be a good idea to look into it to understand how to +- do the same as a standalone hook.

MaxymVlasov avatar Nov 04 '22 20:11 MaxymVlasov

@yermulnik when using your tf_vars_sort.awk I am getting the following:

❯ cat _variables.tf  | awk -f tf_vars_sort.awk | tee _variables_sorted.tf                                                                            ξ‚² ⇣15.9 KiB/s ⇑15 KiB/s 192.168.1.107  β”‚ 208.127.175.132  β”‚ 100% ο•Έ β”‚ 405 Mbps  
awk: syntax error at source line 11 source file tf_vars_sort.awk
 context is
                switch ($0) >>>  { <<< 
awk: illegal statement at source line 11 source file tf_vars_sort.awk
awk: illegal statement at source line 11 source file tf_vars_sort.awk
        3 missing }'s

oviliz avatar Feb 22 '23 10:02 oviliz

@oviliz be sure that you use gawk awk not mawk. That's root cause in most cases

MaxymVlasov avatar Feb 22 '23 12:02 MaxymVlasov

@oviliz https://gist.github.com/yermulnik/7e0cf991962680d406692e1db1b551e6

Tested with GNU Awk 5.0.1, API: 2.0 (GNU MPFR 4.0.2, GNU MP 6.2.0)

yermulnik avatar Feb 22 '23 12:02 yermulnik