如何基于布尔值在Terraform的jsonencode中省略IAM策略指定Statement?
解决方案:动态生成IAM策略Statement数组
不用创建两个独立的IAM策略,直接利用Terraform的条件表达式和concat函数,就能根据特性标志var.rds_aurora_postgres_enabled动态决定是否包含针对Aurora Postgres的权限Statement。
修改后的代码示例
resource "aws_iam_policy" "coalesce_schedule_instance_policy" { name = "${local.namespace_coalesce}-coalesce-schedule-instance-policy" policy = jsonencode({ "Version": "2012-10-17", "Statement": concat( # 基础通用权限 Statement [ { "Effect": "Allow", "Action": [ "rds:DescribeDBInstances", "rds:DescribeDBClusters", "rds:ListTagsForResource", "dms:DescribeOrderableReplicationInstances", "dms:DescribeReplicationTasks", "dms:DescribeReplicationInstances", "dms:ListTagsForResource", ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "rds:StartDBInstance", "rds:StopDBInstance", ], "Resource": [ "${module.rds_sqlserver.db_instance_arn}" ] }, { "Effect": "Allow", "Action": [ "dms:ModifyReplicationInstance" ], "Resource": concat(values(aws_dms_replication_instance.dms_instance_bronze)[*].replication_instance_arn, values(aws_dms_replication_instance.dms_instance_silver)[*].replication_instance_arn, values(aws_dms_replication_instance.dms_instance_on_prem_to_rds)[*].replication_instance_arn) }, { "Effect": "Allow", "Action": [ "dms:ModifyReplicationTask", "dms:MoveReplicationTask", "dms:StartReplicationTask", "dms:StopReplicationTask", ], "Resource": concat(values(aws_dms_replication_task.onprem_to_s3_replication_task)[*].replication_task_arn, values(aws_dms_replication_task.s3_to_rds_sqlserver_replication_task)[*].replication_task_arn, values(aws_dms_replication_task.s3_to_rds_aurora_postgres_replication_task)[*].replication_task_arn, values(aws_dms_replication_task.s3_silver_to_s3_gold_replication_task)[*].replication_task_arn) }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "${module.s3_config.bucket.arn}/*" } ], # 根据特性标志决定是否添加 Aurora Postgres 权限 Statement var.rds_aurora_postgres_enabled ? [ { "Effect": "Allow", "Action": [ "rds:StartDBCluster", "rds:StopDBCluster" ], "Resource": [ module.rds_aurora_postgres.primary_rds_cluster_arn ] } ] : [] ) }) tags = local.common_tags }
关键说明
- 拆分Statement数组:把固定的通用权限放在一个数组里,把需要动态控制的Aurora Postgres权限单独作为一个条件数组。
- 条件判断:用
var.rds_aurora_postgres_enabled ? [statement] : []实现——当标志为true时,将该权限Statement加入数组;为false时,加入空数组(相当于不添加)。 - 避免模块引用报错:如果你的
rds_aurora_postgres模块是根据var.rds_aurora_postgres_enabled条件创建的(即禁用时模块不会部署),直接引用module.rds_aurora_postgres.primary_rds_cluster_arn会报错。这种情况下,需要给模块添加一个输出,当禁用时返回空字符串,或者用try(module.rds_aurora_postgres.primary_rds_cluster_arn, "")来容错,但更稳妥的是确保模块在禁用时输出合法的空值。
内容的提问来源于stack exchange,提问作者Ross Bush
相关产品推荐
相关产品推荐

