在 AWS 策略上的 Terraform 中使用模板文件,该策略使用 IAM 策略变量

mat*_*mat 2 amazon-web-services terraform terraform-template-file terraform-provider-aws aws-policies

我正在尝试使用 Terraform 在 AWS 中构建云基础设施。我想为 S3 存储桶添加一个策略,该策略通过templatefileterraform 的功能使用基于属性的授权 (ABAC)。我的问题是 terraform 和 AWS 使用的变量语法是相同的 ( ${...})。

这是策略模板:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowReadRole1",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::${bucketName}/*",
            "Effect": "Allow",
            "Principal": "*",
            "Condition": {
                "s3:ExistingObjectTag/myid": "${aws:PrincipalTag/myid}"
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

terrafrom 文件的相关部分是:

resource "aws_s3_bucket_policy" "mybuckets-policy" {
  bucket = aws_s3_bucket.mybuckets[count.index].bucket
  policy = templatefile("${path.module}/bucket-policy.json", {
    bucketName = aws_s3_bucket.mybuckets[count.index].bucket
  })
  count = 2
}
Run Code Online (Sandbox Code Playgroud)

所以我想要的是${bucketName}模板的一部分被 terraform 替换,同时保留 AWS 表达式${aws:PrincipalTag/user-id}。但是在上面的配置上运行 terraform 会导致错误消息

调用函数“templatefile”失败:./bucket-policy.json:14,49-50:插值表达式后出现额外字符;期望用右大括号结束插值表达式,但发现了额外的字符。

如果我在模板中放置另一个项目${foobar}而不指定其值,则错误消息为

“vars”参数的值无效:vars 映射不包含键“foobar”,引用于 ./bucket-policy.json:11,30-36。

如何使 terraform 对模板文件进行部分评估,同时保持所有其他项目完好无损?

Abh*_*aya 5

在上面的示例中,语法 ${} 将导致 Terraform 尝试将字段计算为插值函数。由于您想按字面意思使用该值,而不是作为插值函数,因此需要使用两个 $ 符号进行双重转义。

$${aws:PrincipalTag/user-id}