I often find myself trying to connect to Virtual Machines in Azure when my IP Address has changed, either because I’ve physically moved to another office, or because I don’t have a static IP Address.
We are going to create a script to modify the IP Address for a NSG rule and allow full access to that IP address.
1. Firstly run az login to login to your azure account.
2. Now, lets request a list of the NSGs that are in your account
az network nsg list
This will give you a big list of json back with all the NSGs you have.
3. To filter down this further and find the exact NSG you are looking to update you can parse in the Resource Group name and the NSG name
az network nsg show -g MyResourceGroupName -n MyNSGName
4. Now view the rules in the NSG
az network nsg rule list -g MyResourceGroupName --nsg-name MyNSGName
5. Create a new NSG rule
az network nsg rule create --network-security-group-name MyNSGName --resource-group MyResourceGroupName -n owenallowipaccess --source-address-prefixes <YOURIPADDRESS> --destination-address-prefixes '*' --access Allow --priority 400 --destination-port-ranges '*'
Here we have to specify: -n the name of the new rule –source-address-prefixe the IP address you want to add –destination-address-prefixes the destination IP addresses –destination-port-ranges the destination ports. (I’m allowing all for this since it’s my development server.)
6. Update existing NSG rule
Now that we have a NSG rule called owenallowipaddress, lets assume that my IP address has changed and I want to update that rule, I don’t want to create a new one for this instance, this would be my dynamic IP address rule, I can always create another rule called londonoffice etc.
az network nsg rule update --network-security-group-name MyNSGName --resource-group MyResourceGroupName -security-rule-name owenallowipaccess --source-address-prefixes <YOURIPADDRESS> az network nsg rule update -g MyResourceGroupName --nsg-name MyNSGName -n owenallowipaccess --source-address-prefixes <YOURIPADDRESS>