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

时间:2018-05-14 18:17:11

标签: 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}"
}

更具体到我的情况,我希望用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}"
}

我尝试了lookup(data.terraform_remote_state.thing, var.attribute)和(对于splat问题)lookup(element(data.terraform_remote_state.*, count.index), var.attribute)之类的内容,但他们都抱怨我的属性引用不完整/格式错误。

1 个答案:

答案 0 :(得分:0)

Terraform版本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")}"
}

Terraform版本0.11或更低版本

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

"outputs": {            
       "thing_variable": {
           "type": "map",
           "value": {
                "property1": "foobar"                        
               }
          }
 }

然后在您的Terraform中引用property1属性,以查找输出变量“ 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")}"
}