Bernard Pietraga

Bash array as a Terraform list of strings input variable

Bash Array Terraform

So terraform supports string list assigment to new input variable but not the bash array format. But during the time of writing.

Lets say that we have bash array like this one below

BASH_ARRAY=( "a" "b" "c" )

And we want to pass the bash array to terraform variable declaration which is list of strings.

variable "example" {
  type = list(string)
}

To do it we need to transform the bash array to string format which will look like this:

"[\"a\","\b\",\"c\"]"

To do it use the bash below

# define array
BASH_ARRAY=( "a" "b" "c" )

# convert array to serialized list
ARRAY_WITH_QUOTES=()
for ENTRY in "${BASH_ARRAY[@]}";
do
  ARRAY_WITH_QUOTES+=( "\"${ENTRY}\"" )
done
TERRAFORM_LIST=$(IFS=,; echo [${ARRAY_WITH_QUOTES[*]}])

# pass it to the teraform
terraform plan -var example=$TERRAFORM_LIST

Done, this way you can use bash array as terraform list of string variable