【问题标题】:Referencing Element Of List In Terraform Templated Yaml File在 Terraform 模板化 Yaml 文件中引用列表元素
【发布时间】:2022-01-18 21:57:29
【问题描述】:

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

变量:

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

template_file sn-p:

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

yaml 文件 sn-p:

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.

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

【问题讨论】:

  • 我认为您遇到的问题与一些关于每个函数和模板的预期内容的小细节有关。您希望在最后看到什么,映射到“xyz”([“myrecipientB”])的完整元素列表?“xyz”(“myrecipientB”)列表中的第一个元素?

标签: terraform


【解决方案1】:

我认为问题可能在于如何定义事物以及如何将事物从 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

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2023-03-03
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多