地形变量中地图内的地图

Map within a map in terraform variables

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

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

如果有人知道这是否可行或有任何详细说明的文档,那就太好了。

是的,可以将地图变量作为地图变量键的值。您的变量只需要正确的缩进。此外,我正在寻找访问该变量的方法。

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

Would this syntax be possible? ${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