NSG
Last updated: December 15, 2024Network Security Groups (NSGs) are helpful in defining the traffic rules in a VNet. By defining the rules, you'll specify the inbound and outbound traffic regulations and protect your network from unintended traffic.
Setting up a traffic rule in a VNet is done in 2 steps:
Setting up a traffic rule in a VNet is done in 2 steps:
- Define a NSG and traffic rules
- Attach rules to the specific subnets
You can define an NSG as follows:
resource "azurerm_network_security_group" "nsg" { name = "${local.resource_prefix}_nsg" location = local.location resource_group_name = azurerm_resource_group.rg.name tags = local.tags security_rule { name = "deny-http" priority = 100 direction = "Outbound" access = "Deny" protocol = "Tcp" source_port_range = "*" destination_port_range = "80" source_address_prefix = "*" destination_address_prefix = "*" } security_rule { name = "allow-https" priority = 110 direction = "Inbound" access = "Allow" protocol = "Tcp" source_port_range = "*" destination_port_range = "443" source_address_prefix = "*" destination_address_prefix = "*" } depends_on = [ azurerm_resource_group.rg ] }
The example above defines two inbound rules, one to deny HTTP traffic and one to allow HTTPS traffic.
Next, you need to attach the NSG to the desired subnet, e.g.
resource "azurerm_subnet_network_security_group_association" "hub-sql-subnet" { subnet_id = azurerm_subnet.hub-sql-subnet.id network_security_group_id = azurerm_network_security_group.nsg.id depends_on = [ azurerm_subnet.hub-sql-subnet, azurerm_network_security_group.nsg ] }