简体   繁体   中英

Terraform 13, how to reference the output of a single instance of a module that uses count

I have a module that creates multiple buckets:

module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  count   = length(var.buckets)
  bucket  = "bucket-${var.buckets[count.index]}"
}

I'd like to apply a bucket policy to only one of those instances:

resource "aws_s3_bucket_policy" "policy" {
  bucket = module.s3_bucket.THAT_ONE_BUCKET_BY_NAME

  policy = jsonencode(
    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "AWS": [
                        "arn:aws:iam::1111111111:role/access-role"
                    ]
                },
                "Action": [
                    "s3:PutObject"

                ],
                "Resource": [
                    "arn:aws:s3:::THAT_ONE_BUCKET_BY_NAME",
                    "arn:aws:s3:::THAT_ONE_BUCKET_BY_NAME/*"
                ]
            }
        ]
    }
  )

what's the right way to do this in terraform 13?

You have to use index , such as 0, 1, 2, depending on length(var.buckets) . For example,

bucket = module.s3_bucket[0].name

When you use count in this module block, the symbol module.s3_bucket becomes a list of objects rather than just a single object representing one set of outputs.

Therefore in order to access the name of only one of them you'll need to know the index of the one you want to use and access it using the normal index syntax:

module.s3_bucket[0].name

(the above is assuming that your module has an output "name" which returns the bucket name.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM