Azure 实例元数据服务Azure Instance Metadata service

Azure 实例元数据服务提供有关可用于管理和配置虚拟机的正在运行的虚拟机实例的信息。The Azure Instance Metadata Service provides information about running virtual machine instances that can be used to manage and configure your virtual machines. 这包括 SKU、网络配置和即将发生的维护事件等信息。This includes information such as SKU, network configuration, and upcoming maintenance events. 若要详细了解可用信息类型,请参阅元数据 APIFor more information on what type of information is available, see metadata APIs.

Azure 的实例元数据服务是一个 REST 终结点,所有创建的 IaaS VM 可通过 Azure Resource Manager 访问此终结点。Azure's Instance Metadata Service is a REST Endpoint accessible to all IaaS VMs created via the Azure Resource Manager. 该终结点位于已知不可路由的 IP 地址 (169.254.169.254),该地址只能从 VM 中访问。The endpoint is available at a well-known non-routable IP address (169.254.169.254) that can be accessed only from within the VM.

Important

此服务在所有 Azure 区域中提供有正式版 。This service is generally available in all Azure Regions. 它会定期接收更新,发布有关虚拟机实例的新信息。It regularly receives updates to expose new information about virtual machine instances. 本页反映了最新可用的元数据 APIThis page reflects the up-to-date metadata APIs available.

服务可用性Service availability

此服务在所有 Azure 区域中提供有可用的正式版。The service is available in generally available Azure regions. 并非所有 API 版本在所有 Azure 区域中可用。Not all API version may be available in all Azure Regions.

区域Regions 可用性?Availability? 支持的版本Supported Versions
全球所有公开上市的 Azure 区域All Generally Available Global Azure Regions 正式版Generally Available 2017-04-02、2017-08-01、2017-12-01、2018-02-01、2018-04-02、2018-10-012017-04-02, 2017-08-01, 2017-12-01, 2018-02-01, 2018-04-02, 2018-10-01
Azure 美国政府版Azure US Government 正式版Generally Available 2017-04-02、2017-08-01、2017-12-01、2018-02-01、2018-04-02、2018-10-012017-04-02, 2017-08-01, 2017-12-01, 2018-02-01, 2018-04-02, 2018-10-01
Azure 中国Azure China 正式版Generally Available 2017-04-02、2017-08-01、2017-12-01、2018-02-01、2018-04-02、2018-10-012017-04-02, 2017-08-01, 2017-12-01, 2018-02-01, 2018-04-02, 2018-10-01
Azure 德国Azure Germany 正式版Generally Available 2017-04-02、2017-08-01、2017-12-01、2018-02-01、2018-04-02、2018-10-012017-04-02, 2017-08-01, 2017-12-01, 2018-02-01, 2018-04-02, 2018-10-01

当有服务更新且/或有可用的新支持版本时,此表将更新。This table is updated when there are service updates and or new supported versions are available.

若要试用实例元数据服务,请在上述区域中从 Azure 资源管理器Azure 门户创建一个 VM,并按照以下示例操作。To try out the Instance Metadata Service, create a VM from Azure Resource Manager or the Azure portal in the above regions and follow the examples below.

使用情况Usage

版本控制Versioning

已对实例元数据服务进行了版本控制。The Instance Metadata Service is versioned. 版本是必需的,全局 Azure 上的当前版本为 2018-10-01Versions are mandatory and the current version on Global Azure is 2018-10-01. 当前支持的版本为(2017-04-02、2017-08-01、2017-12-01、2018-02-01、2018-04-02、2018-10-01)。Current supported versions are (2017-04-02, 2017-08-01, 2017-12-01, 2018-02-01, 2018-04-02, 2018-10-01).

在添加更新的版本时,早期版本仍可供访问以保持兼容性(如果脚本依赖于特定的数据格式)。As newer versions are added, older versions can still be accessed for compatibility if your scripts have dependencies on specific data formats.

如果未指定版本,则会返回错误并列出受支持的最新版本。When no version is specified, an error is returned with a list of the newest supported versions.

Note

此响应是 JSON 字符串。The response is a JSON string. 以下示例响应显示清晰,可供阅读。The following example response is pretty-printed for readability.

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance"

响应Response

{
    "error": "Bad request. api-version was not specified in the request. For more information refer to aka.ms/azureimds",
    "newest-versions": [
        "2018-10-01",
        "2018-04-02",
        "2018-02-01"
    ]
}

使用标头Using headers

查询实例元数据服务时,必须提供标头 Metadata: true 以确保不会意外重定向请求。When you query the Instance Metadata Service, you must provide the header Metadata: true to ensure the request was not unintentionally redirected.

检索元数据Retrieving metadata

实例元数据可用于运行使用 Azure Resource Manager 创建/管理的 VM。Instance metadata is available for running VMs created/managed using Azure Resource Manager. 使用以下请求访问虚拟机实例的所有数据类别:Access all data categories for a virtual machine instance using the following request:

curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01"

Note

所有实例元数据查询都区分大小写。All instance metadata queries are case-sensitive.

数据输出Data output

默认情况下,实例元数据服务会返回 JSON 格式的数据 (Content-Type: application/json)。By default, the Instance Metadata Service returns data in JSON format (Content-Type: application/json). 但是,如果提出请求,不同 API 可以其他格式返回数据。However, different APIs return data in different formats if requested. 下表是有关 API 可支持的其他数据格式的参考。The following table is a reference of other data formats APIs may support.

APIAPI 默认数据格式Default Data Format 其他格式Other Formats
/instance/instance jsonjson texttext
/scheduledevents/scheduledevents jsonjson none
/attested/attested jsonjson none

若要访问非默认响应格式,请在请求中将所请求的格式指定为查询字符串参数。To access a non-default response format, specify the requested format as a query string parameter in the request. 例如:For example:

curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01&format=text"

Note

对于叶节点,format=json 不起作用。For leaf nodes the format=json doesn't work. 对于这些查询,如果默认格式是 JSON,则需要显式指定 format=textFor these queries format=text needs to be explicitly specified if the default format is json.

安全性Security

此实例元数据服务终结点只能从不可路由的 IP 地址上正在运行的虚拟机实例中访问。The Instance Metadata Service endpoint is accessible only from within the running virtual machine instance on a non-routable IP address. 此外,任何包含X-Forwarded-For标头的请求都会被服务拒绝。In addition, any request with a X-Forwarded-For header is rejected by the service. 请求必须包含 Metadata: true 标头,以确保实际请求是直接计划好的,而不是无意重定向的一部分。Requests must also contain a Metadata: true header to ensure that the actual request was directly intended and not a part of unintentional redirection.

错误Error

如果找不到某个数据元素,或者请求的格式不正确,则实例元数据服务返回标准 HTTP 错误。If there is a data element not found or a malformed request, the Instance Metadata Service returns standard HTTP errors. 例如:For example:

HTTP 状态代码HTTP Status Code 原因Reason
200 正常200 OK
400 错误的请求400 Bad Request 查询叶节点时缺少 Metadata: true 标头或缺少格式Missing Metadata: true header or missing the format when querying a leaf node
404 未找到404 Not Found 请求的元素不存在The requested element doesn't exist
不允许 405 方法405 Method Not Allowed 仅支持 GETPOST 请求Only GET and POST requests are supported
429 请求次数过多429 Too Many Requests 该 API 当前支持每秒最多 5 个查询The API currently supports a maximum of 5 queries per second
500 服务错误500 Service Error 请稍后重试Retry after some time

示例Examples

Note

所有 API 响应都是 JSON 字符串。All API responses are JSON strings. 以下所有响应示例都以美观的形式输出以提高可读性。All following example responses are pretty-printed for readability.

检索网络信息Retrieving network information

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance/network?api-version=2017-08-01"

响应Response

Note

此响应是 JSON 字符串。The response is a JSON string. 以下示例响应显示清晰,可供阅读。The following example response is pretty-printed for readability.

{
  "interface": [
    {
      "ipv4": {
        "ipAddress": [
          {
            "privateIpAddress": "10.1.0.4",
            "publicIpAddress": "X.X.X.X"
          }
        ],
        "subnet": [
          {
            "address": "10.1.0.0",
            "prefix": "24"
          }
        ]
      },
      "ipv6": {
        "ipAddress": []
      },
      "macAddress": "000D3AF806EC"
    }
  ]
}

检索公共 IP 地址Retrieving public IP address

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

检索实例的所有元数据Retrieving all metadata for an instance

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2018-10-01"

响应Response

Note

此响应是 JSON 字符串。The response is a JSON string. 以下示例响应显示清晰,可供阅读。The following example response is pretty-printed for readability.

{
  "compute": {
    "azEnvironment": "AZURECHINACLOUD",
    "location": "chinanorth",
    "name": "jubilee",
    "offer": "Windows-10",
    "osType": "Windows",
    "placementGroupId": "",
    "plan": {
        "name": "",
        "product": "",
        "publisher": ""
    },
    "platformFaultDomain": "1",
    "platformUpdateDomain": "1",
    "provider": "Microsoft.Compute",
    "publicKeys": [],
    "publisher": "MicrosoftWindowsDesktop",
    "resourceGroupName": "myrg",
    "sku": "rs4-pro",
    "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
    "tags": "Department:IT;Environment:Prod;Role:WorkerRole",
    "version": "17134.345.59",
    "vmId": "13f56399-bd52-4150-9748-7190aae1ff21",
    "vmScaleSetName": "",
    "vmSize": "Standard_D1",
    "zone": "1"
  },
  "network": {
    "interface": [
      {
        "ipv4": {
          "ipAddress": [
            {
              "privateIpAddress": "10.1.2.5",
              "publicIpAddress": "X.X.X.X"
            }
          ],
          "subnet": [
            {
              "address": "10.1.2.0",
              "prefix": "24"
            }
          ]
        },
        "ipv6": {
          "ipAddress": []
        },
        "macAddress": "000D3A36DDED"
      }
    ]
  }
}

在 Windows 虚拟机中检索元数据Retrieving metadata in Windows Virtual Machine

请求Request

可通过 curl 程序在 Windows 中检索实例元数据:Instance metadata can be retrieved in Windows via the curl program:

curl -H @{'Metadata'='true'} http://169.254.169.254/metadata/instance?api-version=2018-10-01 | select -ExpandProperty Content

还可以通过 Invoke-RestMethod PowerShell cmdlet 检索:Or through the Invoke-RestMethod PowerShell cmdlet:


Invoke-RestMethod -Headers @{"Metadata"="true"} -URI http://169.254.169.254/metadata/instance?api-version=2018-10-01 -Method get

响应Response

Note

此响应是 JSON 字符串。The response is a JSON string. 以下示例响应显示清晰,可供阅读。The following example response is pretty-printed for readability.

