从 terraform 中的任何类型获取特定键的值

Get the value for a specific key from any type in terraform

我目前正在使用如下变量类型 map(string) 来声明列表类型的电子邮件地址值。这很好用。但是我更喜欢使用 map(string,list) 类型而不是 map(string,string).

variable "email_addresses" {
  type        = map(string)
  default = {
    team1    = "test1@abc.com,test2@abc.com"
    team2    = "test3@abc.com,test4@abc.com"
}

data "template_file" "policies" {
  for_each = local.policies
  template = file(format("${path.module}/policies/%s.yaml", each.key))
  vars = {
    recipients             = lookup(var.email_addresses, element(split("-", each.key), 0), "")
    tag                    = local.tags["name"]
  }
}

有没有办法通过将变量设置为以下任何类型来获取密钥的值(即收件人)。

variable "email_addresses" {
  type        = any
  default = {
    team1 = [
      "test1@abc.com",
      "test2@abc.com"
    ], 
    team2 = [
     "test3@abc.com",
     "test4@abc.com"
    ], 
  }
}

您可以通过以下方式优化您的变量声明类型:

variable "email_addresses" {
  type        = map(list(string))
  default = {
    team1 = [
      "test1@abc.com",
      "test2@abc.com"
    ], 
    team2 = [
     "test3@abc.com",
     "test4@abc.com"
    ], 
  }
}

然后,您可以使用 yamlencode function.

确保 YAML 文件中的收件人数组格式正确
data "template_file" "policies" {
  for_each = var.email_addresses
  template = file(format("${path.module}/policies/%s.yaml", each.key))
  vars = {
    recipients             = each.value
    tag                    = local.tags["name"]
  }
}

并在您的模板中:

---
${yamlencode(recipients)}

请注意您的配置的几个使用警告是 lookup 应该只在您想要提供默认值时使用,如果不存在密钥,并且应该更新 template_file 数据与 templatefile function.