Ask Your Question
2

How can a PowerShell script be written to iterate through NSGs, delete existing rules, and then create new ones?

asked 2022-08-19 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-11-17 13:00:00 +0000

nofretete gravatar image

Here is a PowerShell script that can iterate through NSGs, delete existing rules, and then create new ones:

#Connect to Azure
Connect-AzAccount

#Set variables for the subscription and NSG name
$subscriptionId = "your-subscription-id"
$nsgName = "your-nsg-name"

#Get the NSG object
$nsg = Get-AzNetworkSecurityGroup -Name $nsgName -ResourceGroupName YourResourceGroupName

#Delete all existing security rules
$nsg.SecurityRules | ForEach-Object {Remove-AzNetworkSecurityRuleConfig -Name $_.Name -NetworkSecurityGroup $nsg}

#Create new security rules
New-AzNetworkSecurityRuleConfig -Name "Rule1" -Description "Allow traffic on port 80" -Access Allow -Protocol Tcp -Direction Inbound -Priority 300 -SourceAddressPrefix "10.0.0.0/24" -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 80 | Set-AzNetworkSecurityGroup -NetworkSecurityGroup $nsg

New-AzNetworkSecurityRuleConfig -Name "Rule2" -Description "Deny traffic on port 22" -Access Deny -Protocol Tcp -Direction Inbound -Priority 400 -SourceAddressPrefix "10.0.0.0/24" -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 22 | Set-AzNetworkSecurityGroup -NetworkSecurityGroup $nsg

#Update the NSG with the new rules
Set-AzNetworkSecurityGroup -NetworkSecurityGroup $nsg

#Disconnect from Azure
Disconnect-AzAccount

Note: This script assumes that you have already connected to your Azure account using Connect-AzAccount, and that you have replaced "your-subscription-id", "your-nsg-name", and "YourResourceGroupName" with your actual values. You will also need to modify the security rules as needed for your specific needs.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-19 11:00:00 +0000

Seen: 15 times

Last updated: Nov 17 '21