【问题标题】:Create AWS IAM Policy using Function var{count.index} in file() in Terraform在 Terraform 的 file() 中使用函数 var{count.index} 创建 AWS IAM 策略
【发布时间】:2019-08-14 03:40:57
【问题描述】:
  1. 我正在创建一个以 .json 格式存储的 IAM 策略列表。
  2. 我只有 1 个资源块,通过使用 count = length(count) 我想创建一个多 IAM 策略。
  3. 策略以 .json 格式存储。我在 Terraform 中使用 file() 来指代它们。

如果我创建一个多资源块,程序就可以工作。

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")}"

变量.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")}

【问题讨论】:

标签: list file variables terraform


【解决方案1】:

乍一看没有问题。但是仍然有几种方法可以解决文件路径问题。

${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]}"))}"

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2018-04-13
    • 2020-11-11
    • 2020-12-16
    • 2020-04-25
    • 2021-06-04
    • 2020-08-12
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多