Applying IP Restrictions to a Large Set of Azure Resources

To do this, use PowerShell and Azure CLI to collect all of the NSGs and get all of the NSGs in the subscription:

az account set -s <SUB_ID>
$nsgs = az network nsg list | ConvertFrom-Json

Then go through every NSG and create the rule:

$nsgs | ForEach-Object -Process { az network nsg rule create --name NAME --nsg-name $_.name --priority PRIORITY --resource-group $_.resourceGroup <ANY OTHER FIELDS> }

Next, get a list of the App Services:

$webapps = az webapp list | ConvertFrom-Json

And go through and add the list of IPs required (must use individual IPs):

$webapps | ForEach-Object -Process { $WebAppConfig = Get-AzResource -ResourceName $_.name -ResourceType Microsoft.Web/sites/config -ResourceGroupName $_.resourceGroup -ApiVersion 2018-11-01; $WebAppConfig.Properties.ipSecurityRestrictions = @([PSCustomObject] @{ ipAddress = '127.0.0.1/32' },@{ ipAddress = '127.0.0.1/32' });  Set-AzResource -ResourceId $WebAppConfig.ResourceId -Properties $WebAppConfig.Properties -ApiVersion 2018-11-01 }

Removing Access

To delete the same list of rules from the NSGs, use the same name:

$nsgs | ForEach-Object -Process { az network nsg rule delete -g resourceGroup --nsg-name $_.name -n NAME }

Reference:

https://docs.microsoft.com/en-us/cli/azure/network/nsg?view=azure-cli-latest#az-network-nsg-list

https://docs.microsoft.com/en-us/cli/azure/network/nsg/rule?view=azure-cli-latest#az-network-nsg-rule-create

https://docs.microsoft.com/en-us/cli/azure/network/nsg/rule?view=azure-cli-latest#az-network-nsg-rule-delete

Leave a Reply

Your email address will not be published. Required fields are marked *