Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@atward
Last active July 13, 2021 11:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atward/7a2eb1b4a78fbaebe585 to your computer and use it in GitHub Desktop.
Save atward/7a2eb1b4a78fbaebe585 to your computer and use it in GitHub Desktop.
Rudimentary parsing of terraform tfvars in bash
#!/bin/bash
# source: https://gist.github.com/atward/7a2eb1b4a78fbaebe585
# here be dragons: this is as dangerous as it looks
## terraform variable defaults
# takes *.tf and assigns env=default (if any)
# - map not supported (obvious reasons)
# - Tested on Darwin sed(1) only
function source_tfdefaults() {
eval "$(
sed -n '/variable [-a-z0-9_]* {/{:start
/}/!{N;b start
}
s/^variable \([-a-z0-9_]*\).*default *= *"\([^"]*\)".*/\1="\2"/p
}' "$@"
)"
}
## tfvars assignments
# takes *.tfvars and assigns env=value
# - works with terraform 0.6 types: string, map
# - map.key becomes map_key
function source_tfvars() {
eval "$(
awk 'BEGIN {FS=OFS="="}
!/^(#| *$)/ && /^.+=.+$/ {
gsub(/^[ \t]+|[ \t]+$/, "", $1);
gsub(/\./, "_", $1);
gsub(/^[ \t]+|[ \t]+$/, "", $2);
if ($1 && $2) print $0
}' "$@"
)"
}
# usage:
#source_tfdefaults *.tf
#source_tfvars "./conf.tfvars"
@clemenspeters
Copy link

Did you consider using tfvars.json files and then processing them using jq?

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