Home > Blockchain >  How to create subnets inside virtual network and security rules inside nsg using loop concept in ter
How to create subnets inside virtual network and security rules inside nsg using loop concept in ter

Time:10-25

I’m trying to create network security group with multiple security rules in one script and virtual network along with five subnets in one script.

For that, I have referred azurerm_virtual_network and azurerm_subnet_network_security_group_association documentations.

The above documentation contains the code with hardcode values. But I want to use loop concept to create subnets inside virtual network, security rules inside network security group and then associate each subnet with network security group.

Thanks in advance for the help !

CodePudding user response:

In order to "loop" you can use the for_each = var.value method and instead of placing the values within the Main.tf file, you can instead use a .tfvars file to loop through the # of resources.

CodePudding user response:

As this is quite advanced, you would be better off dissecting/reusing something that's already available. Take a look at the Azurerm subnet modules from Claranet, available at the modules page on the Terraform website (and there are a ton more to explore!). Here's how you would define the nsgs, vnet and subnets in the locals, at a glance:

locals {
  network_security_group_names = ["nsg1", "nsg2", "nsg3"]

  vnet_cidr = "10.0.1.0/24"

  subnets = [
    {
      name              = "subnet1"
      cidr              = ["10.0.1.0/26"]
      service_endpoints = ["Microsoft.Storage", "Microsoft.KeyVault", "Microsoft.ServiceBus", "Microsoft.Web"]
      nsg_name          = local.network_security_group_names[0]
      vnet_name         = module.azure-network-vnet.virtual_network_name

    },
    {
      name              = "subnet2"
      cidr              = ["10.0.1.64/26"]
      service_endpoints = ["Microsoft.Storage", "Microsoft.KeyVault", "Microsoft.ServiceBus", "Microsoft.Web"]
      nsg_name          = local.network_security_group_names[2]
      vnet_name         = module.azure-network-vnet.virtual_network_name
    }
  ]
}
  • Related