You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform模板生成IAM策略时标签值映射错误问题咨询

Terraform templatefile渲染IAM策略标签映射错误修复方案

1. 确认本地变量定义

首先确保本地标签约束变量定义正确:

locals {
  enforce_tags = {
    Environment = ["development", "production"]
    Application = ["app-01", "app-02"]
  }
}

2. 编写IAM策略模板

新建模板文件(如iam_policy.tpl),直接在模板内部遍历标签键值对,无需使用Terraform层的for_each或dynamic块:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": [
        "ec2:RunInstances",
        "ec2:CreateTags"
      ],
      "Resource": "*",
      "Condition": {
        "ForAnyValue:StringNotEquals": {
          %{for tag_key, allowed_values in enforce_tags ~}
          "aws:ResourceTag/${tag_key}": ${jsonencode(allowed_values)}${if tag_key != keys(enforce_tags)[length(keys(enforce_tags))-1] then "," else ""}
          %{endfor ~}
        }
      }
    }
  ]
}

3. 调用templatefile生成单个JSON文件

使用local_file资源渲染输出单个策略文件:

resource "local_file" "iam_tag_policy" {
  filename = "${path.module}/enforce_tag_policy.json"
  content  = templatefile("${path.module}/iam_policy.tpl", {
    enforce_tags = local.enforce_tags
  })
}

生成效果验证

最终输出的JSON文件符合预期:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": [
        "ec2:RunInstances",
        "ec2:CreateTags"
      ],
      "Resource": "*",
      "Condition": {
        "ForAnyValue:StringNotEquals": {
          "aws:ResourceTag/Environment": ["development","production"],
          "aws:ResourceTag/Application": ["app-01","app-02"]
        }
      }
    }
  ]
}

内容的提问来源于stack exchange,提问作者Rostyslav Malenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:45:07