use*_*679 5 amazon-web-services terraform
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
}
Run Code Online (Sandbox Code Playgroud)
错误:
At column 1, line 1: output of an HIL expression must be a string, or a single list (argument 2 is TypeList) in:
Run Code Online (Sandbox Code Playgroud)
我尝试了 join 函数,但我需要输出为列表["a","b","c"]
join 函数给出类似的输出["a,b,c"]
我jsonencode
用template_file
首先创建下面的json文件
$ cat s3_policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": ${iam_action}
},
"Effect": "Allow",
"Sid": ""
}
]
}
Run Code Online (Sandbox Code Playgroud)
更新 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}"
}
Run Code Online (Sandbox Code Playgroud)
跑 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>"
Run Code Online (Sandbox Code Playgroud)
参考:
jsonencode(item) - 返回给定项目的 JSON 编码表示,它可以是字符串、字符串列表或从字符串到字符串的映射。请注意,如果项目是字符串,则返回值包括双引号。
我不能直接"${var.iam_action}"
在 in 中使用 vars 的原因template_file
解释如下:
vars -(可选)模板内插值的变量。请注意,变量必须都是原语。直接引用列表或映射将导致验证错误。
归档时间: |
|
查看次数: |
4972 次 |
最近记录: |