在 terraform 中使用 for_each 时缺少资源实例密钥

Missing resource instance key when using for_each in terraform

我正在 terraform 中使用 for_each 创建多个 s3 存储桶。这是我正在使用的代码

resource "aws_s3_bucket" "s3_private" {
  for_each = var.git_repo_branch_env
  bucket   = each.value.override_domain_name == "" ?  each.value.sitename_prefix == "" ? each.value.domain_name : join(".", [each.value.sitename_prefix, each.value.domain_name]) : each.value.sitename_prefix == ""  ? each.value.override_domain_name : join(".", [each.value.sitename_prefix, each.value.override_domain_name])
  force_destroy = true
}

我想为创建的每个存储桶设置 ACL 属性,这是我尝试使用的代码

resource "aws_s3_bucket_acl" "s3_private_acl" {
  bucket = aws_s3_bucket.s3_private.bucket
  acl    = "private"
}

我收到以下错误消息

│ Error: Missing resource instance key │ │ on ../../modules/cloudfront-edge-auth-acp/main.tf line 149, in resource "aws_s3_bucket_acl" "s3_private_acl": │ 149: bucket = aws_s3_bucket.s3_private.bucket │ │ Because aws_s3_bucket.s3_private has "for_each" set, its attributes must be │ accessed on specific instances. │ │ For example, to correlate with indices of a referring resource, use: │ aws_s3_bucket.s3_private[each.key]

我收到错误消息是因为我的存储桶资源上有一个 for_each,我需要为每个存储桶添加 ACL 属性。但我不确定如何将 ACL 属性 添加到每个存储桶。

问题:如何将 ACL 属性 分配给使用 for_each 创建的每个存储桶?

如果您使用 for_each 创建了多个存储桶,您需要对 ACL 执行同样的操作:

resource "aws_s3_bucket_acl" "s3_private_acl" {
  for_each = aws_s3_bucket.s3_private
  bucket   = each.value.bucket
  acl      = "private"
}

在 Terraform 文档中对此有很好的解释:chaining for_each between resources