{
  "compute": {
    "azEnvironment": "AZURECHINACLOUD",
    "location": "chinanorth",
    "name": "SQLTest",
    "offer": "SQL2016SP1-WS2016",
    "osType": "Windows",
    "placementGroupId": "",
    "plan": {
        "name": "",
        "product": "",
        "publisher": ""
    },
    "platformFaultDomain": "0",
    "platformUpdateDomain": "0",
    "provider": "Microsoft.Compute",
    "publicKeys": [],
    "publisher": "MicrosoftSQLServer",
    "resourceGroupName": "myrg",
    "sku": "Enterprise",
    "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
    "tags": "Department:IT;Environment:Test;Role:WebRole",
    "version": "13.0.400110",
    "vmId": "453945c8-3923-4366-b2d3-ea4c80e9b70e",
    "vmScaleSetName": "",
    "vmSize": "Standard_DS2",
    "zone": ""
  },
  "network": {
    "interface": [
      {
        "ipv4": {
          "ipAddress": [
            {
              "privateIpAddress": "10.0.1.4",
              "publicIpAddress": "X.X.X.X"
            }
          ],
          "subnet": [
            {
              "address": "10.0.1.0",
              "prefix": "24"
            }
          ]
        },
        "ipv6": {
          "ipAddress": []
        },
        "macAddress": "002248020E1E"
      }
    ]
  }
}

元数据 APIMetadata APIs

可以通过元数据终结点使用以下 API:The following APIs are available through the metadata endpoint:

数据Data 说明Description 引入的版本Version Introduced
attestedattested 请参阅证明数据See Attested Data 2018-10-012018-10-01
instanceinstance 请参阅实例 APISee Instance API 2017-04-022017-04-02
scheduledeventsscheduledevents 请参阅计划事件See Scheduled Events 2017-08-012017-08-01

实例 APIInstance API

可以通过实例 API 使用以下计算类别:The following Compute categories are available through the Instance API:

Note

在元数据终结点中通过实例/计算访问以下类别Through the metadata endpoint, the following categories are accessed through instance/compute

数据Data 说明Description 引入的版本Version Introduced
azEnvironmentazEnvironment VM 运行时所在的 Azure 环境Azure Environment where the VM is running in 2018-10-012018-10-01
locationlocation VM 在其中运行的 Azure 区域Azure Region the VM is running in 2017-04-022017-04-02
namename VM 的名称Name of the VM 2017-04-022017-04-02
offeroffer 为 VM 映像提供信息。Offer information for the VM image. 此值只适用于 Azure 映像库中部署的图像。This value is only present for images deployed from Azure image gallery. 2017-04-022017-04-02
osTypeosType Linux 或 WindowsLinux or Windows 2017-04-022017-04-02
planplan 在 Azure 市场映像中 VM 的计划,包含名称、产品和发布者Plan for a VM in its an Azure Marketplace Image, contains name, product and publisher 2018-04-022018-04-02
platformUpdateDomainplatformUpdateDomain 正在运行 VM 的更新域Update domain the VM is running in 2017-04-022017-04-02
platformFaultDomainplatformFaultDomain 正在运行 VM 的容错域Fault domain the VM is running in 2017-04-022017-04-02
providerprovider VM 的提供商Provider of the VM 2018-10-012018-10-01
publicKeyspublicKeys 公钥的集合,已分配给 VM 和路径Collection of Public Keys assigned to the VM and paths 2018-04-022018-04-02
publisherpublisher VM 映像的发布者Publisher of the VM image 2017-04-022017-04-02
resourceGroupNameresourceGroupName 虚拟机的资源组Resource group for your Virtual Machine 2017-08-012017-08-01
skusku VM 映像的特定 SKUSpecific SKU for the VM image 2017-04-022017-04-02
subscriptionIdsubscriptionId 虚拟机的 Azure 订阅Azure subscription for the Virtual Machine 2017-08-012017-08-01
tagstags 虚拟机的标记Tags for your Virtual Machine 2017-08-012017-08-01
versionversion VM 映像的版本Version of the VM image 2017-04-022017-04-02
vmIdvmId VM 的唯一标识符Unique identifier for the VM 2017-04-022017-04-02
vmScaleSetNamevmScaleSetName 虚拟机规模集的虚拟机规模集名称Virtual Machine ScaleSet Name of your virtual machine scale set 2017-12-012017-12-01
vmSizevmSize VM 大小VM size 2017-04-022017-04-02
可以通过实例 API 使用以下网络类别:The following Network categories are available through the Instance API:

Note

在元数据终结点中通过实例/网络/接口访问以下类别Through the metadata endpoint, the following categories are accessed through instance/network/interface

数据Data 说明Description 引入的版本Version Introduced
ipv4/privateIpAddressipv4/privateIpAddress VM 的本地 IPv4 地址Local IPv4 address of the VM 2017-04-022017-04-02
ipv4/publicIpAddressipv4/publicIpAddress VM 的公共 IPv4 地址Public IPv4 address of the VM 2017-04-022017-04-02
subnet/addresssubnet/address VM 的子网地址Subnet address of the VM 2017-04-022017-04-02
subnet/prefixsubnet/prefix 子网前缀,例如 24Subnet prefix, example 24 2017-04-022017-04-02
macAddressmacAddress VM mac 地址VM mac address 2017-04-022017-04-02

证明数据Attested Data

实例元数据在 http 终结点上响应 169.254.169.254。Instance Metadata responds at http endpoint on 169.254.169.254. 实例元数据服务提供的部分方案是为了保证响应的数据来自 Azure。Part of the scenario served by Instance Metadata Service is to provide guarantees that the data responded is coming from Azure. 我们对此信息的一部分进行签名,以便市场映像可以确保其映像在 Azure 上运行。We sign part of this information so that marketplace images can be sure that it's their image running on Azure.

示例证明数据Example Attested Data

Note

所有 API 响应都是 JSON 字符串。All API responses are JSON strings. 以下示例响应显示清晰,可供阅读。The following example responses are pretty-printed for readability.

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/attested/document?api-version=2018-10-01&nonce=1234567890"

Api-version 是必填字段,证明数据支持的版本为 2018-10-01。Api-version is a mandatory field and the version supported for attested data is 2018-10-01. Nonce 是一个可选的 10 位字符串。Nonce is an optional 10-digit string provided. Nonce 可用于跟踪请求,如果未提供,则响应编码字符串中会返回当前 UTC 时间戳。Nonce can be used to track the request and if not provided, in response encoded string the current UTC timestamp is returned.

响应Response

Note

此响应是 JSON 字符串。The response is a JSON string. 以下示例响应显示清晰,可供阅读。The following example response is pretty-printed for readability.

{
"encoding":"pkcs7","signature":"MIIEEgYJKoZIhvcNAQcCoIIEAzCCA/8CAQExDzANBgkqhkiG9w0BAQsFADCBugYJKoZIhvcNAQcBoIGsBIGpeyJub25jZSI6IjEyMzQ1NjY3NjYiLCJwbGFuIjp7Im5hbWUiOiIiLCJwcm9kdWN0IjoiIiwicHVibGlzaGVyIjoiIn0sInRpbWVTdGFtcCI6eyJjcmVhdGVkT24iOiIxMS8yMC8xOCAyMjowNzozOSAtMDAwMCIsImV4cGlyZXNPbiI6IjExLzIwLzE4IDIyOjA4OjI0IC0wMDAwIn0sInZtSWQiOiIifaCCAj8wggI7MIIBpKADAgECAhBnxW5Kh8dslEBA0E2mIBJ0MA0GCSqGSIb3DQEBBAUAMCsxKTAnBgNVBAMTIHRlc3RzdWJkb21haW4ubWV0YWRhdGEuYXp1cmUuY29tMB4XDTE4MTEyMDIxNTc1N1oXDTE4MTIyMDIxNTc1NlowKzEpMCcGA1UEAxMgdGVzdHN1YmRvbWFpbi5tZXRhZGF0YS5henVyZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAML/tBo86ENWPzmXZ0kPkX5dY5QZ150mA8lommszE71x2sCLonzv4/UWk4H+jMMWRRwIea2CuQ5RhdWAHvKq6if4okKNt66fxm+YTVz9z0CTfCLmLT+nsdfOAsG1xZppEapC0Cd9vD6NCKyE8aYI1pliaeOnFjG0WvMY04uWz2MdAgMBAAGjYDBeMFwGA1UdAQRVMFOAENnYkHLa04Ut4Mpt7TkJFfyhLTArMSkwJwYDVQQDEyB0ZXN0c3ViZG9tYWluLm1ldGFkYXRhLmF6dXJlLmNvbYIQZ8VuSofHbJRAQNBNpiASdDANBgkqhkiG9w0BAQQFAAOBgQCLSM6aX5Bs1KHCJp4VQtxZPzXF71rVKCocHy3N9PTJQ9Fpnd+bYw2vSpQHg/AiG82WuDFpPReJvr7Pa938mZqW9HUOGjQKK2FYDTg6fXD8pkPdyghlX5boGWAMMrf7bFkup+lsT+n2tRw2wbNknO1tQ0wICtqy2VqzWwLi45RBwTGB6DCB5QIBATA/MCsxKTAnBgNVBAMTIHRlc3RzdWJkb21haW4ubWV0YWRhdGEuYXp1cmUuY29tAhBnxW5Kh8dslEBA0E2mIBJ0MA0GCSqGSIb3DQEBCwUAMA0GCSqGSIb3DQEBAQUABIGAld1BM/yYIqqv8SDE4kjQo3Ul/IKAVR8ETKcve5BAdGSNkTUooUGVniTXeuvDj5NkmazOaKZp9fEtByqqPOyw/nlXaZgOO44HDGiPUJ90xVYmfeK6p9RpJBu6kiKhnnYTelUk5u75phe5ZbMZfBhuPhXmYAdjc7Nmw97nx8NnprQ="
}

Note

签名 Blob 是 pkcs7 签名的文档版本。 它包含用于签名的证书以及 VM 详情,如 vmId、nonce、文档创建和到期的时间戳以及关于映像的计划信息。 计划信息只针对 Azure 市场映像填充。 证书可从响应中提取,用于验证响应是否有效、是否来自 Azure。The certificate can be extracted from the response and used to validate that the response is valid and is coming from Azure.

检索 Windows 虚拟机中的证明元数据Retrieving attested metadata in Windows Virtual Machine

请求Request

可以通过 Powershell 实用工具 curl 在 Windows 中检索实例元数据:Instance metadata can be retrieved in Windows via the PowerShell utility curl:

curl -H @{'Metadata'='true'} "http://169.254.169.254/metadata/attested/document?api-version=2018-10-01&nonce=1234567890" | select -ExpandProperty Content

或通过 Invoke-RestMethodcmdlet:Or through the Invoke-RestMethod cmdlet:

