Search code examples
azureazure-devopscloudterraform-provider-azure

Azure associating security group with multiple network interfaces and load balancer with multiple subnets using Terraform


I've built an environment inside Azure using Terraform which I've created virtual network, multiple subnets, security groups (in the amount of the subnets), network interfaces (in the amount of virtual machine), load balancer, virtual machines, etc. I'm trying to associate each security group with multiple network interfaces but haven't found a solution yet. In addition, I facing issues associating my load balancer with multiple subnets.

Let's say that I have in my environment 4 subnets, 4 security groups, 8 NICs (2 NICs in each subnet) and 1 load balancer. I want to associate each SG within the specific subnet with 2 NICs inside that subnet and then associate my load balancers with 2 subnets out of my 4 subnets.

In Terraform's documentation associating SG with NIC works with one specific NIC id and not many: enter image description here

Moreover, In Terraform's documentation associating load balancer with subnet works with one specific subnet id and not many: enter image description here

How do I do handle these multiple associations? Thank you.


Solution

  • You can use the count property in the association to associate multiple NICs with the one NSG. Here is an example:

    resource "azurerm_network_interface_security_group_association" "example" {
      count                     = length(azurerm_network_interface.example.*.id)
      network_interface_id      = element(azurerm_network_interface.example.*.id, count.index)
      network_security_group_id = azurerm_network_security_group.example.id
    }