3

I'd need to iterate through a list of variables in local-exec provider. Is that possible?

variables.tf:

variable "items" {
  default = []
}

main.tf:

resource "null_resource" "loop_list" {
  provisioner "local-exec" {
    interpreter = ["/bin/bash", "-c"]
    command = <<EOF
      for i in ${join(' ', var.items)}
        print $i
      done
EOF
  }
}
3
  • Have you tried this? :) Commented Mar 2, 2022 at 9:28
  • I'm just trying to see it in action. I wouldn't think this "pseudocode" could work well on the first try :) Commented Mar 2, 2022 at 9:39
  • Ok, then: I would probably create a local variable with join and whatever you wanted to achieve. Second step would be to use templatefile to swap the variable you specify in the script with the value of the local variable. The last step would be to run the script instead of providing it with heredoc syntax. But there are sure multiple possible approaches. Commented Mar 2, 2022 at 9:43

1 Answer 1

5

You should be able to use environment. Something like this:

variable "items" {
  default = ["item1", "item2"]
}

resource "null_resource" "loop_list" {
  provisioner "local-exec" {
    command     = "for item in $ITEMS; do echo $item >> test-file; done"
    environment = { ITEMS = join(" ", var.items) }
  }
}

Where terraform apply and cat test-file yields:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.