Posts Dynamically Managing Azure NSG Rules with PowerShell
Post
Cancel

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:

$SubscriptionId = ""
$RGName = ""
$NSGName = ""
$RuleName = ""
# Ensure Azure modules are installed
if (-not (Get-Module -ListAvailable -Name Az.Network)) {
Install-Module -Name Az.Network -AllowClobber -Scope CurrentUser
}
# Log in to Azure (manual intervention might be required)
if (-not (Get-AzContext)) {
Connect-AzAccount
}
# Set the subscription context
Set-AzContext -Subscription $SubscriptionId
# Get the current public IP address
$publicIp = Invoke-RestMethod http://ipinfo.io/json | Select-Object -ExpandProperty ip
#Fetch the NSG
$NSG = Get-AzNetworkSecurityGroup -Name $NSGName -ResourceGroupName $RGName
# Fetch the current inbound security rule
$rule = Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $NSG -Name $RuleName
# If the source address prefix is '*', 'Any', or null, we just set the current IP as the source.
# If there's already a source address, we append our IP to the list, separated by a comma.
# Check the current rule's source address
if ($rule.SourceAddressPrefix -eq '*' -or $rule.SourceAddressPrefix -eq 'Any' -or $rule.SourceAddressPrefix -eq $null) {
$rule.SourceAddressPrefix.Clear() # Clear any existing entries
$rule.SourceAddressPrefix.Add($publicIp) # Add the public IP
} else {
# Add new IP if it's not already in the list
if (-not $rule.SourceAddressPrefix.Contains($publicIp)) {
$rule.SourceAddressPrefix.Add($publicIp)
}
}
try {
# Update the NSG with the new rule configuration
$NSG | Set-AzNetworkSecurityGroup -ErrorAction Stop
# Inform the user of success
Write-Output "Added $publicIp to the inbound rule $RuleName for RDP connection successfully."
}
catch {
# Capture the error and inform the user
Write-Output "Failed to add $publicIp to the inbound rule $RuleName for RDP connection. Error: $($_.Exception.Message)"
}

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:

$SubscriptionName = ""
$RGName = ""
$NSGName = ""
$RuleName = ""
# Ensure Azure modules are installed
if (-not (Get-Module -ListAvailable -Name Az.Network)) {
Install-Module -Name Az.Network -AllowClobber -Scope CurrentUser
}
# Log in to Azure (manual intervention might be required)
if (-not (Get-AzContext)) {
Connect-AzAccount
}
# Set the subscription context using SubscriptionID
Set-AzContext -SubscriptionId $SubscriptionID
# Get the current public IP address
$publicIp = Invoke-RestMethod http://ipinfo.io/json | Select-Object -ExpandProperty ip
# Fetch the NSG
$NSG = Get-AzNetworkSecurityGroup -Name $NSGName -ResourceGroupName $RGName
# Fetch the current inbound security rule
$rule = Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $NSG -Name $RuleName
# If the IP is present in the list, we'll remove it
if ($rule.SourceAddressPrefix.Contains($publicIp)) {
$rule.SourceAddressPrefix.Remove($publicIp)
}
# Update the NSG rule and capture potential errors
try {
$NSG | Set-AzNetworkSecurityGroup -ErrorAction Stop
Write-Output "Removed $publicIp from the inbound rule $RuleName for RDP connection successfully."
}
catch {
Write-Output "Failed to remove $publicIp from the inbound rule $RuleName for RDP connection. Error: $($_.Exception.Message)"
}

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

Conclusion

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 1 year ago2023-10-18T06:43:17+02:00
This post is licensed under CC BY 4.0