Invoke-RestMethod -Headers @{"Metadata"="true"} -URI "http://169.254.169.254/metadata/attested/document?api-version=2018-10-01&nonce=1234567890" -Method get

Api-version 是必填字段,证明数据支持的版本为 2018-10-01。Api-version is a mandatory field and the version supported for attested data is 2018-10-01. Nonce 是一个可选的 10 位字符串。Nonce is an optional 10-digit string provided. Nonce 可用于跟踪请求,如果未提供,则响应编码字符串中会返回当前 UTC 时间戳。Nonce can be used to track the request and if not provided, in response encoded string the current UTC timestamp is returned.

响应Response

Note

此响应是 JSON 字符串。The response is a JSON string. 以下示例响应显示清晰,可供阅读。The following example response is pretty-printed for readability.

{
 "encoding":"pkcs7","signature":"MIIEEgYJKoZIhvcNAQcCoIIEAzCCA/8CAQExDzANBgkqhkiG9w0BAQsFADCBugYJKoZIhvcNAQcBoIGsBIGpeyJub25jZSI6IjEyMzQ1NjY3NjYiLCJwbGFuIjp7Im5hbWUiOiIiLCJwcm9kdWN0IjoiIiwicHVibGlzaGVyIjoiIn0sInRpbWVTdGFtcCI6eyJjcmVhdGVkT24iOiIxMS8yMC8xOCAyMjowNzozOSAtMDAwMCIsImV4cGlyZXNPbiI6IjExLzIwLzE4IDIyOjA4OjI0IC0wMDAwIn0sInZtSWQiOiIifaCCAj8wggI7MIIBpKADAgECAhBnxW5Kh8dslEBA0E2mIBJ0MA0GCSqGSIb3DQEBBAUAMCsxKTAnBgNVBAMTIHRlc3RzdWJkb21haW4ubWV0YWRhdGEuYXp1cmUuY29tMB4XDTE4MTEyMDIxNTc1N1oXDTE4MTIyMDIxNTc1NlowKzEpMCcGA1UEAxMgdGVzdHN1YmRvbWFpbi5tZXRhZGF0YS5henVyZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAML/tBo86ENWPzmXZ0kPkX5dY5QZ150mA8lommszE71x2sCLonzv4/UWk4H+jMMWRRwIea2CuQ5RhdWAHvKq6if4okKNt66fxm+YTVz9z0CTfCLmLT+nsdfOAsG1xZppEapC0Cd9vD6NCKyE8aYI1pliaeOnFjG0WvMY04uWz2MdAgMBAAGjYDBeMFwGA1UdAQRVMFOAENnYkHLa04Ut4Mpt7TkJFfyhLTArMSkwJwYDVQQDEyB0ZXN0c3ViZG9tYWluLm1ldGFkYXRhLmF6dXJlLmNvbYIQZ8VuSofHbJRAQNBNpiASdDANBgkqhkiG9w0BAQQFAAOBgQCLSM6aX5Bs1KHCJp4VQtxZPzXF71rVKCocHy3N9PTJQ9Fpnd+bYw2vSpQHg/AiG82WuDFpPReJvr7Pa938mZqW9HUOGjQKK2FYDTg6fXD8pkPdyghlX5boGWAMMrf7bFkup+lsT+n2tRw2wbNknO1tQ0wICtqy2VqzWwLi45RBwTGB6DCB5QIBATA/MCsxKTAnBgNVBAMTIHRlc3RzdWJkb21haW4ubWV0YWRhdGEuYXp1cmUuY29tAhBnxW5Kh8dslEBA0E2mIBJ0MA0GCSqGSIb3DQEBCwUAMA0GCSqGSIb3DQEBAQUABIGAld1BM/yYIqqv8SDE4kjQo3Ul/IKAVR8ETKcve5BAdGSNkTUooUGVniTXeuvDj5NkmazOaKZp9fEtByqqPOyw/nlXaZgOO44HDGiPUJ90xVYmfeK6p9RpJBu6kiKhnnYTelUk5u75phe5ZbMZfBhuPhXmYAdjc7Nmw97nx8NnprQ="
}

签名 Blob 是 pkcs7 签名的文档版本。 它包含用于签名的证书以及 VM 详情,如 vmId、nonce、文档创建和到期的时间戳以及关于映像的计划信息。 计划信息只针对 Azure 市场映像填充。 证书可从响应中提取,用于验证响应是否有效、是否来自 Azure。The certificate can be extracted from the response and used to validate that the response is valid and is coming from Azure.

用法的示例方案Example scenarios for usage

跟踪 Azure 上正在运行的 VMTracking VM running on Azure

作为服务提供商,可能需要跟踪运行软件的 VM 数目,或者代理需要跟踪 VM 的唯一性。As a service provider, you may require to track the number of VMs running your software or have agents that need to track uniqueness of the VM. 为了能够获取 VM 的唯一 ID,请使用实例元数据服务中的 vmId 字段。To be able to get a unique ID for a VM, use the vmId field from Instance Metadata Service.

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance/compute/vmId?api-version=2017-08-01&format=text"

响应Response

5c08b38e-4d57-4c23-ac45-aca61037f084

基于容错/更新域放置容器、数据分区Placement of containers, data-partitions based fault/update domain

对于某些方案,不同数据副本的放置至关重要。For certain scenarios, placement of different data replicas is of prime importance. 例如,对于 HDFS 副本放置或者对于通过 orchestrator 放置容器,可能需要知道正在运行 VM 的 platformFaultDomainplatformUpdateDomainFor example, HDFS replica placement or container placement via an orchestrator may you require to know the platformFaultDomain and platformUpdateDomain the VM is running on.

