我正在尝试在 IAM 策略资源块中循环获取字符串值以允许 rds IAM 身份验证。我的资源定义是:
resource "aws_iam_policy" "rds_iam_authentication"{
name = "${title(var.environment)}RdsIamAuthentication"
policy = templatefile(
"${path.module}/iam_policy.json",
{
aws_account_id = data.aws_caller_identity.current.account_id
region = var.region
environment = var.environment
iam_rds_pg_role_name = var.iam_rds_pg_role_name
}
)
}
iam_rds_pg_role_name
in的变量定义terraform.tfvars
如下:
region = "eu-west-3"
environment = "env_name"
iam_rds_pg_role_name = ["read_only_role", "full_role"]
aws_account_id = "1234567890"
IAM 策略模板文件为:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"rds-db:connect"
],
"Resource": [
%{ for rds_role in iam_rds_pg_role_name ~}
"arn:aws:rds-db:${region}:${aws_account_id}:dbuser:*/${rds_role}"
%{ endfor ~}
]
}
]
}
我收到一条错误消息
错误:“policy”包含无效的 JSON:数组元素后有无效字符“”
我很确定问题出在 json 编码上,但是当尝试jsonencode
像下面这样在 json 中进行 arn 定义时,错误仍然存在:
%{ for rds_role in iam_rds_pg_role_name ~}
jsonencode("arn:aws:rds-db:${region}:${aws_account_id}:dbuser:*/${rds_role}")}
%{ endfor ~}
希望能有人解释我遗漏了什么,或者给我指明正确的方向。
提前致谢
答案1
在您的 IAM 策略模板文件中,以下项目的尾部逗号缺失Resource
:
...
"Resource": [
%{ for rds_role in iam_rds_pg_role_name ~}
"arn:aws:rds-db:${region}:${aws_account_id}:dbuser:*/${rds_role}",
there should be a comma here ^
%{ endfor ~}
]
...
您可以循环遍历中的索引和项目iam_rds_pg_role_name
,如果索引小于,则添加逗号length(iam_rds_pg_role_name) - 1
:
...
"Resource": [
%{ for index, rds_role in iam_rds_pg_role_name ~}
"arn:aws:rds-db:${region}:${aws_account_id}:dbuser:*/${rds_role}"%{ if idx < length(iam_rds_pg_role_name) - 1 },%{ endif }
%{ endfor ~}
]
...
结果:
Terraform will perform the following actions:
# aws_iam_policy.rds_iam_authentication will be created
+ resource "aws_iam_policy" "rds_iam_authentication" {
+ arn = (known after apply)
+ id = (known after apply)
+ name = "Env_nameRdsIamAuthentication"
+ name_prefix = (known after apply)
+ path = "/"
+ policy = jsonencode(
{
+ Statement = [
+ {
+ Action = [
+ "rds-db:connect",
]
+ Effect = "Allow"
+ Resource = [
+ "arn:aws:rds-db:eu-west-3:1234567890:dbuser:*/read_only_role",
+ "arn:aws:rds-db:eu-west-3:1234567890:dbuser:*/full_role",
]
},
]
+ Version = "2012-10-17"
}
)
+ policy_id = (known after apply)
+ tags_all = (known after apply)
}