Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Azure

Add IP Address to Azure Network Security Group

0.00/5 (No votes)
5 Feb 2020CPOL1 min read 1.9K  
A script to modify the IP Address for a NSG rule and allow full access to that IP address

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.

Azure CLI

  1. Firstly, run az login to login to your Azure account.

  2. Now, let's request a list of the NSGs that are in your account:

    Azure-CLI
    az network nsg list

    This will give you a big list of json back with all the NSGs you have.

  3. To filter this down further and find the exact NSG you are looking to update, you can parse in the Resource Group name and the NSG name:
    Azure-CLI
    az network nsg show -g MyResourceGroupName -n MyNSGName
  4. Now view the rules in the NSG:
    Azure-CLI
    az network nsg rule list -g MyResourceGroupName --nsg-name MyNSGName
  5. Create a new NSG rule:
    Azure-CLI
    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-prefixes the IP address you want to add
    • –destination-address-prefixes the destination IP addresses
    • destination-port-ranges the destination ports

      (I’m allowing for all this since it’s my development server.)

  6. Update existing NSG rule: Now that we have a NSG rule called owenallowipaddress, let's 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.
    Azure-CLI
    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> 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)