# Variables - Customize these according to your environment
$resourceGroupName = "MyResourceGroup"
$location = "EastUS"
$nsgName = "MyNetworkSecurityGroup"
$vnetName = "MyVNet"
$subnetName = "MySubnet"
$nicName = "MyNetworkInterface"
# Login to Azure Account (If not already logged in)
Connect-AzAccount
# Create a new Resource Group (if it doesn't exist)
$rg = Get-AzResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue
if (-not $rg) {
$rg = New-AzResourceGroup -Name $resourceGroupName -Location $location
Write-Host "Resource Group '$resourceGroupName' created." -ForegroundColor Green
} else {
Write-Host "Resource Group '$resourceGroupName' already exists." -ForegroundColor Yellow
}
# Create a new Network Security Group
$nsg = New-AzNetworkSecurityGroup `
-ResourceGroupName $resourceGroupName `
-Location $location `
-Name $nsgName
Write-Host "Network Security Group '$nsgName' created in Resource Group '$resourceGroupName'." -ForegroundColor Green
# Add Inbound Security Rule to Allow HTTP (Port 80)
$rule1 = Add-AzNetworkSecurityRuleConfig `
-Name "Allow-HTTP-Inbound" `
-NetworkSecurityGroup $nsg `
-Priority 100 `
-Direction Inbound `
-Access Allow `
-Protocol Tcp `
-SourceAddressPrefix "*" `
-SourcePortRange "*" `
-DestinationAddressPrefix "*" `
-DestinationPortRange 80 `
-Description "Allow HTTP inbound traffic on port 80"
# Add Outbound Security Rule to Allow All Traffic
$rule2 = Add-AzNetworkSecurityRuleConfig `
-Name "Allow-All-Outbound" `
-NetworkSecurityGroup $nsg `
-Priority 100 `
-Direction Outbound `
-Access Allow `
-Protocol "*" `
-SourceAddressPrefix "*" `
-SourcePortRange "*" `
-DestinationAddressPrefix "*" `
-DestinationPortRange "*" `
-Description "Allow all outbound traffic"
# Update the Network Security Group with the new rules
$nsg | Set-AzNetworkSecurityGroup
Write-Host "Security rules added to Network Security Group '$nsgName'." -ForegroundColor Green
# Optional: Associate NSG with a Subnet
$subnet = Get-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork (Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $resourceGroupName)
Set-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork (Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $resourceGroupName) -AddressPrefix $subnet.AddressPrefix -NetworkSecurityGroup $nsg
(Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $resourceGroupName) | Set-AzVirtualNetwork
Write-Host "Network Security Group '$nsgName' associated with Subnet '$subnetName'." -ForegroundColor Green
# Optional: Associate NSG with a Network Interface
$nic = Get-AzNetworkInterface -Name $nicName -ResourceGroupName $resourceGroupName
$nic.NetworkSecurityGroup = $nsg
$nic | Set-AzNetworkInterface
Write-Host "Network Security Group '$nsgName' associated with Network Interface '$nicName'." -ForegroundColor Green
Write-Host "Azure Network Security Group setup completed successfully." -ForegroundColor Cyan
Comentários