可以直接通过实例元数据服务查询此数据。You can query this data directly via the Instance Metadata Service.

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance/compute/platformFaultDomain?api-version=2017-08-01&format=text"

响应Response

0

在支持案例期间获取有关 VM 的详细信息Getting more information about the VM during support case

作为服务提供商,你可能会接到支持电话,了解有关 VM 的详细信息。As a service provider, you may get a support call where you would like to know more information about the VM. 请求客户共享计算元数据可以提供基本信息,以支持专业人员了解有关 Azure 上的 VM 类型。Asking the customer to share the compute metadata can provide basic information for the support professional to know about the kind of VM on Azure.

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance/compute?api-version=2017-08-01"

响应Response

Note

此响应是 JSON 字符串。The response is a JSON string. 以下示例响应显示清晰,可供阅读。The following example response is pretty-printed for readability.

{
  "compute": {
    "location": "chinanorth",
    "name": "IMDSCanary",
    "offer": "RHEL",
    "osType": "Linux",
    "platformFaultDomain": "0",
    "platformUpdateDomain": "0",
    "publisher": "RedHat",
    "sku": "7.2",
    "version": "7.2.20161026",
    "vmId": "5c08b38e-4d57-4c23-ac45-aca61037f084",
    "vmSize": "Standard_DS2"
  }
}

获取 VM 所在的 Azure 环境Getting Azure Environment where the VM is running

Azure 具有各种主权云,如 Azure 中国云。Azure has various sovereign clouds like Azure China Cloud. 有时你需要使用 Azure 环境来做出一些运行时决策。Sometimes you need the Azure Environment to make some runtime decisions. 以下示例显示了如何实现此行为。The following sample shows you how you can achieve this behavior.

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance/compute/azEnvironment?api-version=2018-10-01&format=text"

响应Response

AZURECHINACLOUD

获取 VM 的标记Getting the tags for the VM

系统可能已将标记应用到 Azure VM,以便按逻辑方式将其组织成分类。Tags may have been applied to your Azure VM to logically organize them into a taxonomy. 可使用以下请求检索分配给 VM 的标记。The tags assigned to a VM can be retrieved by using the request below.

请求Request

curl -H Metadata:true "http://169.254.169.254/metadata/instance/compute/tags?api-version=2018-10-01&format=text"

响应Response

Department:IT;Environment:Test;Role:WebRole

Note

标记以分号分隔。The tags are semicolon separated. 如果编写的分析器以编程方式提取标记,则标记名称和值不应包含分号,这样分析器才能正常工作。If a parser is written to programmatically extract the tags, the tag names and values shouldn't contain semicolons in order for the parser to work correctly.

验证 VM 是否在 Azure 中运行Validating that the VM is running in Azure

市场供应商希望确保其软件仅许可在 Azure 中运行。Marketplace vendors want to ensure that their software is licensed to run only in Azure. 如果有人将 VHD 复制到本地,则应当有能力检测到这一情况。If someone copies the VHD out to on-premise, then they should have the ability to detect that. 通过调用实例元数据服务,市场供应商可以获得签名数据,以保证响应仅来自 Azure。By calling into Instance Metadata Service, Marketplace vendors can get signed data that guarantees response only from Azure.

Note

需要安装 jq。Requires jq to be installed.

请求Request

# Get the signature
curl  --silent -H Metadata:True http://169.254.169.254/metadata/attested/document?api-version=2018-10-01 | jq -r '.["signature"]' > signature
# Decode the signature
base64 -d signature > decodedsignature
#Get PKCS7 format
openssl pkcs7 -in decodedsignature -inform DER -out sign.pk7
# Get Public key out of pkc7
openssl pkcs7 -in decodedsignature -inform DER  -print_certs -out signer.pem
#Get the intermediate certificate
wget -q -O intermediate.cer "$(openssl x509 -in signer.pem -text -noout | grep " CA Issuers -" | awk -FURI: '{print $2}')"
openssl x509 -inform der -in intermediate.cer -out intermediate.pem
#Verify the contents
openssl smime -verify -in sign.pk7 -inform pem -noverify

响应Response

Verification successful
{"nonce":"20181128-001617",
  "plan":
    {
     "name":"",
     "product":"",
     "publisher":""
    },
"timeStamp":
  {
    "createdOn":"11/28/18 00:16:17 -0000",
    "expiresOn":"11/28/18 06:16:17 -0000"
  },
"vmId":"d3e0e374-fda6-4649-bbc9-7f20dc379f34"
}
数据Data 说明Description
noncenonce 用户提供了带有请求的可选字符串。User supplied optional string with the request. 如果请求中未提供 nonce,则返回当前 UTC 时间戳If no nonce was supplied in the request, the current UTC timestamp is returned
planplan 在 Azure 市场映像中 VM 的计划,包含名称、产品和发布者Plan for a VM in it's an Azure Marketplace Image, contains name, product, and publisher
timestamp/createdOntimestamp/createdOn 创建第一个签名文档的时间戳The timestamp at which the first signed document was created
timestamp/expiresOntimestamp/expiresOn 签名文档到期的时间戳The timestamp at which the signed document expires
vmIdvmId VM 的唯一标识符Unique identifier for the VM

验证签名Verifying the signature

