Skip to content

Instantly share code, notes, and snippets.

@arnobroekhof
Last active September 30, 2020 14:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save arnobroekhof/ae51624702462642f6e2100a9838d282 to your computer and use it in GitHub Desktop.
Save arnobroekhof/ae51624702462642f6e2100a9838d282 to your computer and use it in GitHub Desktop.
Terraform 0.11.x loop through a map and create files with content based on a maps --> key, value
variable "object_list" {
type = "map"
default = {
content1 = "this is example content 1",
content2 = "this is example content 2"
}
}
resource "local_file" "local_files" {
count = "${length(var.object_list)}" # perform this action based on the amount of items in the map
filename = "${element(keys(var.object_list), count.index)}" # lookup the key name based on the current count index.
content = "${lookup(var.object_list, "${element(keys(var.object_list), count.index)}")}" # lookup the key's value based on a double interpolation.
}
@charlie-charlie
Copy link

as we're using count to loop through a map, just like filename we used count.index, why not write content as following:
count = "${element(values(var.object_list), count.index)}"
? thx

@arnobroekhof
Copy link
Author

Because count is the number it needs to iterate over the items and we need to know how many times it needs to iterate.
In you’re proposal it would give you a undefined error or type mismatch ( depending on the terraform version you are using )

Also this gist is a bit outdated because in terraform 0.12 for and foreach are introduced

@max-lobur
Copy link

Thank you so much! Saved my day

@confiq
Copy link

confiq commented Jan 23, 2020

how would you do this in 0.12?

@itskornbailey
Copy link

how would you do this in 0.12?

You dont need to do this in terraform 12, terraform 12 introduces for and foreach which makes the approach much easier and cleaner
https://www.terraform.io/docs/configuration/expressions.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment