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
相关产品推荐
相关产品推荐

