如何遍历 s3 存储桶列表并为每个存储桶创建和附加多个策略?

How to loop through a list of s3 buckets and create and attach a number of policies for each bucket?

我正在学习 Terraform 模块,我的 objective 是构建接收 s3 存储桶集合的模块,然后创建并应用一些 iam 策略。

到目前为止,我尝试的是使用某种 for 循环,在其中生成策略并将它们附加到存储桶。作为参考,我的代码看起来像这样:

data "aws_iam_policy_document" "foo_iam_policy" {
  statement {
    sid       = ""
    effect    = "Allow"
    resources = [
    for arn in var.s3_buckets_arn :
    "${arn}/*"
    ]

    actions = [
      "s3:GetObject",
      "s3:GetObjectVersion",
    ]
  }

  statement {
    sid       = ""
    effect    = "Allow"
    resources = var.s3_buckets_arn
    actions = ["s3:*"]
  }
}


resource "aws_iam_policy" "foo_iam_policy" {
  name        = "foo-iam-policy"
  path        = "/"
  description = "IAM policy for foo to access S3"
  policy      = data.aws_iam_policy_document.foo_iam_policy.json
}

data "aws_iam_policy_document" "foo_assume_rule_policy" {
  statement {
    effect  = "Allow"
    actions = [
      "sts:AssumeRole"]

    principals {
      type        = "AWS"
      identifiers = [
        var.foo_iam_user_arn]
    }
    condition {
      test     = "StringEquals"
      values   = var.foo_external_ids
      variable = "sts:ExternalId"
    }
  }
}

resource "aws_iam_role" "foo_role" {
  name               = "foo-role"
  assume_role_policy = data.aws_iam_policy_document.foo_assume_rule_policy.json
}

resource "aws_iam_role_policy_attachment" "foo_attach_s3_policy" {
  role       = aws_iam_role.foo_role.name
  policy_arn = aws_iam_policy.foo_iam_policy.arn
}

data "aws_iam_policy_document" "foo_policy_source" {
  for_each = toset(var.s3_buckets_arn)
  //  arn = each.key
  statement {
    sid    = "VPCAllow"
    effect = "Allow"

    resources = [
      each.key,
      "${each.key}/*",
    ]

    actions = [
      "s3:*"]

    condition {
      test     = "StringEquals"
      variable = "aws:SourceVpc"
      values   = [
        "vpc-01010101"]
    }

    principals {
      type        = "*"
      identifiers = [
        "*"]
    }
  }
}

我不知道我的尝试是否有意义,或者是否有更好的方法来遍历存储桶并生成策略。我的问题是:对于想要提供存储桶列表并遍历它们以附加策略的情况,最佳实践是什么?

附带说明一下,我的方法遇到了错误:

The “for_each” value depends on resource attributes that cannot be determined (Terraform)

要将 存储桶策略 附加到存储桶,您应该使用 aws_s3_bucket_policy, not aws_iam_policy_document. Also if the buckets already exist, probably it would be better to fetch their data first using data source aws_s3_bucket:

data "aws_s3_bucket" "selected" {
  # s3_buckets_names easier to use then s3_buckets_arns 
  for_each = toset(var.s3_buckets_names)

  bucket = each.value
}

然后,您可以遍历选定的存储桶并将您的策略​​添加到其中:

resource "aws_s3_bucket_policy" "bucket_policie" {

  for_each = data.aws_s3_bucket.selected

  bucket = each.key

  policy = "your policy document"
}