5

In terraform HCL, is it possible to reference an object's attribute dynamically from a variable?

I.e.:

variable "attribute" {
  type = "string"
}

data "terraform_remote_state" "thing" {
  not_really_important
}

output "chosen" {
  value = "${data.terraform_remote_state.thing.$var.attribute}"
}

More specific to my situation, I'm looking to do this with the splat syntax:

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}"
}

I've tried things like lookup(data.terraform_remote_state.thing, var.attribute) and (for the splat problem) lookup(element(data.terraform_remote_state.*, count.index), var.attribute) but they both complain about my attribute reference being incomplete/in the wrong form.

Pooja Kamath
  • 1,290
  • 1
  • 10
  • 17
ThisGuy
  • 2,661
  • 2
  • 18
  • 18

1 Answers1

0

Terraform version 0.12

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

you are able to access the terraform_remote_state outputs directly as a map.

access the state file outputs as a map data.terraform_remote_state.thing.outputs

output "chosen" {
  value = "${lookup(data.terraform_remote_state.thing.outputs, "property1")}"
}

Terraform version 0.11 or below

If you have the luxury of changing the outputs variables in the state file you can set the variable you're interested in to a map and then look up the variable by an index.

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

Then to reference the property1 attribute in your terraform do a look up on the output variable "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")}"
}
Mike
  • 2,547
  • 1
  • 24
  • 36