3

So, basically I want to be able to iterate in my Bash script template file over the array, that I initialise in Terraform.

The template file is used as user_data for AWS instance:

resource "aws_instance" "my_instance" {
    
...

  user_data = templatefile("${path.module}/${var.template_file}",
    {
      my_array    = ["item1", "item2"]
  })

...

}

Here is my template file:

#!/usr/bin/env bash

printf "%s\n" "$${my_array[@]}" > my_array.txt

And when I execute cat my_array.txt it gives me no content.

I can know that workaround might be to define my_array as a string and after that parse it in Bash to an array, but I curios whether is it possible to avoid that and get kinda native variable interpolation here.

Any help or hints will be appreciated. Thanks!

1 Answer 1

5

Hmmmm. Seems like it's impossible yet. The shortest solution would be to pass the array as a string in the following way:

my_array    = join(",",["item1", "item2"])

and use that source to init required array:

IFS=',' read -r -a bash_array <<< "${my_array}"
printf "%s\n" "$${my_array[@]}" > my_array.txt

now your array's items should be listed in the file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.