Terraform - dynamically create resources using a nested map

Viewed 798

I'm trying to dynamically create s3 buckets using a map, but changing certain parameters for each bucket.

  custom_s3_buckets = {
  "bucket1" = {
    "bucket" = "aaaa",
    "acl" = "private"
    },
  "bucket2" = {
    "bucket" = "bbbb",
    "versioning" = true 
    },
  "bucket3" = {
    "bucket" = "cccc" 
    }
  }

The resource should expect variables:

resource "aws_s3_bucket" "s3_buckets" {
  bucket     = var.bucket_name
  acl        = var.acl
  versioning = {
    enabled = var.versioning
  }
}

And the variables should be filled with the above custom_s3_buckets map and create as many buckets as there are keys in the map, filling only changed values and leaving the rest as default in variables.tf

variable "bucket_name" {
  type = string
}

variable "acl" {
  type = string
  default = "private"
}

variable "versioning" {
  type = bool
  default = false
}

I assume I need a for_each here, but can't seem to make it work.

Relevant sources: Terraform - iterate over nested map

1 Answers

You'll need a map for each bucket and then a definition of your aws_s3_bucket like this:

resource "aws_s3_bucket" "s3_buckets" {
  for_each = {
    bucket_1 = {
      bucket = "aaaa",
      acl = "private",
      versioning = false
    },
    bucket_2 = {
      bucket = "bbbb",
      acl = "private",
      versioning = true
    }
  }

  bucket = each.value.bucket
  acl    = each.value.acl

  versioning {
    enabled = each.value.versioning
  }
}

See also The for_each Meta-Argument page in the official TF documentation.

Related