Skip to content

Instantly share code, notes, and snippets.

@KiaraGrouwstra
Last active January 25, 2024 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KiaraGrouwstra/249ede6a7dfc00ea44d85bc6bdbcd875 to your computer and use it in GitHub Desktop.
Save KiaraGrouwstra/249ede6a7dfc00ea44d85bc6bdbcd875 to your computer and use it in GitHub Desktop.
hcl2nix.sh
#!/usr/bin/env sh
# usage: cat my-file.hcl | ./hcl2nix.sh > my-file.nix
cat << EOF
{
$(sed -E 's/\}$/};/g' \
| sed -E 's/\]$/];/g' \
| sed -E 's/= (.*[^\[\{])$/= \1;/g' \
| sed -E 's/ \{/ = {/g' \
| sed -E 's/^(\w+) "/\1."/g' \
| sed -E 's/" "/"."/g' \
| sed -E 's/\/\//#/g' \
| sed -E 's/:#/:\/\//g' \
| sed -E 's/\$/\$/g' \
| sed -E 's/= =/=/g' \
| sed -E 's/\{$;/{/g' \
| sed -E 's/\[$;/[/g' \
| sed -E 's/,$//g' \
| sed -E 's/,;$/;/g' \
| sed -E 's/;;$/;/g' \
| sed -E 's/^(.*)$/ \1/g' \
| sed -E 's/^(\s+\w+) "/\1."/g' \
| sed -E 's/ (list|object|number|string|bool);/ "\1";/g' \
| sed -E 's/\$\{/\\${/g' \
| sed -E 's/affinity /affinities [/g' \
| sed -E 's/constraint /constraints [/g' \
| sed -E 's/network /networks [/g' \
| sed -E 's/service /services [/g' \
| sed -E 's/check /checks [/g' \
| sed -E 's/listener /listeners [/g' \
| sed -E 's/spread /spreads [/g' \
| sed -E 's/artifact /artifacts [/g' \
| sed -E 's/scaling /scalings [/g' \
| sed -E 's/template /templates [/g' \
| sed -E 's/volume_mount /volumeMounts [/g' \
| sed -E 's/", "/" "/g'
)
}
EOF
@KiaraGrouwstra
Copy link
Author

wtfpl :)

@mrVanDalo
Copy link

mrVanDalo commented Jan 13, 2024

Very nice! This helps quite a lot to speed up terraform -> terranix transformation.

Of course for_each and list comprehensions can't be parsed or transformed. But maybe the comma in lists

subject_alternative_names = ["www.example.com", "example.org"]

to

subject_alternative_names = ["www.example.com" "example.org"]

but I guess sed is not capable of this type of context awareness.

Anyway, thanks for the script, will definitely use it to transform examples from the documentation. 🙇

@KiaraGrouwstra
Copy link
Author

@mrVanDalo i added a line to try and catch the commas.
admittedly string-based replacements will be fragile in the end, but yeah. :)

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