在Terraform变量中的地图内进行映射

时间:2019-06-26 15:18:12

标签: variables terraform terraform-provider-aws

有人知道用代码片段表示是否可以在terraform变量的map变量内创建map变量吗?

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

如果有人对这是否可能或任何详细说明的文档有深刻的见解。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

是的,可以将map变量作为map变量键的值。您的变量只需要右缩进即可。另外,我也在提出访问该变量的方法。

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