How to programatically know the current region in an azure role?

后端 未结 3 1067
挽巷
挽巷 2021-01-12 20:09

I need to programmatically find the current region (e.g \"West US\" or \"East US\") where my current role is running. Is there any API to find this?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 21:08

    That information is available from the Azure Instance Metadata Service (IMDS). The REST endpoint for any VM running in the Azure public cloud is http://169.254.169.254/metadata/instance?api-version=2017-04-02. The metadata object contains two sub-objects, one for "compute" and one for "network". The region name appears in the "location" member of the "compute" object.

    Sample code in multiple languages for accessing various elements of IMDS data are available from the Microsoft/azureimds repo on github. Far more information than I show here is available through the 2018-10-01 version of the IMDS API; see IMDS docs for details.

    $ curl -s -H Metadata:True "http://169.254.169.254/metadata/instance?api-version=2017-04-02&format=json" | jq .
    {
      "compute": {
        "location": "westus2",
        "name": "samplevm",
        "offer": "UbuntuServer",
        "osType": "Linux",
        "platformFaultDomain": "0",
        "platformUpdateDomain": "0",
        "publisher": "Canonical",
        "sku": "18.04-LTS",
        "version": "18.04.201904020",
        "vmId": "(redacted)",
        "vmSize": "Standard_D2s_v3"
      },
      "network": {
        "interface": [
          {
            "ipv4": {
              "ipAddress": [
                {
                  "privateIpAddress": "10.0.0.7",
                  "publicIpAddress": ""
                }
              ],
              "subnet": [
                {
                  "address": "10.0.0.0",
                  "prefix": "24"
                }
              ]
            },
            "ipv6": {
              "ipAddress": []
            },
            "macAddress": "(redacted)"
          }
        ]
      }
    }
    

提交回复
热议问题