1

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

belkor
  • 15
  • 4

1 Answers1

4

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.

yvesonline
  • 4,609
  • 2
  • 21
  • 32
  • I think @yvesonline is right, you need to create a general template to fill all attributes, one more thing I think we need improve is that add if statement to check null or not when ever an attribute has been assigned, because follow the question, not every object has the same attribute – Tho Quach Apr 15 '21 at 09:31
  • This works, but it there a way to extend this so that if I don't have a value for `acl` in bucket1 to use a default value from a variable? – belkor Apr 16 '21 at 08:43