如何在 terraform 中访问 aws_iam_user_policy 资源的策略参数中列表变量的所有元素

how to access all elements of a list variable in the policy argument of aws_iam_user_policy resource in terraform

我在 terraform 中有一个 aws_iam_user_policy 资源,如下所示:

resource "aws_iam_user_policy" "pol" {
  name = "policy"
  user = aws_iam_user.singleuser.name

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:List*"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:s3:::toybucket-development/*",
        "arn:aws:s3:::toybucket-staging/*",
        "arn:aws:s3:::toybucket-production/*"
      ]
    }
  ]
}
EOF
}

带有 developmentstagingproduction 的资源是我希望通过使用值为 development 的列表变量放在一行中的东西, stagingproduction 并以某种方式循环遍历它们,但我不确定如何在 EOF 中执行此操作。我知道通常你可以遍历这样的列表变量,但这是在正常的地形中,而不是当你有这个 EOF 和一个代表 json 的字符串时。有人知道解决方案吗?

您可以使用 Terraform 模板和 templatefile 函数轻松完成此操作。 templatefile 函数调用将显示为:

resource "aws_iam_user_policy" "pol" {
  name = "policy"
  user = aws_iam_user.singleuser.name

  policy = templatefile("${path.module}/policy.tmpl", { envs = ["development", "staging", "production"] }
}

函数的 documentation 可能会有帮助。

模板将显示为:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:List*"
      ],
      "Effect": "Allow",
      "Resource": [
        %{~ for env in envs ~}
        "arn:aws:s3:::toybucket-${env}/*"%{ if env != envs[length(envs) - 1] },%{ endif }
        %{~ endfor ~}
      ]
    }
  ]
}

仅当逗号不是最后一个元素时才检查末尾是否添加逗号,以确保 JSON 格式语法不是很好。但是,在 Terraform DSL 中无法轻松检查 list/slice(后者隐式派生自 Golang)是否是最后一个元素,并且使用 jsonencode 需要将整个 ARN 放入变量列表中。

如果envs = ["arn:aws:s3:::toybucket-development/*", "arn:aws:s3:::toybucket-staging/*", "arn:aws:s3:::toybucket-production/*"],那么你可以jsonencode(envs)