for_each over tuples in terraform
Terraform does not allow to iterate through a tuple with for_each, but you can create one in the fly.
locals {
cron_jobs = [
{
name = "every-15-minutes"
command = "rake send:sms:notification"
cron = "*/15 * * * * *"
},
{
name = "every-30-minutes"
command = "rake send:sqs:notification"
cron = "*/30 * * * * *"
}
]
}
resource "nomad_job" "cron_jobs" {
for_each = { for cj in local.cron_jobs : cj.name => cj }
jobspec = templatefile("cron_job.tpl", {
name = each.key
command = each.value.command
cron = each.value.cron
})
}
Inside the block, each.key is the map key (cj.name) and each.value is the full object.
for_each over a plain list
For a simple list of strings, convert it to a set first with toset() - this is required because sets have no index.
variable "buckets" {
default = ["logs", "backups", "artifacts"]
}
resource "aws_s3_bucket" "this" {
for_each = toset(var.buckets)
bucket = each.key
}
each.key and each.value are identical when iterating a set.
for_each over a map
variable "buckets" {
default = {
logs = "us-east-1"
backups = "eu-west-1"
}
}
resource "aws_s3_bucket" "this" {
for_each = var.buckets
bucket = each.key
region = each.value
}
Originally published at https://bard.sh/posts/for_each/
Top comments (0)