Skip to content

Instantly share code, notes, and snippets.

@abuxton
Last active November 19, 2021 13:48
Show Gist options
  • Save abuxton/27a777476a5abe4479f8061fbbec3b76 to your computer and use it in GitHub Desktop.
Save abuxton/27a777476a5abe4479f8061fbbec3b76 to your computer and use it in GitHub Desktop.

manipulate variables helpers

if you've not already go get tfvars utility! https://github.com/shihanng/tfvar it will help a lot.

Lets grab all the variables in a module thats easy tfvar . but what do with them now? You can simply append them to a tfvar or auto.tfvars file tfvar . > example.auto.tfvars

But what if there are multiple modules you want to use and you want to collect all their variables?

  • A sensible approach is to redeclare them all as locals the helpers below create output that can be simple appened and then encapsulated ina. locals{ } block
  • you can then declare the modules using the locals as below
locals{
  module_name_variable=value
}
module "module_name" {
  source = 'module/source'
  variable = local.module_name_variable
}

helpers

ok first lets name all the variables in a valid way and contextually to their source module.

# git clone module source
# alternatively if you are in a initiated terraform module with modules sourced 
# cd ./terraform/modules/modulename
# then execute the following;

i=$(basename $PWD) tfvar . | sed "s/^[a-z]/$(echo $i | cut -d'/' -f1)_&/"

if you want to push them into a locals.tf file (tfvar behaves oddly with bad tf code so to work around issues do the following

echo 'locals {' > locals.tfx
i=$(basename $PWD) tfvar . | sed "s/^[a-z]/$(echo $i | cut -d'/' -f1)_&/" >> locals.tfx
echo '}' >> locals.tfx && mv locals.tfx locals.tf && cat locals.tf

if you want to do the same to a collection of modules.

# if you're in a wrapper modules with ./modules 
module_path='./modules'

# if you're in an initialised terraform module warpper folder
module_path='./terraform/modules'
for i in `ls -a $modulepath | cut -d' ' -f7`; do echo $i && tfvar $modulepath/$i | sed "s/^[a-z]/$(echo $i | cut -d'/' -f1)_&/" ; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment