variable "iam_action" {
type = "list"
default = ["ec2.amazonaws.com","ecs.amazonaws.com"]
}
resource "aws_iam_role" "s3_role" {
name = "abcd"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": [ "${var.iam_action}"
]
},
"Effect": "Allow,
"Sid": ""
}
]
}
EOF
}
错误:
At column 1, line 1: output of an HIL expression must be a string, or a single list (argument 2 is TypeList) in:
我尝试了连接功能,但我需要输出为列表["a","b","c"]
连接函数提供类似["a,b,c"]
的输出
答案 0 :(得分:3)
我通过jsonencode
template_file
一起修复
首先在json文件下面创建
$ cat s3_policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": ${iam_action}
},
"Effect": "Allow",
"Sid": ""
}
]
}
更新tf文件
variable "iam_action" {
type = "list"
default = ["ec2.amazonaws.com", "ecs.amazonaws.com"]
}
data "template_file" "s3_role" {
template = "${file("${path.module}/s3_policy.json")}"
vars {
iam_action = "${jsonencode(var.iam_action)}"
}
}
resource "aws_iam_role" "s3_role" {
name = "abcd"
assume_role_policy = "${data.template_file.s3_role.rendered}"
}
运行template plan
+ aws_iam_role.s3_role
arn: "<computed>"
assume_role_policy: "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": \"sts:AssumeRole\",\n \"Principal\": {\n \"Service\": [\"ec2.amazonaws.com\",\"ecs.amazonaws.com\"]\n },\n \"Effect\": \"Allow\",\n \"Sid\": \"\"\n }\n ]\n}\n"
create_date: "<computed>"
force_detach_policies: "false"
name: "abcd"
path: "/"
unique_id: "<computed>"
参考:
jsonencode(item) - 返回给定项的JSON编码表示,可以是字符串,字符串列表,也可以是从字符串到字符串的映射。 请注意,如果该项是字符串,则返回值包含双引号。
我在"${var.iam_action}"
中无法直接使用template_file
的变种的原因在此解释:
vars - (可选)用于模板内插的变量。请注意,变量必须都是基元。 对列表或地图的直接引用会导致验证错误。