【问题标题】:Map within a map in terraform variables地形变量中的地图内的地图
【发布时间】:2019-11-08 14:17:51
【问题描述】:

有谁知道是否有可能使用代码片段来表示我是否可以在 terraform 变量中的地图变量中创建地图变量?

variable "var" {
  type = map
  default = {
    firstchoice = {
      firstAChoice ="foo"
      firstBChoice = "bar"
    }
    secondchoice = {
      secondAChoice = "foobar"
      secondBChoice = "barfoo"
    }
  }
}

如果有人对这是否可能或任何详细说明的文档有任何见解,那就太好了。

【问题讨论】:

    标签: variables terraform terraform-provider-aws


    【解决方案1】:

    是的,可以将地图变量作为地图变量键的值。您的变量只需要正确的缩进。我还提供了访问该变量的方法。

    variable "var" {
      default = {
        firstchoice = {
          firstAChoice = "foo"
          firstBChoice = "bar"
        }
    
        secondchoice = {
          secondAChoice = "foobar"
          secondBChoice = "barfoo"
        }
      }
    }
    

    要访问映射键firstchoice 的整个映射值,您可以尝试关注

    value = "${var.var["firstchoice"]}"
    
    output:
    {
      firstAChoice = foo
      firstBChoice = bar
    }
    

    要访问该映射键的特定键(例如firstAChoice),您可以尝试

    value = "${lookup(var.var["firstchoice"],"firstAChoice")}"
    
    output: foo
    

    【讨论】:

    • 非常感谢!
    • 这种语法可行吗? ${var.var[firstchoice[firstAchoice]]}
    • 我只问因为我需要第三层地图
    • 这种变量需要设置什么类型?
    【解决方案2】:

    这种语法可能吗? ${var.var[firstchoice[firstAchoice]]}

    Terraform 0.12+ 无缝支持嵌套块。扩展@Avichal Badaya 的答案以使用示例进行解释:

    # Nested Variable
    
    variable "test" {
      default = {
        firstchoice = {
          firstAChoice = "foo"
          firstBChoice = "bar"
        }
    
        secondchoice = {
          secondAChoice = "foobar"
          secondBChoice = "barfoo"
        }
    
        thirdchoice = {
          thirdAChoice = {
              thirdBChoice = {
                  thirdKey = "thirdValue"
            }
          }
        }
      }
    }
    
    
    # Outputs
    
    output "firstchoice" {
      value = var.test["firstchoice"]
    }
    
    output "FirstAChoice" {
      value = var.test["firstchoice"]["firstAChoice"]
    }
    
    output "thirdKey" {
      value = var.test["thirdchoice"]["thirdAChoice"]["thirdBChoice"]["thirdKey"]
    }
    
    

    应用上述内容,您可以验证 Terraform 地图嵌套现在非常强大,这让很多事情变得更容易。

    # Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
    
    # Outputs:
    
    firstchoice = {
      "firstAChoice" = "foo"
      "firstBChoice" = "bar"
    }
    
    thirdKey = thirdValue 
    

    有关更复杂的结构和丰富的值类型,请参阅HashiCorp Terraform 0.12 Preview: Rich Value Types

    【讨论】:

    • 我喜欢这个更新的答案。它使代码更具可读性。是否可以使用点符号遍历地图?例如:var.test.firstchoice.firstAchoice?
    猜你喜欢
    • 2016-05-31
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2011-10-30
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多