在Terraform的file()中使用函数var {count.index}创建AWS IAM策略

时间:2019-03-23 07:43:01

标签: list file variables terraform

  1. 我正在创建一个IAM策略列表,该列表以.json格式存储。
  2. 我只有1个资源块,我想使用count = length(count)创建多个IAM策略。
  3. 策略以.json格式存储。我使用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")}

1 个答案:

答案 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]}"))}"