Skip to content

Instantly share code, notes, and snippets.

@atward
Last active Jul 13, 2021
Embed
What would you like to do?
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

clemenspeters commented Nov 27, 2020

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