获得上面的签名后,可以验证签名是否来自世纪互联。Once you get the signature above, you can verify that the signature is from 21Vianet. 还可以验证中间证书和证书链。Also you can verify the intermediate certificate and the certificate chain.

Note

公有云和主权云的证书将有所不同。The certificate for Public cloud and sovereign cloud will be different.

区域Regions 证书Certificate
全球所有公开上市的 Azure 区域All Generally Available Global Azure Regions metadata.azure.commetadata.azure.com
Azure 美国政府云Azure US Goverment Cloud metadata.azure.usmetadata.azure.us
Azure 中国Azure China metadata.azure.cnmetadata.azure.cn
Azure 德国Azure Germany metadata.microsoftazure.demetadata.microsoftazure.de

# Verify the subject name for the main certificate
openssl x509 -noout -subject -in signer.pem
# Verify the issuer for the main certificate
openssl x509 -noout -issuer -in signer.pem
#Validate the subject name for intermediate certificate
openssl x509 -noout -subject -in intermediate.pem
# Verify the issuer for the intermediate certificate
openssl x509 -noout -issuer -in intermediate.pem
# Verify the certificate chain
openssl verify -verbose -CAfile /etc/ssl/certs/Baltimore_CyberTrust_Root.pem -untrusted intermediate.pem signer.pem

如果由于验证期间出现网络限制,导致中间证书无法下载,可以固定中间证书。In cases where the intermediate certificate cannot be downloaded due to network constraints during validation, the intermediate certificate can be pinned. 但是,Azure 会根据标准的 PKI 做法滚动更新证书。However, Azure will roll over the certificates as per standard PKI practice. 发生滚动更新时,需要更新固定的证书。The pinned certificates would need to be updated when roll over happens. 每当规划某项更改来更新中间证书,就会更新 Azure 博客并向 Azure 客户发出通知。Whenever a change to update the intermediate certificate is planned, the Azure blog will be updated and Azure customers will be notified. 此处可找到中间证书。The intermediate certificates can be found here. 每个区域的中间证书可能并不相同。The intermediate certificates for each of the regions can be different.

Windows Server 中的故障转移群集Failover Clustering in Windows Server

在某些情况下,在使用故障转移群集查询实例元数据服务时,必须向路由表添加路由。For certain scenarios, when querying Instance Metadata Service with Failover Clustering, it is necessary to add a route to the routing table.

  1. 使用管理员特权打开命令提示符。Open command prompt with administrator privileges.

  2. 运行以下命令,并记下 IPv4 路由表中网络目标 (0.0.0.0) 接口的地址。Run the following command and note the address of the Interface for Network Destination (0.0.0.0) in the IPv4 Route Table.

    route print
    

    Note

    为简单起见,启用了故障转移群集的 Windows Server VM 的以下示例输出仅包含 IPv4 路由表。The following example output from a Windows Server VM with Failover Cluster enabled contains only the IPv4 Route Table for simplicity.

    IPv4 Route Table
    ===========================================================================
    Active Routes:
    Network Destination        Netmask          Gateway       Interface  Metric
              0.0.0.0          0.0.0.0         10.0.1.1        10.0.1.10    266
             10.0.1.0  255.255.255.192         On-link         10.0.1.10    266
            10.0.1.10  255.255.255.255         On-link         10.0.1.10    266
            10.0.1.15  255.255.255.255         On-link         10.0.1.10    266
            10.0.1.63  255.255.255.255         On-link         10.0.1.10    266
            127.0.0.0        255.0.0.0         On-link         127.0.0.1    331
            127.0.0.1  255.255.255.255         On-link         127.0.0.1    331
      127.255.255.255  255.255.255.255         On-link         127.0.0.1    331
          169.254.0.0      255.255.0.0         On-link     169.254.1.156    271
        169.254.1.156  255.255.255.255         On-link     169.254.1.156    271
      169.254.255.255  255.255.255.255         On-link     169.254.1.156    271
            224.0.0.0        240.0.0.0         On-link         127.0.0.1    331
            224.0.0.0        240.0.0.0         On-link     169.254.1.156    271
            224.0.0.0        240.0.0.0         On-link         10.0.1.10    266
      255.255.255.255  255.255.255.255         On-link         127.0.0.1    331
      255.255.255.255  255.255.255.255         On-link     169.254.1.156    271
      255.255.255.255  255.255.255.255         On-link         10.0.1.10    266
    
  3. 运行以下命令并使用网络目标 (0.0.0.0) 接口的地址,在此示例中为 10.0.1.10Run the following command and use the address of the Interface for Network Destination (0.0.0.0) which is (10.0.1.10) in this example.

route add 169.254.169.254/32 10.0.1.10 metric 1 -p

自定义数据Custom Data

实例元数据服务提供让 VM 访问其自定义数据的功能。Instance Metadata Service provides the ability for the VM to have access to its custom data. 二进制数据必须不到 64 KB,以 base64 编码形式提供给 VM。The binary data must be less than 64 KB and is provided to the VM in base64 encoded form. 若要详细了解如何使用自定义数据来创建 VM,请参阅使用 CustomData 部署虚拟机For details on how to create a VM with custom data, see Deploy a Virtual Machine with CustomData.

自定义数据可供在 VM 中运行的所有进程使用。Custom data is available to all processes running in the VM. 建议客户不要将机密信息插入自定义数据中。It is suggested that customers do not insert secret information into custom data.

在虚拟机中检索自定义数据Retrieving custom data in Virtual Machine

