Skip to content

Instantly share code, notes, and snippets.

@vukasinterzic
Last active October 18, 2023 01:19
Show Gist options
  • Save vukasinterzic/c40463daa045ec7b1ad1054cea9b1823 to your computer and use it in GitHub Desktop.
Save vukasinterzic/c40463daa045ec7b1ad1054cea9b1823 to your computer and use it in GitHub Desktop.
Adds your current Public IP to list of allowed IPs in NSG for RDP
$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)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment