Get the Public IP of an Azure VM using the Azure Instance Metadata service

By | 2017-11-28T23:48:20+00:00 November 28th, 2017|Uncategorized|0 Comments

There are some instances in which you may need to get the public IP of an Azure VM that you’ve deployed, such as writing it to a config file on the machine or using it in a script.

One way to achieve this is to use the Azure Resource Manager cmdlets for PowerShell:


$publicIp = Get-AzureRmPublicIpAddress -Name $publicIpName -ResourceGroupName $rgName

However, this does require setting up the ARM cmdlets to the machine first.

Another way to get the public IP is by going to an external site, but there are no guarantees the external site is available.

There’s an even easier way that is generally available (in preview for Azure Government, Azure China, Azure Germany as of now). This is through the Azure Instance Metadata service for Azure VMs.

The Azure Instance Metadata service is a REST endpoint (well-known non-routable IP address) useful for all IaaS VMs created through Azure Resource Manager and is only accessible to the VM for which you want to get configuration information (e.g., public IP). The information available includes SKU, network configuration, and maintenance events. The response returned from the call is in the standard JSON format.

Here’s what it looks like to get the public IP from within a Windows VM in Azure and set it to a variable through PowerShell:


#Get Public IP from Azure Instance Metadata service for Windows VMs

$uri = "http://169.254.169.254/metadata/instance?api-version=2017-04-02"

$jsonBody = Invoke-RestMethod -Headers @{"Metadata"="true"} -URI $uri -Method get

$publicIp = $jsonBody.network.interface[0].ipv4.ipaddress.publicIpAddress

Write-Host "Getting public IP: $($publicIp)"

And it looks like you can also get the public IP from within a Linux VM in Azure (from the documentation):


curl -H Metadata:true "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-04-02&format=text"

Note that you can also get the private IP address by changing to “.privateIpAddress.” How I usually debug the values of the JSON returned is by adding a breakpoint into the line of code at the Invoke-RestMethod line and then type in PowerShell, $jsonBody to view the full response back and then start manually parsing to find the appropriate value.

There is a lot more that you can do with the Azure Instance Metadata service, I’d definitely recommend checking it out starting here: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service#.

About the Author:

Leave A Comment