Terraform:变量的动态属性(以splat语法显示)

Thi*_*Guy 5 terraform hcl

在terraform HCL中,是否可以从变量动态引用对象的属性?

即:

variable "attribute" {
  type = "string"
}

data "terraform_remote_state" "thing" {
  not_really_important
}

output "chosen" {
  value = "${data.terraform_remote_state.thing.$var.attribute}"
}
Run Code Online (Sandbox Code Playgroud)

更具体到我的情况,我希望用splat语法做到这一点:

variable "attribute" {
  type = "string"
}

data "terraform_remote_state" "thing" {
  count = 3 # really this is also a variable
  not_really_important
}

output "chosen" {
  value = "${data.terraform_remote_state.thing.*.$var.attribute}"
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了类似的东西lookup(data.terraform_remote_state.thing, var.attribute)(对于splat问题),lookup(element(data.terraform_remote_state.*, count.index), var.attribute)但他们都抱怨我的属性引用不完整/错误的形式.

Mik*_*ike 0

地形版本 0.12

https://www.terraform.io/upgrade-guides/0-12.html#remote-state-references

您可以terraform_remote_state直接以地图形式访问输出。

以地图 data.terraform_remote_state.thing.outputs 的形式访问状态文件输出

output "chosen" {
  value = "${lookup(data.terraform_remote_state.thing.outputs, "property1")}"
}
Run Code Online (Sandbox Code Playgroud)

Terraform 版本 0.11 或更低版本

如果您可以更改outputs状态文件中的变量,则可以将您感兴趣的变量设置为 a map,然后通过索引查找该变量。

"outputs": {            
       "thing_variable": {
           "type": "map",
           "value": {
                "property1": "foobar"                        
               }
          }
 }
Run Code Online (Sandbox Code Playgroud)

然后,要引用property1terraform 中的属性,请查找输出变量“thing_variable”。

 data "terraform_remote_state" "thing" {
 }

output "chosen" {
  #"property1" could be a variable var.attribute = "property1"
  value = "${lookup(data.terraform_remote_state.thing_variable, "property1")}"
}
Run Code Online (Sandbox Code Playgroud)