实例元数据服务向 VM 提供 base64 编码形式的自定义数据。Instance Metadata Service provides custom data to the VM in base64 encoded form. 以下示例解码 base64 编码的字符串。The following example decodes the base64 encoded string.

Note

此示例中的自定义数据解释为 ASCII 字符串,其内容是“My custom data.”。The custom data in this example is interpreted as an ASCII string that reads, "My custom data.".

请求Request

curl -H "Metadata:true" "http://169.254.169.254/metadata/instance/compute/customData?api-version=2019-02-01&&format=text" | base64 --decode

响应Response

My custom data.

使用 VM 中的不同语言调用元数据服务的示例Examples of calling metadata service using different languages inside the VM

语言Language 示例Example
RubyRuby https://github.com/Microsoft/azureimds/blob/master/IMDSSample.rb
GoGo https://github.com/Microsoft/azureimds/blob/master/imdssample.go
PythonPython https://github.com/Microsoft/azureimds/blob/master/IMDSSample.py
C++C++ https://github.com/Microsoft/azureimds/blob/master/IMDSSample-windows.cpp
C#C# https://github.com/Microsoft/azureimds/blob/master/IMDSSample.cs
JavascriptJavaScript https://github.com/Microsoft/azureimds/blob/master/IMDSSample.js
PowerShellPowerShell https://github.com/Microsoft/azureimds/blob/master/IMDSSample.ps1
BashBash https://github.com/Microsoft/azureimds/blob/master/IMDSSample.sh
PerlPerl https://github.com/Microsoft/azureimds/blob/master/IMDSSample.pl
JavaJava https://github.com/Microsoft/azureimds/blob/master/imdssample.java
Visual BasicVisual Basic https://github.com/Microsoft/azureimds/blob/master/IMDSSample.vb
PuppetPuppet https://github.com/keirans/azuremetadata

常见问题FAQ

  1. 我收到错误 400 Bad Request, Required metadata header not specifiedI am getting the error 400 Bad Request, Required metadata header not specified. 这是什么意思呢?What does this mean?

    • 实例元数据服务需要在请求中传递标头 Metadata: trueThe Instance Metadata Service requires the header Metadata: true to be passed in the request. 将该标头传入 REST 调用将允许访问实例元数据服务。Passing this header in the REST call allows access to the Instance Metadata Service.
  2. 为什么我无法获取我的 VM 的计算信息?Why am I not getting compute information for my VM?

    • 当前实例元数据服务仅支持 Azure Resource Manager 创建的实例。Currently the Instance Metadata Service only supports instances created with Azure Resource Manager. 将来可能会添加对云服务 VM 的支持。In the future, support for Cloud Service VMs might be added.
  3. 我刚才通过 Azure Resource Manager 创建了我的虚拟机。I created my Virtual Machine through Azure Resource Manager a while back. 为什么我无法看到计算元数据信息?Why am I not see compute metadata information?

    • 对于 2016 年 9 月之后创建的所有 VM,请添加标记以开始查看计算元数据。For any VMs created after Sep 2016, add a Tag to start seeing compute metadata. 对于早期 VM(在 2016 年 9 月之前创建),请在 VM 中添加/删除扩展或数据磁盘以刷新元数据。For older VMs (created before Sep 2016), add/remove extensions or data disks to the VM to refresh metadata.
  4. 我看不到为新版本填充的任何数据I am not seeing all data populated for new version

    • 对于 2016 年 9 月之后创建的所有 VM,请添加标记以开始查看计算元数据。For any VMs created after Sep 2016, add a Tag to start seeing compute metadata. 对于早期 VM(在 2016 年 9 月之前创建),请在 VM 中添加/删除扩展或数据磁盘以刷新元数据。For older VMs (created before Sep 2016), add/remove extensions or data disks to the VM to refresh metadata.
  5. 我为什么会收到错误 500 Internal Server ErrorWhy am I getting the error 500 Internal Server Error?

    • 请根据指数后退系统重试请求。Retry your request based on exponential back off system. 如果问题持续出现,请联系 Azure 支持部门。If the issue persists contact Azure support.
  6. 在何处共享其他问题/评论?Where do I share additional questions/comments?

  7. 这是否适用于虚拟机规模集实例?Would this work for Virtual Machine Scale Set Instance?

    • 是的,元数据服务可用于规模集实例。Yes Metadata service is available for Scale Set Instances.
  8. 如何获取服务支持?How do I get support for the service?

    • 若要获取该服务的支持,请针对长时间重试后仍无法获取元数据响应的 VM,在 Azure 门户中创建相关支持问题。To get support for the service, create a support issue in Azure portal for the VM where you are not able to get metadata response after long retries.
  9. 调用服务时请求超时?I get request timed out for my call to the service?

    • 必须从分配给 VM 的网卡的主 IP 地址进行元数据调用,此外,在已更改路由的情况下,网卡外必须存在地址 169.254.0.0/16 的路由。Metadata calls must be made from the primary IP address assigned to the network card of the VM, in addition in case you have changed your routes there must be a route for 169.254.0.0/16 address out of your network card.
  10. 我更新了虚拟机规模集中的标记,但与 VM 不同,它们未显示在实例中,这是怎么回事?I updated my tags in virtual machine scale set but they don't appear in the instances unlike VMs?

    • 目前,对于规模集,仅在重启/重置映像/或对实例的磁盘更改时,向 VM 显示标记。Currently for ScaleSets tags only show to the VM on a reboot/reimage/or a disk change to the instance.

后续步骤Next steps