Combine state output and variable

Hi, is there a way to combine state output with a variable? For example:

data.terraform_remote_state.prefix.outputs.${var.variable}

The use case is that a bunch of resources have been created based upon a defined service name, which is then declared as an output, ie. output “<service_name>” {}. It would be useful to be able to reference the required output using the service name in other scripts, as it’ll save having to hard code value, i.e. it would be more dynamic.

Thanks for any assistance.

Hi @glenn.comiskey,

The outputs attribute of the terraform_remote_state data source is a normal object value with an attribute for each of the output values in the latest remote state snapshot, so you can access keys dynamically using the normal index operator that is allowed for any object or map attribute:

data.terraform_remote_state.prefix.outputs[var.variable]

Inside those brackets you can write any expression which produces a value appropriate for the collection. Since this is an object, the index expression must be a string which Terraform will understand as being an attribute name.

Thanks for the feedback, which has been very helpful in resolving my current need and extending my knowledge of Terraform. Much appreciate you taking the time to help me out.