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.
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
Asked: 2022-08-19 11:00:00 +0000
Seen: 15 times
Last updated: Nov 17 '21
What is the process for installing SASS/Compass in the DDEV web container?
Is it possible to create and execute a file without having to type the file name twice?
How can you obtain the sha1 of the most recent commit in a git repository using C#?
What is the process for initializing Java UDFs in Spark?
How can I use crontab to initiate and modify the libcamera-vid RTSP stream on my Raspberry Pi?
Is it possible to repair a file within a docker container that has failed to start?
What is an effective way to edit HTML strings using PowerShell?