1
votes

i want my terraform command plan to have some additional variable override according to if some variables are setted up prior in the bash script.

that is to say: the usual terraform plan i want to expand to terraform plan -var="foo=bar" if some variable is set up.

i tried up

terraform plan "${_TERRAFORM_DOCKER_IMAGE_OPTION:-}"

but this fails due to the terraform error:

Too many command line arguments. Configuration path expected.

is there a way to do a dynamic plan command for terraform?


the bash script is a slight modification of the bash SIMPLE boilerplate by alphabetum. https://github.com/alphabetum/bash-boilerplate/blob/master/bash-simple

with a couple of conditionals to create the -var strings.

if [[ -n "${_DOCKER_IMAGE}" ]]
  then
    _TERRAFORM_DOCKER_IMAGE_OPTION="-var=\"app_image=${_DOCKER_IMAGE}\""
fi

after the variable strings are setted up, i try to use them in the terraform plan command as:

terraform plan "${_TERRAFORM_DOCKER_IMAGE_OPTION}" "${_TERRAFORM_APPLICATION_COUNT_OPTION}"

what i expect is the terraform plan to work without parameters when the vars are unset, or use the respective -var strings when they are setted up

1
what value do you have for _TERRAFORM_DOCKER_IMAGE_OPTION? Note that ${_TERRAFORM_DOCKER_IMAGE_OPTION:-} will produce a null if the variable is not set. Usually, that syntax is used like ${_TERRAFORM_DOCKER_IMAGE_OPTION:-myDefaultValue} . Sorry, no experience with terraform. Good luck!shellter
What do your bash script look like ?Chargaff

1 Answers

0
votes

Here you go.

Sample output when run... as you can see i just echo out the terraform plan command plus the variables..

export TF_VAR_region=eu-west-1
export TF_VAR_ami=ami-12434555666633
export TF_VAR_name=development

bash-3.2$ ./terraform.sh 
terraform plan  -var="region=eu-west-1" -var="ami=ami-12434555666633" -var="name=development"
#! /bin/bash

VarsArray=()

if [[ -z "$TF_VAR_region"  ]]
then
      echo "\$TF_VAR_region is empty"
else
      ### add to terraform command array
      VarsArray+=('-var="region='$TF_VAR_region'"')

fi

if [[ -z "$TF_VAR_ami" ]]
then
      echo "\$TF_VAR_ami is empty"
else
  ### add to terraform command array
  VarsArray+=('-var="ami='$TF_VAR_ami'"')

fi

if [[  -z "$TF_VAR_name"  ]]
then
      echo "\$TF_VAR_name is empty"
else
  ### add to terraform command array
  VarsArray+=('-var="name='$TF_VAR_name'"')

fi
tfCommand=$(printf " %s " "${VarsArray[@]}")
tfCommand=${tfCommand:1}
echo "terraform plan " $tfCommand

If you commit a certain variable... or leave them out all together, you get your normal... terraform plan command

bash-3.2$ unset TF_VAR_ami
bash-3.2$ ./terraform.sh 
$TF_VAR_ami is empty
terraform plan  -var="region=eu-west-1" -var="name=development"



unset TF_VAR_region
unset TF_VAR_ami
unset TF_VAR_name
./terraform.sh                     
$TF_VAR_region is empty
$TF_VAR_ami is empty
$TF_VAR_name is empty
terraform plan