'How do I create multiple Security rules using Terraform in Azure?

I am trying to create a Network security group with multiple security rules in it. The idea is to create a list variable (of port ranges) and interpolate the list items in .tf file. The below script throws an error that "priority.

"Error: azurerm_network_security_group.k8hway: security_rule.0: invalid or unknown key: count"

Below is the Terraform code:

resource "azurerm_network_security_group" "NSG" {
  name     = "NSG-Demo"
  location = "${azurerm_resource_group.main.location}"
  resource_group_name  = "${azurerm_resource_group.main.name}"

  security_rule  {
      count = "${length(var.inbound_port_ranges)}"
      name                       = "sg-rule-${count.index}"
      direction                  = "Inbound"
      access                     = "Allow"
      priority                   = "(100 * (${count.index} + 1))"
      source_address_prefix      = "*"
      source_port_range          = "*"
      destination_address_prefix = "*"
      destination_port_range     = "${element(var.inbound_port_ranges, count.index)}"
      protocol                   = "TCP"
    }
}


Solution 1:[1]

I dont think properties support count, but resources do. Use network security group rule:

resource "azurerm_network_security_rule" "test" {
  count = "${length(var.inbound_port_ranges)}"
  name                       = "sg-rule-${count.index}"
  direction                  = "Inbound"
  access                     = "Allow"
  priority                   = "(100 * (${count.index} + 1))"
  source_address_prefix      = "*"
  source_port_range          = "*"
  destination_address_prefix = "*"
  destination_port_range     = "${element(var.inbound_port_ranges, count.index)}"
  protocol                   = "TCP"
}

Reading:

https://www.terraform.io/docs/providers/azurerm/r/network_security_rule

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Spikatrix