Last active
October 18, 2023 04:34
-
-
Save vukasinterzic/e333eb7a6c9662bbe6089c8de3767306 to your computer and use it in GitHub Desktop.
Adds last Public IP from the list of allowed IPs in NSG for RDP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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)" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment