【问题标题】:Get the value for a specific key from any type in terraform从 terraform 中的任何类型获取特定键的值
【发布时间】:2020-10-06 20:02:48
【问题描述】:

我目前正在使用如下的变量类型 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"
    ], 
  }
}

【问题讨论】:

    标签: terraform terraform-provider-aws


    【解决方案1】:

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

    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 仅应在您希望在不存在键的情况下提供默认值时使用,并且应使用 templatefile function 更新 template_file 数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 2018-01-25
      • 2021-12-24
      • 1970-01-01
      • 2022-08-07
      • 2023-04-09
      • 2021-05-22
      相关资源
      最近更新 更多