Objective : How to use output value of one resource created and use that for creating another resource in same root module
What I tried:
resource "azurerm_virtual_network" "vnet" {
name = var.hub_vnet_name
location = azurerm_resource_group.rg[0].location
resource_group_name = azurerm_resource_group.rg[0].name
for_each = {for k,v in var.vnet_address_space: k=>v if k == "${var.env}"}
address_space = each.value
dns_servers = var.dns_servers
tags = {
environment = "${var.env}"
costcentre = "14500"
}
dynamic "ddos_protection_plan" {
for_each = local.if_ddos_enabled
content {
id = azurerm_network_ddos_protection_plan.ddos[0].id
enable = false
}
}
}
output "azurerm_vnets_names" {
value = values(azurerm_virtual_network.vnet)[*].name
}
Till above point its working and I see output of as
Outputs:
azurerm_vnets_names = [
"vnet-hub",
]
Now as next step I am trying to create Subnets in loop as below
tfvars.json:
"subnets" : {
"Dev" :
[
{"gw_snet":{
"name" : "GatewaySubnet",
"address_prefixes" : ["10.1.1.0/24"]
},
"dns-snet" : {
"name" : "InboundDNSSubnet",
"address_prefixes" : ["10.1.2.0/24"]
},
"common_snet" : {
"name" : "Common",
"address_prefixes" : ["10.1.3.0/24"]
},
"clientdata_snet" : {
"name" : "ClientDataSubnet",
"address_prefixes" : ["10.1.4.0/20"]
}}
],
"Stage" :
[
{"gw_snet":{
"name" : "GatewaySubnet",
"address_prefixes" : ["10.2.1.0/24"]
},
"dns-snet" : {
"name" : "InboundDNSSubnet",
"address_prefixes" : ["10.2.2.0/24"]
},
"common_snet" : {
"name" : "Common",
"address_prefixes" : ["10.2.3.0/24"]
},
"clientdata_snet" : {
"name" : "ClientDataSubnet",
"address_prefixes" : ["10.2.4.0/20"]
}}
],
"Prod" :
[
{"gw_snet":{
"name" : "GatewaySubnet",
"address_prefixes" : ["10.3.1.0/24"]
},
"dns-snet" : {
"name" : "InboundDNSSubnet",
"address_prefixes" : ["10.3.2.0/24"]
},
"common_snet" : {
"name" : "Common",
"address_prefixes" : ["10.3.3.0/24"]
},
"clientdata_snet" : {
"name" : "ClientDataSubnet",
"address_prefixes" : ["10.3.4.0/20"]
}}
]
}
In my main.tf:
locals {
net_subnets = merge([
for env, network in var.subnets : {
for k, v in network[0] :
"${k}-${v.name}" => {
subnet_name = v.name
address_prefixes = v.address_prefixes
} if env == "Dev"
}]...)
}
#Creating subnets
resource "azurerm_subnet" "mysubnet" {
for_each = local.net_subnets
name = each.value.subnet_name
address_prefixes = each.value.address_prefixes
virtual_network_name = azurerm_virtual_nework.vnet.name
resource_group_name = var.resource_group_name
}
Now below line is erroring out
virtual_network_name = azurerm_virtual_nework.vnet[var.env].name
I am getting error below
│ A managed resource "azurerm_virtual_nework" "vnet" has not been declared in the root module.
I am not using any modules, I putting all code in root only.
Please help me to identify issue