Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reference objects in terraform

I am creating an Azure VNet using terraform, and creating a couple subnets in it. Later on , I want to create a network interface, and want to put it in one of the subnets already created for VNet. I do not know how to reference that subnet.

I tried below but it is now working:

subnet_id = "${azurerm_virtual_network.virtual-network.subnet.ServersSubnet.id}"

resource "azurerm_virtual_network" "virtual-network" {
    name                = "${var.ClientShortName}-az-network"
    address_space       = ["${local.AzureInfraNetwork}"]
    location            = "${var.resource-location}"
    resource_group_name =  "${azurerm_resource_group.test-resource-group.name}"

subnet {
    name           = "ServersSubnet"
    address_prefix = "${local.ServersSubnet}"
}

subnet {
    name           = "GatewaySubnet"
    address_prefix = "${local.GatewaySubnet}"
} 
}

Error: Cannot index a set value

  on main.tf line 120, in resource "azurerm_network_interface" "DCNIC":
 120:     subnet_id                     = "${azurerm_virtual_network.virtual-network.subnet.ServersSubnet.id}"

Block type "subnet" is represented by a set of objects, and set elements do
not have addressable keys. To find elements matching specific criteria, use a
"for" expression with an "if" clause.
like image 825
Vad Avatar asked Oct 28 '25 12:10

Vad


1 Answers

Below is the complete solution.

If the subnets are created as blocks, you can reference a given subnet's resource ID as follows:

resource "azurerm_resource_group" "main" {
  name     = "vnet-rg"
  location = "eastus"
}

resource "azurerm_virtual_network" "main" {
  name                = "my-vnet"
  location            = azurerm_resource_group.main.location
  resource_group_name = azurerm_resource_group.main.name
  address_space       = ["10.0.0.0/16"]

  subnet {
    name           = "subnet1"
    address_prefix = "10.0.1.0/24"
  }

  subnet {
    name           = "subnet2"
    address_prefix = "10.0.2.0/24"
  }

  subnet {
    name           = "subnet3"
    address_prefix = "10.0.3.0/24"
  }

}

output "subnet1_id" {
  value = azurerm_virtual_network.main.subnet.*.id[0]
}

output "subnet2_id" {
  value = azurerm_virtual_network.main.subnet.*.id[1]
}

output "subnet3_id" {
  value = azurerm_virtual_network.main.subnet.*.id[2]
}
like image 197
chew224 Avatar answered Oct 30 '25 02:10

chew224



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!