Hello!
I need to reference the exact resource created with for_each loop.
So, this code works fine:
variable "natgw" {
type = object({
azs = set(string)
zone = string
})
default = {
zone = "1"
azs = ["1", "2", "3"]
}
}
resource "azurerm_public_ip" "pip" {
for_each = var.natgw.azs
...
zones = [each.value]
}
resource "azurerm_nat_gateway" "natgateway" {
for_each = var.natgw.azs
....
zones = [each.value]
}
resource "azurerm_nat_gateway_public_ip_association" "pip_association" {
for_each = var.natgw.azs
nat_gateway_id = azurerm_nat_gateway.natgateway[each.value].id
public_ip_address_id = azurerm_public_ip.pip[each.value].id
}
resource "azurerm_subnet_nat_gateway_association" "subnet_association" {
subnet_id = azurerm_subnet.exact_subnet.id
nat_gateway_id = azurerm_nat_gateway.natgateway[var.natgw.zone].id
}
Until I change var.natgw.zone
default = {
zone = "2"
azs = ["1", "2", "3"]
}
or just put 2 as index:
nat_gateway_id = azurerm_nat_gateway.natgateway[2].id
I receive an error:
│ Error: Invalid index
│
│"azurerm_subnet_nat_gateway_association" "subnet_association":
│ nat_gateway_id = azurerm_nat_gateway.natgateway[var.natgw.zone].id
│ ├────────────────
│ │ azurerm_nat_gateway.natgateway is object with 1 attribute "1"
│ │ var.natgw.zone is "2"
│
│ The given key does not identify an element in this collection value.
terraform state list | grep azurerm_nat_gateway.natgateway
module.vnet.azurerm_nat_gateway.natgateway["1"]
module.vnet.azurerm_nat_gateway.natgateway["2"]
module.vnet.azurerm_nat_gateway.natgateway["3"]
It looks a bit weird to me since azurerm_nat_gateway_public_ip_association doesn’t through an error that it can’t find indexes.
Or I can’t reference in such a way and need to add some kind of loop there also?
thanks in advance