How to refer to a terraform resource by a resource attribute containing an environmental variable

For example we have a resource defined as

resource “aws_iam_role_policy” “example” {
name = “${local.env}-role-policy”

I would like to refer to this terraform resource by name but not by “example” but by “${local.env}-role-policy”. The reason is because I specify an environmental variable inside the attribute, so I would be able to specify different resource stacks within the same AWS account.

Hi @anarinsky,

The resource names are unique only within a particular module in a particular Terraform state, so there is no need for them to be namespaced in this way. It can be called example in all of the instances of your module and Terraform will use the module address and/or the separate Terraform state to keep them separated.

If you’re coming from a programming background, it might help to think of a Terraform module as being a little like a class in an object-oriented programming language, where the resources inside are like properties of that class. You can have a class property called example and then each instance of that class has its own separate value for that property, even though they are all called “example”.

1 Like

you can try something like

"aws_iam_role_policy" "example" {
       name = "${var.env}-role-policy"
        ............................................
}

variable "env" {
 type = string
 default = "dev"
}
1 Like

Yes, this was my solution, a little different. I used workspace but the idea is about the same