I am trying to use below code
data "azurerm_resource_group" "rg_tst_na" {
name = "test1"
}
data "azurerm_resource_group" "rg_dev_na" {
name = "test2"
}
resource "azurerm_role_assignment" "test_role_assign" {
for_each = var.test_role_assignment
principal_id = azurerm_user_assigned_identity.test_setup["${each.key}_${each.value}"].principal_id # this is created as separate resource using a for_each loop this resource is validate by terraform apply
role_definition_name = "Network Contributor"
scope = data.azurerm_resource_group."${each.key}_${each.value}".id
}
variable "var.test_role_assignment" {
type = map(string)
default={
"na" = "dev",
"na" = "tst",
}
}
I am getting error that scope cannot be read during terraform plan, how can I variablize the input of resource attribute
scope = data.azurerm_resource_group.rg_"${each.value}"_"${each.key}".id
Is this possible?
Can I use variable in the value of scope as resource attribute but variablized? Is this violation of terraform rules
2
Answers
There are a couple of things to note:
variable "var.test_role_assignment"
should be onlyvariable "test_role_assignment"
scope
, that’s not how terraform works and cannot be done.However, you could use the same
for_each
for the data source, and reference that in the resource block. Something along the lines should work:Terraform uses static analysis of references to understand the dependencies between resources, and so a reference from one resource to another must be written as a static reference; dynamic expression evaluation is not allowed.
However, you can achieve a similar effect by defining a local value that acts as a lookup table for your resource objects:
In an expression like
local.resource_groups.tst_na
, only thelocal.resource_groups
part is important for Terraform’s dependency analysis: Terraform will conclude thatlocal.resource_groups
depends on bothazurerm_resource_group.rg_tst_na
andazurerm_resource_group.rg_dev_na
, and so therefore anything that refers tolocal.resource_groups
indirectly depends on both of those resources, regardless of what other attribute accesses might appear after that reference.You can therefore construct the attribute lookup for that object using arbitrary expressions:
…and the result would be the same object as if you’d referred to the corresponding resource directly.