Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform - creating multiple buckets

Creating a bucket is pretty simple.

resource "aws_s3_bucket" "henrys_bucket" {
  bucket                  = "${var.s3_bucket_name}"
  acl                     = "private"
  force_destroy           = "true"
}

Initially I thought I could create a list for the s3_bucket_name variable but I get an error:

Error: bucket must be a single value, not a list

-

variable "s3_bucket_name" {
  type = "list"
  default  = ["prod_bucket", "stage-bucket", "qa_bucket"]
}

How can I create multiple buckets without duplicating code?

like image 397
hfranco Avatar asked Jun 07 '26 10:06

hfranco


1 Answers

You can use a combination of count & element like so:

variable "s3_bucket_name" {
  type    = "list"
  default = ["prod_bucket", "stage-bucket", "qa_bucket"]
}

resource "aws_s3_bucket" "henrys_bucket" {
  count         = "${length(var.s3_bucket_name)}"
  bucket        = "${element(var.s3_bucket_name, count.index)}"
  acl           = "private"
  force_destroy = "true"
}

Edit: as suggested by @ydaetskcoR you can use the list[index] pattern rather than element.

variable "s3_bucket_name" {
  type    = "list"
  default = ["prod_bucket", "stage-bucket", "qa_bucket"]
}

resource "aws_s3_bucket" "henrys_bucket" {
  count         = "${length(var.s3_bucket_name)}"
  bucket        = "${var.s3_bucket_name[count.index]}"
  acl           = "private"
  force_destroy = "true"
}
like image 140
Conor Mongey Avatar answered Jun 10 '26 08:06

Conor Mongey