Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save darrenjrobinson/f19371123f6029d6f51ac3ee33474201 to your computer and use it in GitHub Desktop.
Save darrenjrobinson/f19371123f6029d6f51ac3ee33474201 to your computer and use it in GitHub Desktop.
Update an Azure NSG for my current public ip address, start the virtual machine and launch remote desktop to the VM. Associated blogpost https://blog.darrenjrobinson.com/automating-source-ip-address-updates-on-an-azure-network-security-group-rdp-access-rule/
# My RG
$resourceGroup = "MyResourceGroup"
# VM that will be started after updating the NSG
$VMName = "MyVM"
# NSG Name
$NSGName = "MyResourceGroupNSG"
# RDP File
$RDPFile = "C:\Users\Darren\Desktop\MyVM.rdp"
# Get my Public IP
$ip = Invoke-RestMethod http://ipinfo.io/json | Select -exp ip
# Login to Azure
Import-Module AzureRM
Login-AzureRmAccount
# Get Sub Info and select Subscription
$SubscriptionName = Get-AzureRmSubscription | sort SubscriptionName | Select SubscriptionName, SubscriptionID
$SubscriptionName = $SubscriptionName.SubscriptionName
Select-AzureRmSubscription -SubscriptionName $SubscriptionName
$SubscriptionID = $SubscriptionName.SubscriptionId
# Get NSG
$NSG = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroup -Name $NSGName
# Current IP in the RDP Rule
write-host "Current NSG RDP Rule IP is" $NSG.SecurityRules[0].SourceAddressPrefix
write-host "Current External IP is" $IP
# Updating to current external IP if different
if ($NSG.SecurityRules[0].SourceAddressPrefix -ne $ip) {
Set-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $NSG -Name $NSG.SecurityRules[0].Name -SourceAddressPrefix $ip -Protocol * -SourcePortRange * -DestinationPortRange 3389 -Access Allow -DestinationAddressPrefix * -Priority 100 -Direction Inbound
Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $NSG
}
# Start VM
$vm = Get-AzureRmVM -ResourceGroupName $resourceGroup -Name $VMName -Status
$PowerState = (get-culture).TextInfo.ToTitleCase(($vm.statuses)[1].code.split("/")[1])
if ($PowerState -eq "Deallocated"){
$vmstatus = Start-AzureRMVM -ResourceGroupName $resourceGroup -Name $VMName
}
# Connect to VM using RDP Settings File
if($vmstatus.Status.Equals("Succeeded")){
Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList $RDPFile
}
else{
write-host "Something went wrong starting $VMName" -foregroundcolor "magenta" -backgroundcolor "yellow"
}
# Stop VM
# Stop-AzureRMVM -ResourceGroupName $resourceGroup -Name $VMName -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment