DEV Community

Bartłomiej Danek
Bartłomiej Danek

Posted on • Originally published at bard.sh

for_each over tuple in Terraform

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
  })
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Originally published at https://bard.sh/posts/for_each/

Top comments (0)