1

We need to align the = character in our terraform files against the longest variable name. Is there any tool that can do this automatically?

For example

thomas = "train"
harrypotter = "wizard"
roger = "rabbit"

...would become...

thomas      = "train"
harrypotter = "wizard"
roger       = "rabbit"

Bonus points: I use PyCharm primarily, so if it were a plugin for PyCharm I would be overjoyed.

3 Answers 3

2

Smart Align is a PyCharm plugin which does exactly that. Just,

Windows & Linux

  1. Click into the file
  2. Ctrl + a
  3. Alt + ⇧ + -

Mac

  1. Click into the file
  2. ⌘ + a
  3. ⌥ + ⇧ + -

Done

2

Just install the "Terraform and HCL"-Plugin from Jetbrains. It also supports syntax highglighting and much more features.

After you've installed it, open your file and press "Ctrl+Alt+L" to reformat your code.

Maybe check the "Align properties" settings in Settings->Editor->Code Style->Terraform Config and there in the last tab at the right called "Other" (see screenshot). It has to be "On equals", but that is the default setting.

enter image description here

3
  • How do you get this plugin to align all logical blocks the same? As far as I can see, it only aligns each logical block separately. Nov 18, 2021 at 7:58
  • @James I don't think the plugin can do that. The formatting is applied to blocks seperately, not equally over the whole file. Your original question didn't imply this to be a requested feature, but if you like that to happen, then Smart align might be the better solution for you :)
    – Micha
    Nov 18, 2021 at 11:17
  • Thanks, and apologies for the omission. I don't suppose I might be able to ask if you know how I would add smart aline to the precommit config, could I? Nov 18, 2021 at 11:33
2

As usual - Unix shell utilities to the rescue! Specifically, column:

$ column -t
thomas = "train"
harrypotter = "wizard"
roger = "rabbit"

thomas         = "train"
harrypotter    = "wizard"
roger          = "rabbit"

And it works on files as well, of course:

$ cat my_file.txt
thomas = "train"
harrypotter = "wizard"
roger = "rabbit"
$ column -t my_file.txt
thomas         = "train"
harrypotter    = "wizard"
roger          = "rabbit"
3
  • Nice and simple! Your answer may benefit from adding an example showing how to process input from a file. Either way, upvoted! Dec 12, 2021 at 13:50
  • @RockPaperLz-MaskitorCasket: I thought that was obvious, but ok.
    – einpoklum
    Dec 12, 2021 at 13:52
  • Yep, it's obvious for those of us who know how easy it is. :) Dec 12, 2021 at 13:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.