Search code examples
azureresourcesvirtual-machinesubscription

How to get the Azure subscription and resouce group from within a VM using REST API?


A lot of Azure API endpoints require you pass in the subscriptionID and resource group name of the resouce you want to work with.

From a bash script running on an Azure Linux VM, how can I get these info? I can't have the Azure CLI installed hence looking for some REST API.

There is this old answer which I found convoluted and requires the CLI anyway. One answer even mentions this API to get all info of one given VM:

/subscriptions/[subscription-id]/resourceGroups/[resource-group-name]/providers/Microsoft.Compute/virtualMachines/[virtual-machine-name]

It seems to be a chicken and egg problem.


Solution

  • I've found it. The Azure Instance Metadata Service returns a lot of metadata about the Azure VM where the request has made from. I used the following REST endpoint to retrieve the VM's subscriptionId and resourceGroupName:

    curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01"
    {
      "compute": {
        "location": "",
        "name": "",
        "offer": "",
        "osType": "",
        "placementGroupId": "",
        "platformFaultDomain": "",
        "platformUpdateDomain": "",
        "publisher": "",
        "resourceGroupName": "",
        "sku": "",
        "subscriptionId": "",
        "tags": "",
        "version": "",
        "vmId": "",
        "vmScaleSetName": "",
        "vmSize": "",
        "zone": ""
      },
      "network": {
        "interface": [
          {
            "ipv4": {
              "ipAddress": [
                {
                  "privateIpAddress": "",
                  "publicIpAddress": ""
                }
              ],
              "subnet": [
                {
                  "address": "",
                  "prefix": ""
                }
              ]
            },
            "ipv6": {
              "ipAddress": []
            },
            "macAddress": ""
          }
        ]
      }
    }