Terraform - creating multiple buckets

2019-06-14 06:14发布

问题:

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?

回答1:

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"
}