Search code examples
loopsterraformterraform-provider-azureterraform-template-fileterraform0.12+

How can I associate NSG's and Subnets being created by loops in Terraform?


Here is the code I am using to create subnets and nsgs I want to associate the NSG and subnet in the same script but I am unable to understand how can I get subnet IDs and NSG IDs which are being produced here and use them in the association resource. Thanks in advance for the help !

First part of code this is being used to create n no of Subnets and NSGs depends upon the parameter

provider "azurerm" {

  version = "2.0.0"
  features {}
}

resource "azurerm_resource_group" "new-rg" {
  name     = var.rg_name
  location = "West Europe"
}

resource "azurerm_virtual_network" "new-vnet" {
  name                = var.vnet_name
  address_space       = ["${var.vnet_address_space}"]
  location            = azurerm_resource_group.new-rg.location
  resource_group_name = azurerm_resource_group.new-rg.name


}

resource "azurerm_subnet" "test" {
  count                = "${length(var.subnet_prefix)}"
  name                 = "${element(var.subnet_subnetname, count.index)}"
  resource_group_name  = azurerm_resource_group.new-rg.name
  virtual_network_name = azurerm_virtual_network.new-vnet.name
  address_prefix       = "${element(var.subnet_prefix, count.index)}"

}


resource "azurerm_network_security_group" "new-nsg" {

    count        =  "${length(var.subnet_prefix)}"
  name                = "${element(var.subnet_subnetname, count.index)}-nsg"
  location            = azurerm_resource_group.new-rg.location
  resource_group_name = azurerm_resource_group.new-rg.name
}

Below is the resource where i have to pass the parameters to create the association for the above subnets and nsgs being created.

Second Part of code Need to make the below code usable for above solution for n no of associations.

resource "azurerm_subnet_network_security_group_association" "example" {

  subnet_id                 = azurerm_subnet.example.id
  network_security_group_id = azurerm_network_security_group.example.id
}

How can associate the n number of subnets and nsgs being created by using 2nd part of code, I cant find my way to that


Solution

  • So i was able to solve the issue mentioned by me above the following code contains the solution for the mentioned scenario for the problem.

    resource "azurerm_subnet_network_security_group_association" "snet-nsg-association" {
    
    count = length(var.subnet_subnetname)
    subnet_id                 = element(azurerm_subnet.multi-snet.*.id, count.index)
    network_security_group_id = element(azurerm_network_security_group.new-nsg.*.id, count.index)
    
    }