PowerShell one-liner to easily use Azure VM Metadata Service

Have you heard about the Azure Instance Metadata Service?

When I implemented my blog in Azure I used a handy PowerShell “one-liner” to easily query specific information about the VM I was currently logged into.
The code uses the Metadata Service URL scheme do “drill” into the Data Categories.

So here is the code:


# “One-liner” for easily querying the Azure Instance Metadata Service.
"network/interface/0/ipv4/ipAddress/0/publicIpAddress" | Tee-Object -Variable p | Out-Null ; Invoke-RestMethod -Headers @{"Metadata"="true"} -URI "http://169.254.169.254/metadata/instance/$($p)?api-version=2017-08-01&format=text"
# Instead of "network/interface/0/ipv4/ipAddress/0/publicIpAddress" you can use any
# path throgh the instance metadata json structure.
# You can find a sample json structure here:
# {
# "compute": {
# "location": "westus2",
# "name": "Win10",
# "offer": "Windows",
# "osType": "Windows",
# "placementGroupId": "",
# "platformFaultDomain": "0",
# "platformUpdateDomain": "0",
# "publisher": "MicrosoftVisualStudio",
# "resourceGroupName": "****",
# "sku": "Windows-10-N-x64",
# "subscriptionId": "****",
# "tags": "",
# "version": "2017.10.12",
# "vmId": "****",
# "vmSize": "Standard_B2s"
# },
# "network": {
# "interface": [
# {
# "ipv4": {
# "ipAddress": [
# {
# "privateIpAddress": "10.1.2.4",
# "publicIpAddress": "51.143.***.***"
# }
# ],
# "subnet": [
# {
# "address": "10.1.2.0",
# "prefix": "24"
# }
# ]
# },
# "ipv6": {
# "ipAddress": []
# },
# "macAddress": "******"
# }
# ]
# }
# }

You can also create a function which gives a much easier flow of repetitive usage:


# Function for easily querying the Azure Instance Metadata Service
Function AzMeta {
Param( [Parameter(ValueFromPipeline)] $p )
Invoke-RestMethod `
-Headers @{"Metadata"="true"} `
-URI "http://169.254.169.254/metadata/instance/$($p)?api-version=2017-08-01&format=text"
}
# Get the public IP if your Azure instance
"network/interface/0/ipv4/ipAddress/0/publicIpAddress" | AzMeta
# Get the Virtual Machine Size/SKU, e.g. "Standard_B2s"
"compute/vmSize" | AzMeta

 

Note: During the creation of this blog I experimented with different instance types: virtual machines, containers, App Services. But I ended up using App Service for Containers and it mostly seems to work great.

 

 

 

Header photo by Rodger_Evans

7