count = length(count)
创建多个IAM策略。file()
在Terraform中指代它们。如果我创建了多个资源块,该程序将起作用。
main.tf:
resource "aws_iam_role_policy" "cloudcheckr" {
count = "${length(var.file_name)}"
role = "${aws_iam_role.cloudcheckr.id}" // An IAM role is created in another resource block
name = "${var.file_name[count.index]}"
policy = "${file("${var.file_name[count.index]}.json")}"
variables.tf:
variable "file_name" {
type = "list"
default = [
"xxxxxx",
"xxxxxx",
"xxxxxx",
"xxxxxx",
]
}
预期结果:
已创建多个IAM策略。
实际结果:
aws_iam_role_policy.cloudcheckr: 3 error(s) occurred:
* aws_iam_role_policy.cloudcheckr[3]: file: open iam_policy_cloudcheckr_security.json: no such file or directory in:
${file("${var.file_name[count.index]}.json")}
* aws_iam_role_policy.cloudcheckr[0]: file: open iam_policy_cloudcheckr_cloudwatchflowlogs.json: no such file or directory in:
${file("${var.file_name[count.index]}.json")}
* aws_iam_role_policy.cloudcheckr[2]: file: open iam_policy_cloudcheckr_inventory.json: no such file or directory in:
${file("${var.file_name[count.index]}.json")}
答案 0 :(得分:0)
从第一个角度看没有问题。但是,仍然有几种方法可以解决文件路径问题。
${path.module}在从模块内部使用file()
时很有用,您通常希望相对于模块库建立路径,例如:file("${path.module}/file")
。
因此您的代码可以更改为
resource "aws_iam_role_policy" "cloudcheckr" {
count = "${length(var.file_name)}"
role = "${aws_iam_role.cloudcheckr.id}" // An IAM role is created in another resource block
name = "${var.file_name[count.index]}"
policy = "${file("${path.module}/${var.file_name[count.index]}.json")}"
}
如果这不起作用,请尝试使用format()
policy = "${file(format("%s/%s.json", "${path.module}, ${var.file_name[count.index]}"))}"