Hi guys.
I am trying to create multiple Azure subnets, with separate NSGs attached to them, and dedicated security rules. I am able to create a single rule, but I don’t know how to iterate through the list of strings that contains port needed.
Here is my code:
terraform {
required_providers {
azurerm = {
source = “hashicorp/azurerm”
version = “~>3.27.0”
}
}
}
provider “azurerm” {
features {
}
}
provider “random” {
}
variable “subnets” {
type = map(any)
default = {
“front” = { prefix = [“10.0.0.0/24”], ports = [“80”, “443”] },
“middle” = { prefix = [“10.0.1.0/24”], ports = [“8080”, “8081”, “9090”, “9091”] },
“back” = { prefix = [“10.0.2.0/24”], ports = [“1433”, “3306”, “5432”] },
“bastion” = { prefix = [“192.168.0.0/24”], ports = [“443”, “22”] }
}
}
resource “azurerm_resource_group” “rg” {
//for_each = var.subnets
name = “rgspo00000001”
location = “North Europe”
}
resource “azurerm_network_security_group” “nsg” {
depends_on = [
azurerm_resource_group.rg
]
for_each = var.subnets
name = “${each.key}-nsg”
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
}
resource “azurerm_network_security_rule” “nsg_rules_inbound” {
depends_on = [
azurerm_network_security_group.nsg
]
for_each = var.subnets
name = “Inbound-{each.value.ports[0]}"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = each.value.ports[0]
source_address_prefix = "*"
destination_address_prefix = "*"
resource_group_name = azurerm_resource_group.rg.name
network_security_group_name = "{each.key}-nsg”
}
So, for example for subnet:
“middle” = { prefix = [“10.0.1.0/24”], ports = [“8080”, “8081”, “9090”, “9091”] },
I want to open 8080, 8081, 9090 and 9091.
Appreciate any help.