Search code examples
terraformterraform-provider-azure

How can I reference azurerm_subnet which in not declared in the root module?


I have a virtual network with 2 subnets

Virtual network: vNetVPN-Dev

Subnet: snet-vgp-dev

Subnet: snet-internal-vm

resource "azurerm_virtual_network" "virtual_network" {
  name                = "vNetVPN-Dev"
  location            = var.resource_group_location_north_europe
  resource_group_name = var.resource_group_name
  address_space       = ["10.1.16.0/23", "10.2.0.0/16", "172.16.100.0/24"]

  subnet {
    name           = "snet-vgp-dev"
    address_prefix = "10.2.1.0/24"
  }

  # =================== Virtual network for vm
  subnet {
    name            = "snet-internal-vm"
    address_prefix = "10.2.10.0/24"
  }

  tags = {
    environment = var.tag_dev
  }
}

and now I want to reference snet-internal-vm in this block of code (below)

resource "azurerm_network_interface" "nic" {
  name                = "internal-nic-vm"
  location            = var.resource_group_location_north_europe
  resource_group_name = var.resource_group_name

  ip_configuration {
    name                          = "internal-vm"
    subnet_id                     = **here_I_want_to_reference**
    private_ip_address_allocation = "Dynamic"
  }
}

Solution

  • I tried to reproduce the same in my environment to create NIC creation with Subnet reference:

    Terraform Code

    provider "azurerm" {
      features {}
    }
     resource "azurerm_virtual_network" "virtual_network" {
        name  = "vNetVPN-Dev"
        location  = data.azurerm_resource_group.example.location
        resource_group_name = data.azurerm_resource_group.example.name
        address_space  = ["10.1.16.0/23", "10.2.0.0/16", "172.16.100.0/24"]
        subnet {
        name  = "snet-vgp-dev"
        address_prefix = "10.2.1.0/24"
        
        }
        subnet {
        name  = "snet-internal-vm"
        address_prefix = "10.2.10.0/24"
        }
        }
        
        #-----NIC Creation-----------
        
        resource "azurerm_network_interface" "nic" {
        name  = "internal-nic-vm"
        location  = data.azurerm_resource_group.example.location
        resource_group_name = data.azurerm_resource_group.example.name
        ip_configuration {
        name  = "internal-vm"
        subnet_id  = azurerm_virtual_network.virtual_network.subnet.*.id[1]
        private_ip_address_allocation = "Dynamic"
        }
        }
    

    Terraform Apply.

    enter image description here

    As mentioned by @sylvainmtz , I could get subnet referred successfully while creating NIC.

    enter image description here