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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.