Home > Back-end >  Reference to specific object created with for each terraform
Reference to specific object created with for each terraform

Time:09-05

I create two subnets with for each. But then when I want to associate nsg with ONLY ONE SPECIFIC subnet I don't know how to reference to it((( thanks

resource "azurerm_subnet" "subnets" {
  for_each = {
    def-subnet    = var.subnet_address_prefixes[0]
    GatewaySubnet = var.subnet_address_prefixes[1]
  }
  address_prefixes     = each.value
  name                 = each.key
  virtual_network_name = azurerm_virtual_network.testvm-VNET.name
  resource_group_name  = azurerm_resource_group.testvm-RG.name

}

resource "azurerm_network_security_group" "def-nsg" {
  location            = var.region
  name                = "def-nsg"
  resource_group_name = azurerm_resource_group.testvm-RG.name
  security_rule {
    access                     = "Allow"
    direction                  = "Inbound"
    name                       = "rdp"
    priority                   = 300
    protocol                   = "Tcp"
    destination_port_range     = "3389"
    source_port_range          = "3389"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
}

resource "azurerm_subnet_network_security_group_association" "def-subnet-nsg-association" {
  network_security_group_id = azurerm_network_security_group.def-nsg.id
  subnet_id                 =  here I want to use only def-subnet id

}

CodePudding user response:

Since you've used for_each, you refer to individual instances of azurerm_subnet using key, such as def-subnet:

subnet_id = azurerm_subnet.subnets["def-subnet"].id
  • Related