Posts Dynamically Managing Azure NSG Rules with PowerShell

Dynamically Managing Azure NSG Rules with PowerShell

Dynamically Managing Azure NSG Rules with PowerShell - AzureIs.Fun

Ever found yourself in a situation where you’re hopping from one cafe to another, chasing the Wi-Fi dream, only to realize your IP address keeps changing? Or perhaps you’re traveling and relying on various hotel Wi-Fi networks. Every time your IP changes, accessing your Azure resources can become a challenge, especially if you have Network Security Groups (NSGs) locked down tight for security reasons (as you should!).

Picture this: You’re working remotely from a charming coffee shop in Italy, sipping your espresso. You need to RDP into an Azure VM, but oh no, the NSG is blocking you because your current public IP isn’t whitelisted in that allow RDP rule. It can be a pain to manually add your current IP every time it changes, right?

This is where our nifty little PowerShell script comes into play! It’s designed to fetch your current public IP and dynamically add it to your Azure NSG inbound rules. A real lifesaver for the nomadic techie!

Adding Your Current IP to NSG

Alright, without further ado, here’s the script to dynamically add your current IP to the NSG rules:

Neat, right?

If you happen to change your computers as well, then the easies way is to save this peace of code in your GitHub Gists, and have it ready. If you’re curious about running scripts like this directly from GitHub Gist, I’ve got another article that covers just that. Super useful if you want to keep your scripts centralized and easily accessible!

Using GitHub Gists for PowerShell.

Removing Your IP from NSG RDP rule when done

Okay, you’ve finished your work (or espresso) and now want to tidy up. Just as easily as you added your IP, you can remove it too. Here’s how:

And voila! Your NSG is back to its original state, keeping things secure and neat.


I genuinely hope you found this little trick useful. It’s one of those quality-of-life improvements that, once you start using, you wonder how you lived without. For more PowerShell magic and other tech tidbits, be sure to check out my other blog posts. Keep scripting and stay caffeinated!

Vukasin Terzic

Updated Oct 17, 2023 2023-10-18T06:43:17+02:00
This post is licensed under CC BY 4.0