Variable in resource reference name

Hy,

I want to access to a resourcer using a variable in its name.

I have a plan (state) with general information that is not generated by terraform (because it is generated with another tools or because I generated it before start using terraform and I have no time to migrate it) let’s call it information. This plan have some outputs like this:

output “cluster01_some_data” {
value = “output_value”
}
output “cluster01_some_more_data” {
value = “more_output_value”
}
output “cluster02_some_data” {
value = “output_value”
}

output “cluster02_some_more_data” {
value = “output_more_value”
}

In a module I want to access to some resources that are in this information state, using a parameter in the resource reference:

variable “cluster” {
type = string
}

data “terraform_remote_state” “information” {
backend = “local”
config = {
path = “…/information/”
}
}

resource “some_resouce_type” “some_resource” {
some_parameter = data.terraform_remote_state.information.outputs.{cluster}_some_data some_other_parameter = data.terraform_remote_state.information.outputs.{cluster}_some_more_data
}

Then setting the parameter cluster to cluster01 or cluster02 I can access to all the values I have in the information state without having to have a lot or parameters.

Is this possible to do?

Thanks

No you can’t use a variable in a resource name. You can use a variable when referencing a map/list or reource which uses a count or for_each, so your best option is to adjust that output to be some_more_data["cluster01"] and some_more_data["cluster02"] (i.e. a single output which is a map)

Hy Stuart-c,

thanks for the reply, it works!

This is how I generate the map into the output resource:

output “some_data” {
value = “${
tomap({
“cluster01” = “output_value_1”,
“cluster02” = “output_value_2”
})
}”
}

Roger

I wouldn’t suggest that way of doing things. In general you shouldn’t use ${}. Instead I’d use:

output “some_data” {
    value = {
        “cluster01” = “output_value_1”,
        “cluster02” = “output_value_2”
    }
}

It really a clearer way.

Thanks!!