在 Terraform 模板化 Yaml 文件中引用列表元素

Referencing Element Of List In Terraform Templated Yaml File

我正在尝试将列表映射传递给模板化的 yaml 文件,然后引用该列表的特定元素。我知道这利用了遗留的 template_file 类型,但我仍然很好奇为什么我所做的没有呈现。当我通过 locals 测试时,同样的逻辑工作正常。

变量:

variable "my_recipients" {
  description = "Recipients To Identify"
  type        = map(list(string))
  default = {
    abcd = [
      "myrecipientA"
    ],
    zyx = [
      "myrecipientB"
    ]
  }
}

template_file 片段:

data "template_file" "policies" {
  template = myfile.yaml
    recipients_all                    = jsonencode(var.my_recipients)
}

yaml 文件片段:

to:
  - ${jsondecode({recipients_all})["zyx"]} #Goal is to get the value myrecipientB

我希望获得值 myrecipientB,但我却收到错误:

Missing key/value separator; Expected an equals sign ("=") to mark the beginning of the attribute value.

如有任何建议,我们将不胜感激,因为这似乎是一个应该可行的简单想法,但我不确定我误解了什么。

我认为问题可能在于事物的定义方式以及从 Terraform 到模板的传递方式。模板本身似乎有一些小的语法错误。另外,模板文件希望插值的结果是一个字符串,以便它可以包含在渲染结果中。

这是对我有用的代码。

组合地形代码:

variable "my_recipients" {
  description = "Recipients To Identify"
  type        = map(list(string))
  default = {
    abcd = [
      "myrecipientA"
    ],
    zyx = [
      "myrecipientB"
    ]
  }
}

data "template_file" "policies" {
  template = file("myfile.tpl")
  vars = {
    recipients_all                    = jsonencode(var.my_recipients)
  }
}

# For debugging purposes
locals {
    recepients_all_encoded = jsonencode(var.my_recipients)
}

output "recepients_all_encoded" {
    value = local.recepients_all_encoded
}

output "template_content" {
    value = data.template_file.policies.rendered
}

已更新模板文件 (myfile.tpl)

to:
  - ${jsondecode(recipients_all)["zyx"][0]}

terraform 的结果运行

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

recepients_all_encoded = "{\"abcd\":[\"myrecipientA\"],\"zyx\":[\"myrecipientB\"]}"
template_content = <<EOT
to:
  - myrecipientB

EOT