Azure 实例元数据服务 (Windows)Azure Instance Metadata Service (Windows)

Azure 实例元数据服务 (IMDS) 提供有关当前正在运行的虚拟机实例的信息。The Azure Instance Metadata Service (IMDS) provides information about currently running virtual machine instances. 可以使用它来管理和配置虚拟机。You can use it to manage and configure your virtual machines. 这些信息包括 SKU、存储、网络配置和即将发生的维护事件。This information includes the SKU, storage, network configurations, and upcoming maintenance events. 有关可用数据的完整列表,请参阅终结点类别摘要For a complete list of the data available, see the Endpoint Categories Summary.

IMDS 适用于运行虚拟机 (VM) 的实例和虚拟机规模集实例。IMDS is available for running instances of virtual machines (VMs) and virtual machine scale set instances. 所有终结点均支持使用 Azure 资源管理器创建和管理的 VM。All endpoints support VMs created and managed by using Azure Resource Manager. 只有“实例”类别的“经过证明的”类别和“网络”部分支持通过经典部署模型创建的 VM。Only the Attested category and Network portion of the Instance category support VMs created by using the classic deployment model. “经过证明的”终结点仅在有限的程度上提供这样的支持。The Attested endpoint does so only to a limited extent.

IMDS 是一个 REST API,在已知的、不可路由的 IP 地址 (169.254.169.254) 上提供。IMDS is a REST API that's available at a well-known, non-routable IP address (169.254.169.254). 只能从 VM 中访问它。You can only access it from within the VM. VM 与 IMDS 之间的通信绝不会离开主机。Communication between the VM and IMDS never leaves the host. 让 HTTP 客户端在查询 IMDS 时绕过 VM 中的 Web 代理并同等对待 169.254.169.254168.63.129.16Have your HTTP clients bypass web proxies within the VM when querying IMDS, and treat 169.254.169.254 the same as 168.63.129.16.

使用情况Usage

访问 Azure 实例元数据服务Access Azure Instance Metadata Service

若要访问 IMDS,请从 Azure 资源管理器Azure 门户创建一个 VM,并使用以下示例。To access IMDS, create a VM from Azure Resource Manager or the Azure portal, and use the following samples. 如需更多示例,请参阅 Azure 实例元数据示例For more examples, see Azure Instance Metadata Samples.

下面是用于检索实例的所有元数据的示例代码。Here's sample code to retrieve all metadata for an instance. 若要访问特定的数据源,请参阅终结点类别,其中概述了所有可用的功能。To access a specific data source, see Endpoint Categories for an overview of all available features.

请求Request

重要

此示例会绕过代理。This example bypasses proxies. 查询 IMDS 时,必须绕过代理。You must bypass proxies when querying IMDS. 有关其他信息,请参阅代理See Proxies for additional information.

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance?api-version=2020-09-01" | ConvertTo-Json -Depth 64

响应Response

备注

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

{
    "compute": {
        "azEnvironment": "AzureChinaCloud",
        "isHostCompatibilityLayerVm": "true",
        "licenseType":  "Windows_Client",
        "location": "chinanorth",
        "name": "examplevmname",
        "offer": "WindowsServer",
        "osProfile": {
            "adminUsername": "admin",
            "computerName": "examplevmname",
            "disablePasswordAuthentication": "true"
        },
        "osType": "Windows",
        "placementGroupId": "f67c14ab-e92c-408c-ae2d-da15866ec79a",
        "plan": {
            "name": "planName",
            "product": "planProduct",
            "publisher": "planPublisher"
        },
        "platformFaultDomain": "36",
        "platformUpdateDomain": "42",
        "publicKeys": [{
                "keyData": "ssh-rsa 0",
                "path": "/home/user/.ssh/authorized_keys0"
            },
            {
                "keyData": "ssh-rsa 1",
                "path": "/home/user/.ssh/authorized_keys1"
            }
        ],
        "publisher": "RDFE-Test-Microsoft-Windows-Server-Group",
        "resourceGroupName": "macikgo-test-may-23",
        "resourceId": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname",
        "securityProfile": {
            "secureBootEnabled": "true",
            "virtualTpmEnabled": "false"
        },
        "sku": "2019-Datacenter",
        "storageProfile": {
            "dataDisks": [{
                "caching": "None",
                "createOption": "Empty",
                "diskSizeGB": "1024",
                "image": {
                    "uri": ""
                },
                "lun": "0",
                "managedDisk": {
                    "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampledatadiskname",
                    "storageAccountType": "Standard_LRS"
                },
                "name": "exampledatadiskname",
                "vhd": {
                    "uri": ""
                },
                "writeAcceleratorEnabled": "false"
            }],
            "imageReference": {
                "id": "",
                "offer": "WindowsServer",
                "publisher": "MicrosoftWindowsServer",
                "sku": "2019-Datacenter",
                "version": "latest"
            },
            "osDisk": {
                "caching": "ReadWrite",
                "createOption": "FromImage",
                "diskSizeGB": "30",
                "diffDiskSettings": {
                    "option": "Local"
                },
                "encryptionSettings": {
                    "enabled": "false"
                },
                "image": {
                    "uri": ""
                },
                "managedDisk": {
                    "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampleosdiskname",
                    "storageAccountType": "Standard_LRS"
                },
                "name": "exampleosdiskname",
                "osType": "Windows",
                "vhd": {
                    "uri": ""
                },
                "writeAcceleratorEnabled": "false"
            }
        },
        "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
        "tags": "baz:bash;foo:bar",
        "userData": "Zm9vYmFy",
        "version": "15.05.22",
        "vmId": "02aab8a4-74ef-476e-8182-f6d2ba4166a6",
        "vmScaleSetName": "crpteste9vflji9",
        "vmSize": "Standard_A3",
        "zone": ""
    },
    "network": {
        "interface": [{
            "ipv4": {
               "ipAddress": [{
                    "privateIpAddress": "10.144.133.132",
                    "publicIpAddress": ""
                }],
                "subnet": [{
                    "address": "10.144.133.128",
                    "prefix": "26"
                }]
            },
            "ipv6": {
                "ipAddress": [
                 ]
            },
            "macAddress": "0011AAFFBB22"
        }]
    }
}

安全性和身份验证Security and authentication

实例元数据服务仅供从不可路由的 IP 地址上正在运行的虚拟机实例中访问。The Instance Metadata Service is only accessible from within a running virtual machine instance on a non-routable IP address. VM 仅限与它们自身相关的元数据/功能交互。VMs are limited to interacting with metadata/functionality that pertains to themselves. API 仅限 HTTP,且从不离开主机。The API is HTTP only and never leaves the host.

为了确保请求直接适用于 IMDS,并防止意外的或不需要的请求重定向,请求必须符合以下条件:In order to ensure that requests are directly intended for IMDS and prevent unintended or unwanted redirection of requests, requests:

  • 必须包含标头 Metadata: trueMust contain the header Metadata: true
  • 不得包含 X-Forwarded-For 标头Must not contain an X-Forwarded-For header

任何不符合这两项要求的请求都会被服务拒绝。Any request that does not meet both of these requirements will be rejected by the service.

重要

IMDS 不是敏感数据的通道。IMDS is not a channel for sensitive data. 此 API 不进行身份验证,并且对 VM 上的所有进程开放。The API is unauthenticated and open to all processes on the VM. 应将通过此服务公开的信息视为与 VM 内运行的所有应用程序共享的信息。Information exposed through this service should be considered as shared information to all applications running inside the VM.

代理Proxies

IMDS 不用于在代理后使用,系统不支持那样做。IMDS is not intended to be used behind a proxy and doing so is unsupported. 大多数 HTTP 客户端提供了一个选项,供你对你的请求禁用代理,当与 IMDS 通信时必须使用此功能。Most HTTP clients provide an option for you to disable proxies on your requests, and this functionality must be utilized when communicating with IMDS. 有关详细信息,请参阅客户端的文档。Consult your client's documentation for details.

重要

即使你不知道环境中的任何代理配置的信息,也必须重写任何默认的客户端代理设置。Even if you don't know of any proxy configuration in your environment, you still must override any default client proxy settings. 代理配置可以被自动发现,未能绕过这样的配置就必须冒服务中断的风险(如果将来要更改计算机的配置的话)。Proxy configurations can be automatically discovered, and failing to bypass such configurations exposes you to outage risks should the machine's configuration be changed in the future.

速率限制Rate limiting

一般情况下,对 IMDS 的请求限制为每秒 5 个请求。In general, requests to IMDS are limited to 5 requests per second. 系统会拒绝超过此阈值的请求,并显示 429 响应。Requests exceeding this threshold will be rejected with 429 responses. 托管标识类别的请求限制为每秒 20 个请求,并发请求数限制为 5 个。Requests to the Managed Identity category are limited to 20 requests per second and 5 concurrent requests.

HTTP 谓词HTTP verbs

目前支持以下 HTTP 谓词:The following HTTP verbs are currently supported:

谓词Verb 说明Description
GET 检索请求的资源Retrieve the requested resource

参数Parameters

终结点可以支持必需的和/或可选的参数。Endpoints may support required and/or optional parameters. 有关详细信息,请参阅架构以及相关的特定终结点的文档。See Schema and the documentation for the specific endpoint in question for details.

查询参数Query parameters

IMDS 终结点支持 HTTP 查询字符串参数。IMDS endpoints support HTTP query string parameters. 例如:For example:

http://169.254.169.254/metadata/instance/compute?api-version=2019-06-04&format=json

指定参数:Specifies the parameters:

名称Name Value
api-version 2019-06-04
format json

系统会拒绝具有重复的查询参数名称的请求。Requests with duplicate query parameter names will be rejected.

路由参数Route parameters

对于某些返回较大 json blob 的终结点,我们支持将路由参数追加到请求终结点,以便向下筛选到响应的某个子集:For some endpoints that return larger json blobs, we support appending route parameters to the request endpoint to filter down to a subset of the response:

http://169.254.169.254/metadata/<endpoint>/[<filter parameter>/...]?<query parameters>

参数对应的索引/键将用于逐级向下找到 json 对象(如果你与已分析的表示形式交互)。The parameters correspond to the indexes/keys that would be used to walk down the json object were you interacting with a parsed representation.

例如,/metatadata/instance 会返回 json 对象:For example, /metatadata/instance returns the json object:

{
    "compute": { ... },
    "network": {
        "interface": [
            {
                "ipv4": {
                   "ipAddress": [{
                        "privateIpAddress": "10.144.133.132",
                        "publicIpAddress": ""
                    }],
                    "subnet": [{
                        "address": "10.144.133.128",
                        "prefix": "26"
                    }]
                },
                "ipv6": {
                    "ipAddress": [
                     ]
                },
                "macAddress": "0011AAFFBB22"
            },
            ...
        ]
    }
}

若要将响应向下筛选到计算属性,则可发送以下请求:If we want to filter the response down to just the compute property, we would send the request:

http://169.254.169.254/metadata/instance/compute?api-version=<version>

类似地,若要筛选到嵌套的属性或特定的数组元素,则可不断地追加键:Similarly, if we want to filter to a nested property or specific array element we keep appending keys:

http://169.254.169.254/metadata/instance/network/interface/0?api-version=<version>

将会筛选到 Network.interface 属性中的第一个元素,并返回:would filter to the first element from the Network.interface property and return:

{
    "ipv4": {
       "ipAddress": [{
            "privateIpAddress": "10.144.133.132",
            "publicIpAddress": ""
        }],
        "subnet": [{
            "address": "10.144.133.128",
            "prefix": "26"
        }]
    },
    "ipv6": {
        "ipAddress": [
         ]
    },
    "macAddress": "0011AAFFBB22"
}

备注

筛选到叶节点时,format=json 将不起作用。When filtering to a leaf node, format=json doesn't work. 对于这些查询,需要显式指定 format=text,因为默认格式为 json。For these queries format=text needs to be explicitly specified since the default format is json.

架构Schema

数据格式Data format

默认情况下,IMDS 以 JSON 格式返回数据 (Content-Type: application/json)。By default, IMDS returns data in JSON format (Content-Type: application/json). 但是,支持响应筛选(请参阅路由参数)的终结点还支持 text 格式。However, endpoints that support response filtering (see Route Parameters) also support the format text.

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

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance?api-version=2017-08-01&format=text"

在 json 响应中,所有基元都将为 string 类型,缺失值或不适用的值始终包括在内,但会被设置为空字符串。In json responses, all primitives will be of type string, and missing or inapplicable values are always included but will be set to an empty string.

版本控制Versioning

IMDS 进行了版本控制,在 HTTP 请求中指定 API 版本是必需的。IMDS is versioned and specifying the API version in the HTTP request is mandatory. 此要求的唯一例外是 versions 终结点,该终结点可用于动态检索可用的 API 版本。The only exception to this requirement is the versions endpoint, which can be used to dynamically retrieve the available API versions.

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

如果不指定版本,则会收到错误消息,其中会列出受支持的最新版本:When you don't specify a version, you get an error with a list of the newest supported versions:

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

支持的 API 版本Supported API versions

  • 2017-03-012017-03-01
  • 2017-04-022017-04-02
  • 2017-08-012017-08-01
  • 2017-10-012017-10-01
  • 2017-12-012017-12-01
  • 2018-02-012018-02-01
  • 2018-04-022018-04-02
  • 2018-10-012018-10-01
  • 2019-02-012019-02-01
  • 2019-03-112019-03-11
  • 2019-04-302019-04-30
  • 2019-06-012019-06-01
  • 2019-06-042019-06-04
  • 2019-08-012019-08-01
  • 2019-08-152019-08-15
  • 2019-11-012019-11-01
  • 2020-06-012020-06-01
  • 2020-07-152020-07-15
  • 2020-09-012020-09-01
  • 2020-10-012020-10-01
  • 2020-12-012020-12-01
  • 2021-01-012021-01-01

SwaggerSwagger

可在以下位置找到 IMDS 的完整 Swagger 定义: https://github.com/Azure/azure-rest-api-specs/blob/master/specification/imds/data-plane/readme.mdA full Swagger definition for IMDS is available at: https://github.com/Azure/azure-rest-api-specs/blob/master/specification/imds/data-plane/readme.md

区域可用性Regional availability

此服务在所有 Azure 云中正式发布。The service is generally available in all Azure Clouds.

根终结点Root endpoint

根终结点为 http://169.254.169.254/metadataThe root endpoint is http://169.254.169.254/metadata.

终结点类别Endpoint categories

IMDS API 包含多个表示不同数据源的终结点类别,每一个都包含一个或多个终结点。The IMDS API contains multiple endpoint categories representing different data sources, each of which contains one or more endpoints. 有关详细信息,请查看每个类别。See each category for details.

类别根Category root 说明Description 引入的版本Version introduced
/metadata/attested 请参阅证明数据See Attested Data 2018-10-012018-10-01
/metadata/identity 请参阅通过 IMDS 托管的托管标识See Managed Identity via IMDS 2018-02-012018-02-01
/metadata/instance 请参阅实例元数据See Instance Metadata 2017-04-022017-04-02
/metadata/loadbalancer 请参阅通过 IMDS 检索负载均衡器元数据See Retrieve Load Balancer metadata via IMDS 2020-10-012020-10-01
/metadata/scheduledevents 请参阅通过 IMDS 计划的计划事件See Scheduled Events via IMDS 2017-08-012017-08-01
/metadata/versions 请参阅版本See Versions 不适用N/A

版本Versions

备注

此功能已随版本 2020-10-01 一起发布,该版本目前正处于推出阶段,在某些区域可能尚不可用。This feature was released alongside version 2020-10-01, which is currently being rolled out and may not yet be available in every region.

列出 API 版本List API versions

返回受支持的 API 版本的集合。Returns the set of supported API versions.

GET /metadata/versions

参数Parameters

无(此终结点未进行版本控制)。None (this endpoint is unversioned).

响应Response

{
  "apiVersions": [
    "2017-03-01",
    "2017-04-02",
    ...
  ]
}

实例元数据Instance metadata

获取 VM 元数据Get VM metadata

公开 VM 实例的重要元数据,其中包括计算、网络和存储。Exposes the important metadata for the VM instance, including compute, network, and storage.

GET /metadata/instance

参数Parameters

名称Name 必需/可选Required/Optional 说明Description
api-version 必需Required 用于处理请求的版本。The version used to service the request.
format 可选*Optional* 响应的格式(jsontext)。The format (json or text) of the response. *注意:使用请求参数时可能需要*Note: May be required when using request parameters

此终结点支持通过路由参数进行响应筛选。This endpoint supports response filtering via route parameters.

响应Response

{
    "compute": {
        "azEnvironment": "AzureChinaCloud",
        "isHostCompatibilityLayerVm": "true",
        "licenseType":  "Windows_Client",
        "location": "chinanorth",
        "name": "examplevmname",
        "offer": "WindowsServer",
        "osProfile": {
            "adminUsername": "admin",
            "computerName": "examplevmname",
            "disablePasswordAuthentication": "true"
        },
        "osType": "Windows",
        "placementGroupId": "f67c14ab-e92c-408c-ae2d-da15866ec79a",
        "plan": {
            "name": "planName",
            "product": "planProduct",
            "publisher": "planPublisher"
        },
        "platformFaultDomain": "36",
        "platformUpdateDomain": "42",
        "publicKeys": [{
                "keyData": "ssh-rsa 0",
                "path": "/home/user/.ssh/authorized_keys0"
            },
            {
                "keyData": "ssh-rsa 1",
                "path": "/home/user/.ssh/authorized_keys1"
            }
        ],
        "publisher": "RDFE-Test-Microsoft-Windows-Server-Group",
        "resourceGroupName": "macikgo-test-may-23",
        "resourceId": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname",
        "securityProfile": {
            "secureBootEnabled": "true",
            "virtualTpmEnabled": "false"
        },
        "sku": "2019-Datacenter",
        "storageProfile": {
            "dataDisks": [{
                "caching": "None",
                "createOption": "Empty",
                "diskSizeGB": "1024",
                "image": {
                    "uri": ""
                },
                "lun": "0",
                "managedDisk": {
                    "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampledatadiskname",
                    "storageAccountType": "Standard_LRS"
                },
                "name": "exampledatadiskname",
                "vhd": {
                    "uri": ""
                },
                "writeAcceleratorEnabled": "false"
            }],
            "imageReference": {
                "id": "",
                "offer": "WindowsServer",
                "publisher": "MicrosoftWindowsServer",
                "sku": "2019-Datacenter",
                "version": "latest"
            },
            "osDisk": {
                "caching": "ReadWrite",
                "createOption": "FromImage",
                "diskSizeGB": "30",
                "diffDiskSettings": {
                    "option": "Local"
                },
                "encryptionSettings": {
                    "enabled": "false"
                },
                "image": {
                    "uri": ""
                },
                "managedDisk": {
                    "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampleosdiskname",
                    "storageAccountType": "Standard_LRS"
                },
                "name": "exampleosdiskname",
                "osType": "Windows",
                "vhd": {
                    "uri": ""
                },
                "writeAcceleratorEnabled": "false"
            }
        },
        "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
        "tags": "baz:bash;foo:bar",
        "userData": "Zm9vYmFy",
        "version": "15.05.22",
        "vmId": "02aab8a4-74ef-476e-8182-f6d2ba4166a6",
        "vmScaleSetName": "crpteste9vflji9",
        "vmSize": "Standard_A3",
        "zone": ""
    },
    "network": {
        "interface": [{
            "ipv4": {
               "ipAddress": [{
                    "privateIpAddress": "10.144.133.132",
                    "publicIpAddress": ""
                }],
                "subnet": [{
                    "address": "10.144.133.128",
                    "prefix": "26"
                }]
            },
            "ipv6": {
                "ipAddress": [
                 ]
            },
            "macAddress": "0011AAFFBB22"
        }]
    }
}

架构明细:Schema breakdown:

计算Compute

数据Data 说明Description 引入的版本Version introduced
azEnvironment VM 运行时所在的 Azure 环境Azure Environment where the VM is running in 2018-10-012018-10-01
customData 此功能在 IMDS 中已弃用且已禁用。This feature is deprecated and disabled in IMDS. 它已被 userData 取代It has been superseded by userData 2019-02-012019-02-01
isHostCompatibilityLayerVm 标识 VM 是否在主机兼容性层上运行Identifies if the VM runs on the Host Compatibility Layer 2020-06-012020-06-01
licenseType Azure 混合权益许可证的类型。Type of license for Azure Hybrid Benefit. 这仅适用于启用了 AHB 的 VMThis is only present for AHB-enabled VMs 2020-09-012020-09-01
location VM 在其中运行的 Azure 区域Azure Region the VM is running in 2017-04-022017-04-02
name VM 的名称Name of the VM 2017-04-022017-04-02
offer 提供 VM 映像的信息,仅适用于从 Azure 映像库部署的映像Offer information for the VM image and is only present for images deployed from Azure image gallery 2017-04-022017-04-02
osProfile.adminUsername 指定管理员帐户的名称Specifies the name of the admin account 2020-07-152020-07-15
osProfile.computerName 指定计算机的名称Specifies the name of the computer 2020-07-152020-07-15
osProfile.disablePasswordAuthentication 指定是否禁用密码身份验证。Specifies if password authentication is disabled. 这仅适用于 Linux VMThis is only present for Linux VMs 2020-10-012020-10-01
osType Linux 或 WindowsLinux or Windows 2017-04-022017-04-02
placementGroupId 虚拟机规模集的放置组Placement Group of your virtual machine scale set 2017-08-012017-08-01
plan 包含 VM 的名称、产品和发布者(如果是 Azure 市场映像)的计划Plan containing name, product, and publisher for a VM if it is an Azure Marketplace Image 2018-04-022018-04-02
platformUpdateDomain 正在运行 VM 的更新域Update domain the VM is running in 2017-04-022017-04-02
platformFaultDomain 正在运行 VM 的容错域Fault domain the VM is running in 2017-04-022017-04-02
provider VM 的提供商Provider of the VM 2018-10-012018-10-01
publicKeys 公钥的集合,已分配给 VM 和路径Collection of Public Keys assigned to the VM and paths 2018-04-022018-04-02
publisher VM 映像的发布者Publisher of the VM image 2017-04-022017-04-02
resourceGroupName 虚拟机的资源组Resource group for your Virtual Machine 2017-08-012017-08-01
resourceId 资源的完全限定 IDThe fully qualified ID of the resource 2019-03-112019-03-11
sku VM 映像的特定 SKUSpecific SKU for the VM image 2017-04-022017-04-02
securityProfile.secureBootEnabled 标识是否在 VM 上启用了 UEFI 安全启动Identifies if UEFI secure boot is enabled on the VM 2020-06-012020-06-01
securityProfile.virtualTpmEnabled 标识是否在 VM 上启用了虚拟受信任的平台模块 (TPM)Identifies if the virtual Trusted Platform Module (TPM) is enabled on the VM 2020-06-012020-06-01
storageProfile 请参阅下面的“存储配置文件”See Storage Profile below 2019-06-012019-06-01
subscriptionId 虚拟机的 Azure 订阅Azure subscription for the Virtual Machine 2017-08-012017-08-01
tags 虚拟机的标记Tags for your Virtual Machine 2017-08-012017-08-01
tagsList 格式化为 JSON 数组以方便编程分析的标记Tags formatted as a JSON array for easier programmatic parsing 2019-06-042019-06-04
userData 创建 VM 时指定的一组数据,在预配期间或之后使用(Base64 编码)The set of data specified when the VM was created for use during or after provisioning (Base64 encoded) 2021-01-012021-01-01
version VM 映像的版本Version of the VM image 2017-04-022017-04-02
vmId VM 的唯一标识符Unique identifier for the VM 2017-04-022017-04-02
vmScaleSetName 虚拟机规模集的虚拟机规模集名称Virtual machine scale set Name of your virtual machine scale set 2017-12-012017-12-01
vmSize VM 大小VM size 2017-04-022017-04-02

存储配置文件Storage profile

VM 的存储配置文件分为三个类别:映像引用、OS 磁盘和数据磁盘。The storage profile of a VM is divided into three categories: image reference, OS disk, and data disks.

映像引用对象包含有关 OS 映像的以下信息:The image reference object contains the following information about the OS image:

数据Data 说明Description
id 资源 IDResource ID
offer 平台或市场映像的套餐Offer of the platform or marketplace image
publisher 映像发布者Image publisher
sku 映像 SKUImage sku
version 平台或市场映像的版本Version of the platform or marketplace image

OS 磁盘对象包含有关 VM 所用 OS 磁盘的以下信息:The OS disk object contains the following information about the OS disk used by the VM:

数据Data 说明Description
caching 缓存要求Caching requirements
createOption 有关 VM 创建方式的信息Information about how the VM was created
diffDiskSettings 临时磁盘设置Ephemeral disk settings
diskSizeGB 磁盘大小 (GB)Size of the disk in GB
image 源用户映像虚拟硬盘Source user image virtual hard disk
lun 磁盘的逻辑单元号Logical unit number of the disk
managedDisk 托管磁盘参数Managed disk parameters
name 磁盘名称Disk name
vhd 虚拟硬盘Virtual hard disk
writeAcceleratorEnabled 磁盘上是否启用了 writeAcceleratorWhether or not writeAccelerator is enabled on the disk

数据磁盘阵列包含附加到 VM 的数据磁盘列表。The data disks array contains a list of data disks attached to the VM. 每个数据磁盘对象包含以下信息:Each data disk object contains the following information:

数据Data 说明Description
caching 缓存要求Caching requirements
createOption 有关 VM 创建方式的信息Information about how the VM was created
diffDiskSettings 临时磁盘设置Ephemeral disk settings
diskSizeGB 磁盘大小 (GB)Size of the disk in GB
encryptionSettings 磁盘的加密设置Encryption settings for the disk
image 源用户映像虚拟硬盘Source user image virtual hard disk
managedDisk 托管磁盘参数Managed disk parameters
name 磁盘名称Disk name
osType 磁盘中包含的 OS 类型Type of OS included in the disk
vhd 虚拟硬盘Virtual hard disk
writeAcceleratorEnabled 磁盘上是否启用了 writeAcceleratorWhether or not writeAccelerator is enabled on the disk

NetworkNetwork

数据Data 说明Description 引入的版本Version introduced
ipv4.privateIpAddress VM 的本地 IPv4 地址Local IPv4 address of the VM 2017-04-022017-04-02
ipv4.publicIpAddress VM 的公共 IPv4 地址Public IPv4 address of the VM 2017-04-022017-04-02
subnet.address VM 的子网地址Subnet address of the VM 2017-04-022017-04-02
subnet.prefix 子网前缀,例如 24Subnet prefix, example 24 2017-04-022017-04-02
ipv6.ipAddress VM 的本地 IPv6 地址Local IPv6 address of the VM 2017-04-022017-04-02
macAddress VM mac 地址VM mac address 2017-04-022017-04-02

获取用户数据Get user data

在创建新 VM 时,可以指定一组要在 VM 预配期间或之后使用的数据,并通过 IMDS 进行检索。When creating a new VM, you can specify a set of data to be used during or after the VM provision, and retrieve it through IMDS. 若要设置用户数据,请使用此处的快速入门模板。To set up user data, utilize the quickstart template here. 下面的示例介绍如何通过 IMDS 检索此数据。The sample below shows how to retrieve this data through IMDS.

备注

此功能随版本 2021-01-01 发布,取决于 Azure 平台更新,目前正在推出,但可能尚未在所有区域提供。This feature is released with version 2021-01-01 and depends upon an update to the Azure platform, which is currently being rolled out and may not yet be available in every region.

备注

安全声明:IMDS 对 VM 上的所有应用程序开放,敏感数据不应放在用户数据中。Security notice: IMDS is open to all applications on the VM, sensitive data should not be placed in the user data.

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute/userData?api-version=2021-01-01&format=text" | base64 --decode

示例 1:跟踪 Azure 上正在运行的 VMSample 1: Tracking 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

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute/vmId?api-version=2017-08-01&format=text"

响应Response

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

示例 2:不同数据副本的放置Sample 2: Placement of different data replicas

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

可以通过 IMDS 直接查询此数据。You can query this data directly via IMDS.

请求Request

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute/platformFaultDomain?api-version=2017-08-01&format=text"

响应Response

0

示例 3:获取 VM 标记Sample 3: Get VM tags

VM 标记包含在实例/计算/标记终结点下的实例 API。VM tags are included the instance API under instance/compute/tags endpoint. 标记可能已应用到 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

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute/tags?api-version=2017-08-01&format=text"

响应Response

Department:IT;ReferenceNumber:123456;TestStatus:Pending

tags 字段是带有用分号分隔的标记的字符串。The tags field is a string with the tags delimited by semicolons. 如果标记本身使用了分号,则此输出可能会出现问题。This output can be a problem if semicolons are used in the tags themselves. 如果编写分析程序以编程方式提取标记,则应该依赖于 tagsList 字段。If a parser is written to programmatically extract the tags, you should rely on the tagsList field. tagsList 字段是不带分隔符的 JSON 数组,因此更易于分析。The tagsList field is a JSON array with no delimiters, and consequently, easier to parse. 可以使用以下请求检索分配给 VM 的 tagsList。The tagsList assigned to a VM can be retrieved by using the request below.

请求Request

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute/tagsList?api-version=2019-06-04" | ConvertTo-Json -Depth 64

响应Response

{
    "value":  [
                  {
                      "name":  "Department",
                      "value":  "IT"
                  },
                  {
                      "name":  "ReferenceNumber",
                      "value":  "123456"
                  },
                  {
                      "name":  "TestStatus",
                      "value":  "Pending"
                  }
              ],
    "Count":  3
}

示例 4:在支持案例期间获取有关 VM 的详细信息Sample 4: Get 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

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute?api-version=2020-09-01" | ConvertTo-Json -Depth 64

响应Response

备注

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

{
    "azEnvironment": "AzureChinaCloud",
    "isHostCompatibilityLayerVm": "true",
    "licenseType":  "Windows_Client",
    "location": "chinanorth",
    "name": "examplevmname",
    "offer": "WindowsServer",
    "osProfile": {
        "adminUsername": "admin",
        "computerName": "examplevmname",
        "disablePasswordAuthentication": "true"
    },
    "osType": "Windows",
    "placementGroupId": "f67c14ab-e92c-408c-ae2d-da15866ec79a",
    "plan": {
        "name": "planName",
        "product": "planProduct",
        "publisher": "planPublisher"
    },
    "platformFaultDomain": "36",
    "platformUpdateDomain": "42",
    "publicKeys": [{
            "keyData": "ssh-rsa 0",
            "path": "/home/user/.ssh/authorized_keys0"
        },
        {
            "keyData": "ssh-rsa 1",
            "path": "/home/user/.ssh/authorized_keys1"
        }
    ],
    "publisher": "RDFE-Test-Microsoft-Windows-Server-Group",
    "resourceGroupName": "macikgo-test-may-23",
    "resourceId": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname",
    "securityProfile": {
        "secureBootEnabled": "true",
        "virtualTpmEnabled": "false"
    },
    "sku": "2019-Datacenter",
    "storageProfile": {
        "dataDisks": [{
            "caching": "None",
            "createOption": "Empty",
            "diskSizeGB": "1024",
            "image": {
                "uri": ""
            },
            "lun": "0",
            "managedDisk": {
                "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampledatadiskname",
                "storageAccountType": "Standard_LRS"
            },
            "name": "exampledatadiskname",
            "vhd": {
                "uri": ""
            },
            "writeAcceleratorEnabled": "false"
        }],
        "imageReference": {
            "id": "",
            "offer": "WindowsServer",
            "publisher": "MicrosoftWindowsServer",
            "sku": "2019-Datacenter",
            "version": "latest"
        },
        "osDisk": {
            "caching": "ReadWrite",
            "createOption": "FromImage",
            "diskSizeGB": "30",
            "diffDiskSettings": {
                "option": "Local"
            },
            "encryptionSettings": {
                "enabled": "false"
            },
            "image": {
                "uri": ""
            },
            "managedDisk": {
                "id": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampleosdiskname",
                "storageAccountType": "Standard_LRS"
            },
            "name": "exampleosdiskname",
            "osType": "Windows",
            "vhd": {
                "uri": ""
            },
            "writeAcceleratorEnabled": "false"
        }
    },
    "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
    "tags": "baz:bash;foo:bar",
    "version": "15.05.22",
    "vmId": "02aab8a4-74ef-476e-8182-f6d2ba4166a6",
    "vmScaleSetName": "crpteste9vflji9",
    "vmSize": "Standard_A3",
    "zone": ""
}

示例 5:获取运行 VM 的 Azure 环境Sample 5: Get the 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

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/compute/azEnvironment?api-version=2018-10-01&format=text"

响应Response

AzureChinaCloud

此处列出了 Azure 环境的云和值。The cloud and the values of the Azure environment are listed here.

Cloud Azure 环境Azure environment
Azure 中国世纪互联Azure China 21Vianet AzureChinaCloudAzureChinaCloud

示例 6:检索网络信息Sample 6: Retrieve network information

请求Request

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/network?api-version=2017-08-01" | ConvertTo-Json  -Depth 64

响应Response

{
  "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"
    }
  ]
}

示例 7:检索公共 IP 地址Sample 7: Retrieve public IP address

Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-08-01&format=text"

证明数据Attested data

获取“经过证明的”数据Get Attested data

IMDS 可帮助确保提供的数据来自 Azure。IMDS helps to provide guarantees that the data provided is coming from Azure. Azure 会对此信息中的部分进行签名,以便你可以确认 Azure 市场中的映像是你正在 Azure 上运行的映像。Azure signs part of this information, so you can confirm that an image in Azure Marketplace is the one you are running on Azure.

GET /metadata/attested/document

参数Parameters

名称Name 必需/可选Required/Optional 说明Description
api-version 必需Required 用于处理请求的版本。The version used to service the request.
nonce 可选Optional 用作加密 nonce 的 10 位字符串。A 10-digit string that serves as a cryptographic nonce. 如果未提供值,则 IMDS 使用当前的 UTC 时间戳。If no value is provided, IMDS uses the current UTC timestamp.

响应Response

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

备注

由于 IMDS 的缓存机制,可能会返回以前缓存的 nonce 值。Due to IMDS's caching mechanism, a previously cached nonce value may be returned.

签名 blob 是 pkcs7 签名的文档版本。The signature blob is a pkcs7-signed version of document. 它包含用于签名的证书以及某些特定于 VM 的详细信息。It contains the certificate used for signing along with certain VM-specific details.

对于使用 Azure 资源管理器创建的 VM,该文档包括 vmIdskunoncesubscriptionId、文档创建和到期的 timeStamp 以及关于映像的计划信息。For VMs created by using Azure Resource Manager, the document includes vmId, sku, nonce, subscriptionId, timeStamp for creation and expiry of the document, and the plan information about the image. 该计划信息只针对 Azure 市场映像进行填充。The plan information is only populated for Azure Marketplace images.

对于使用经典部署模型创建的 VM,仅保证填充 vmIdFor VMs created by using the classic deployment model, only the vmId is guaranteed to be populated. 可以从响应中提取证书,并使用它来确认响应是否有效并来自 Azure。You can extract the certificate from the response, and use it to confirm that the response is valid and is coming from Azure.

解码的文档包含以下字段:The decoded document contains the following fields:

数据Data 说明Description 引入的版本Version introduced
licenseType Azure 混合权益许可证的类型。Type of license for Azure Hybrid Benefit. 这仅适用于启用了 AHB 的 VM。This is only present for AHB-enabled VMs. 2020-09-012020-09-01
nonce 可以随请求提供的可选字符串。A string that can be optionally provided with the request. 如果未提供 nonce,则会使用当前的协调世界时时间戳。If no nonce was supplied, the current Coordinated Universal Time timestamp is used. 2018-10-012018-10-01
plan Azure 市场映像计划The Azure Marketplace Image plan. 包含计划 ID(名称)、产品映像或产品/服务(产品)和发布者 ID(发布者)。Contains the plan ID (name), product image or offer (product), and publisher ID (publisher). 2018-10-012018-10-01
timestamp.createdOn 创建签名文档时的 UTC 时间戳The UTC timestamp for when the signed document was created 2018-20-012018-20-01
timestamp.expiresOn 签名文档到期时的 UTC 时间戳The UTC timestamp for when the signed document expires 2018-10-012018-10-01
vmId VM 的唯一标识符Unique identifier for the VM 2018-10-012018-10-01
subscriptionId 虚拟机的 Azure 订阅Azure subscription for the Virtual Machine 2019-04-302019-04-30
sku VM 映像的特定 SKUSpecific SKU for the VM image 2019-11-012019-11-01

备注

对于经典(非 Azure 资源管理器)VM,只保证填充 vmId。For Classic (non-Azure Resource Manager) VMs, only the vmId is guaranteed to be populated.

示例文档:Example document:

{
   "nonce":"20201130-211924",
   "plan":{
      "name":"planName",
      "product":"planProduct",
      "publisher":"planPublisher"
   },
   "sku":"Windows-Server-2012-R2-Datacenter",
   "subscriptionId":"8d10da13-8125-4ba9-a717-bf7490507b3d",
   "timeStamp":{
      "createdOn":"11/30/20 21:19:19 -0000",
      "expiresOn":"11/30/20 21:19:24 -0000"
   },
   "vmId":"02aab8a4-74ef-476e-8182-f6d2ba4166a6"
}

示例 1:验证 VM 是否在 Azure 中运行Sample 1: Validate that the VM is running in Azure

Azure 市场供应商希望确保其软件仅获许在 Azure 中运行。Vendors in Azure Marketplace want to ensure that their software is licensed to run only in Azure. 如果有人将 VHD 复制到本地环境,则供应商需要能够检测到此操作。If someone copies the VHD to an on-premises environment, the vendor needs to be able to detect that. 通过 IMDS,这些供应商可以获取能确保只从 Azure 响应的签名数据。Through IMDS, these vendors can get signed data that guarantees response only from Azure.

备注

此示例需要安装 jq 实用工具。This sample requires the jq utility to be installed.

验证Validation

# Get the signature
$attestedDoc = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri http://169.254.169.254/metadata/attested/document?api-version=2020-09-01
# Decode the signature
$signature = [System.Convert]::FromBase64String($attestedDoc.signature)

验证签名是否来自 Azure 并检查证书链中是否存在错误。Verify that the signature is from Azure and check the certificate chain for errors.

# Get certificate chain
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]($signature)
$chain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain
$chain.Build($cert)
# Print the Subject of each certificate in the chain
foreach($element in $chain.ChainElements)
{
    Write-Host $element.Certificate.Subject
}

# Get the content of the signed document
Add-Type -AssemblyName System.Security
$signedCms = New-Object -TypeName System.Security.Cryptography.Pkcs.SignedCms
$signedCms.Decode($signature);
$content = [System.Text.Encoding]::UTF8.GetString($signedCms.ContentInfo.Content)
Write-Host "Attested data: " $content
$json = $content | ConvertFrom-Json
# Do additional validation here

备注

由于 IMDS 的缓存机制,可能会返回以前缓存的 nonce 值。Due to IMDS's caching mechanism, a previously cached nonce value might be returned.

如果在初始请求中提供了 nonce 参数,则可以比较签名文档中的 nonceThe nonce in the signed document can be compared if you provided a nonce parameter in the initial request.

备注

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

Cloud 证书Certificate
Azure 中国世纪互联Azure China 21Vianet *.metadata.azure.cn*.metadata.azure.cn

备注

对于公有云,证书可能不完全匹配 metadata.azure.comThe certificates might not have an exact match of metadata.azure.com for the public cloud. 出于此原因,证书验证应允许任何 .metadata.azure.com 子域中的公用名称。For this reason, the certification validation should allow a common name from any .metadata.azure.com subdomain.

如果由于验证期间出现网络限制,导致中间证书无法下载,可以固定中间证书。In cases where the intermediate certificate can't be downloaded due to network constraints during validation, you can pin the intermediate certificate. Azure 会滚动更新证书,这是标准 PKI 做法。Azure rolls over the certificates, which is standard PKI practice. 发生滚动更新时,必须更新固定的证书。You must update the pinned certificates when rollover happens. 每当规划某项更改来更新中间证书时,就会更新 Azure 博客并向 Azure 客户发出通知。Whenever a change to update the intermediate certificate is planned, the Azure blog is updated, and Azure customers are notified.

可在 PKI 存储库中找到中间证书。You can find the intermediate certificates in the PKI repository. 每个区域的中间证书可能不同。The intermediate certificates for each of the regions can be different.

备注

Azure 中国世纪互联的中间证书将来自 DigiCert 全局根 CA(而不是 Baltimore)。The intermediate certificate for Azure China 21Vianet will be from DigiCert Global Root CA, instead of Baltimore. 如果在更改根证书链颁发机构的过程中已固定 Azure 中国的中间证书,则必须更新中间证书。If you pinned the intermediate certificates for Azure China as part of a root chain authority change, the intermediate certificates must be updated.

托管标识Managed identity

可以在 VM 上启用由系统分配的托管标识。A managed identity, assigned by the system, can be enabled on the VM. 还可以将一个或多个用户分配的托管标识分配给 VM。You can also assign one or more user-assigned managed identities to the VM. 然后,可以从 IMDS 请求托管标识的令牌。You can then request tokens for managed identities from IMDS. 使用这些令牌来通过其他 Azure 服务(如 Azure Key Vault)进行身份验证。Use these tokens to authenticate with other Azure services, such as Azure Key Vault.

有关启用此功能的详细步骤,请参阅获取访问令牌For detailed steps to enable this feature, see Acquire an access token.

负载均衡器元数据Load Balancer Metadata

将虚拟机或虚拟机集实例置于 Azure 标准负载均衡器后面时,可以使用 IMDS 检索与负载均衡器和实例相关的元数据。When you place virtual machine or virtual machine set instances behind an Azure Standard Load Balancer, you can use IMDS to retrieve metadata related to the load balancer and the instances. 有关详细信息,请参阅检索负载均衡器信息。For more information, see Retrieve load balancer information .

计划事件Scheduled events

可以使用 IMDS 获取计划事件的状态。You can obtain the status of the scheduled events by using IMDS. 然后,用户可以指定一组在发生这些事件时要运行的操作。Then the user can specify a set of actions to run upon these events. 有关详细信息,请参阅 Linux 计划事件Windows 计划事件For more information, see Scheduled events for Linux or Scheduled events for Windows.

不同语言的示例代码Sample code in different languages

下表列出了在 VM 中使用不同语言调用 IMDS 的相关示例:The following table lists samples of calling IMDS by using different languages inside the VM:

语言Language 示例Example
BashBash https://github.com/Microsoft/azureimds/blob/master/IMDSSample.sh
C#C# https://github.com/Microsoft/azureimds/blob/master/IMDSSample.cs
GoGo https://github.com/Microsoft/azureimds/blob/master/imdssample.go
JavaJava https://github.com/Microsoft/azureimds/blob/master/imdssample.java
NodeJSNodeJS https://github.com/Microsoft/azureimds/blob/master/IMDSSample.js
PerlPerl https://github.com/Microsoft/azureimds/blob/master/IMDSSample.pl
PowerShellPowerShell https://github.com/Microsoft/azureimds/blob/master/IMDSSample.ps1
PuppetPuppet https://github.com/keirans/azuremetadata
PythonPython https://github.com/Microsoft/azureimds/blob/master/IMDSSample.py
RubyRuby https://github.com/Microsoft/azureimds/blob/master/IMDSSample.rb

错误和调试Errors and debugging

如果找不到某个数据元素,或者请求的格式不正确,则实例元数据服务返回标准 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 OK 请求已成功。The request was successful.
400 Bad Request 查询叶节点时缺少 Metadata: true 标头或缺少参数 format=jsonMissing Metadata: true header or missing parameter format=json when querying a leaf node
404 Not Found 请求的元素不存在The requested element doesn't exist
405 Method Not Allowed 此终结点不支持 HTTP 方法(谓词)。The HTTP method (verb) is not supported on the endpoint.
410 Gone 在一段时间后重试最长 70 秒Retry after some time for a max of 70 seconds
429 Too Many Requests 已超出 API 速率限制API Rate Limits have been exceeded
500 Service Error 请稍后重试Retry after some time

常见问题Frequently asked questions

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

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

    • 当前 IMDS 仅支持 Azure 资源管理器创建的实例。Currently, IMDS only supports instances created with Azure Resource Manager.
  • 我一段时间以前通过 Azure 资源管理器创建了 VM。I created my VM through Azure Resource Manager some time ago. 为什么我无法看到计算元数据信息?Why am I not seeing compute metadata information?

    • 如果在 2016 年 9 月之后创建了 VM,请添加标记以开始查看计算元数据。If you created your VM after September 2016, add a tag to start seeing compute metadata. 如果在 2016 年 9 月之前创建了 VM,请在 VM 实例中添加或删除扩展或数据磁盘以刷新元数据。If you created your VM before September 2016, add or remove extensions or data disks to the VM instance to refresh metadata.
  • 用户数据与自定义数据是否相同?Is user data the same as custom data?

    • 用户数据提供了与自定义数据类似的功能,使你可以将自己的元数据传递给 VM 实例。User data offers the similar functionality to custom data, allowing you to pass your own metadata to the VM instance. 不同之处在于,用户数据是通过 IMDS 进行检索的,并且在 VM 实例的整个生存期内保持不变。The difference is, user data is retrieved through IMDS, and is persistent throughout the lifetime of the VM instance. 现有的自定义数据功能将继续按照本文所述正常运行。Existing custom data feature will continue to work as described in this article. 但是,只能通过本地系统文件夹获取自定义数据,而不能通过 IMDS 获取。However you can only get custom data through local system folder, not through IMDS.
  • 为什么我看不到为新版本填充的任何数据?Why am I not seeing all data populated for a new version?

    • 如果在 2016 年 9 月之后创建了 VM,请添加标记以开始查看计算元数据。If you created your VM after September 2016, add a tag to start seeing compute metadata. 如果在 2016 年 9 月之前创建了 VM,请在 VM 实例中添加或删除扩展或数据磁盘以刷新元数据。If you created your VM before September 2016, add or remove extensions or data disks to the VM instance to refresh metadata.
  • 我为什么会收到错误 500 Internal Server Error410 Resource GoneWhy am I getting the error 500 Internal Server Error or 410 Resource Gone?

    • 请重试请求。Retry your request. 有关详细信息,请参阅临时故障处理For more information, see Transient fault handling. 如果问题持续存在,请在 Azure 门户中为 VM 创建支持问题。If the problem persists, create a support issue in the Azure portal for the VM.
  • 这是否适用于虚拟机规模集实例?Would this work for virtual machine scale set instances?

    • 是的,IMDS 适用于虚拟机规模集实例。Yes, IMDS is available for virtual machine scale set instances.
  • 我在虚拟机规模集中更新了我的标记,但与单实例 VM 不同,这些标记未出现在实例中。I updated my tags in virtual machine scale sets, but they don't appear in the instances (unlike single instance VMs). 我哪里出错了吗?Am I doing something wrong?

    • 目前,虚拟机规模集的标记仅在重启、重置映像或更改实例的磁盘时向 VM 显示。Currently tags for virtual machine scale sets only show to the VM on a reboot, reimage, or disk change to the instance.
  • 为什么在 instance/compute 详细信息中看不到 VM 的 SKU 信息?Why am I am not seeing the SKU information for my VM in instance/compute details?

    • 对于通过 Azure 市场创建的自定义映像,Azure 平台不会保留自定义映像的 SKU 信息以及从自定义映像创建的任何 VM 的详细信息。For custom images created from Azure Marketplace, Azure platform doesn't retain the SKU information for the custom image and the details for any VMs created from the custom image. 这是由设计决定的,因此所述信息不会出现在 VM 的 instance/compute 详细信息中。This is by design and hence not surfaced in the VM instance/compute details.
  • 为什么调用服务时请求超时?Why is my request timed out for my call to the service?

    • 必须从分配给 VM 的主要网卡的主 IP 地址进行元数据调用。Metadata calls must be made from the primary IP address assigned to the primary network card of the VM. 此外,如果你更改了路由,则 VM 的本地路由表中必须存在 169.254.169.254/32 地址的路由。Additionally, if you've changed your routes, there must be a route for the 169.254.169.254/32 address in your VM's local routing table.
    1. 转储本地路由表并查找 IMDS 条目。Dump your local routing table and look for the IMDS entry. 例如:For example:
      > route print
      IPv4 Route Table
      ===========================================================================
      Active Routes:
      Network Destination        Netmask          Gateway       Interface  Metric
              0.0.0.0          0.0.0.0      172.16.69.1      172.16.69.7     10
              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
          168.63.129.16  255.255.255.255      172.16.69.1      172.16.69.7     11
      169.254.169.254  255.255.255.255      172.16.69.1      172.16.69.7     11
      ... (continues) ...
      
    2. 验证是否存在 169.254.169.254 的路由,并记下相应的网络接口(例如 172.16.69.7)。Verify that a route exists for 169.254.169.254, and note the corresponding network interface (for example, 172.16.69.7).
    3. 转储接口配置并查找与路由表中引用的接口相对应的接口,注明 MAC(物理)地址。Dump the interface configuration and find the interface that corresponds to the one referenced in the routing table, noting the MAC (physical) address.
      > ipconfig /all
      ... (continues) ...
      Ethernet adapter Ethernet:
      
      Connection-specific DNS Suffix  . : xic3mnxjiefupcwr1mcs1rjiqa.cx.internal.chinacloudapp.cn
      Description . . . . . . . . . . . : Microsoft Hyper-V Network Adapter
      Physical Address. . . . . . . . . : 00-0D-3A-E5-1C-C0
      DHCP Enabled. . . . . . . . . . . : Yes
      Autoconfiguration Enabled . . . . : Yes
      Link-local IPv6 Address . . . . . : fe80::3166:ce5a:2bd5:a6d1%3(Preferred)
      IPv4 Address. . . . . . . . . . . : 172.16.69.7(Preferred)
      Subnet Mask . . . . . . . . . . . : 255.255.255.0
      ... (continues) ...
      
    4. 确认该接口对应于 VM 的主 NIC 和主 IP。Confirm that the interface corresponds to the VM's primary NIC and primary IP. 可以通过在 Azure 门户中查看网络配置,或通过 Azure CLI 查找它来找到主 NIC 和 IP。You can find the primary NIC and IP by looking at the network configuration in the Azure portal, or by looking it up with the Azure CLI. 请记下专用 IP(如果使用 CLI,还要记下 MAC 地址)。Note the private IPs (and the MAC address if you're using the CLI). 下面是一个 PowerShell CLI 示例:Here's a PowerShell CLI example:
      $ResourceGroup = '<Resource_Group>'
      $VmName = '<VM_Name>'
      $NicNames = az vm nic list --resource-group $ResourceGroup --vm-name $VmName | ConvertFrom-Json | Foreach-Object { $_.id.Split('/')[-1] }
      foreach($NicName in $NicNames)
      {
          $Nic = az vm nic show --resource-group $ResourceGroup --vm-name $VmName --nic $NicName | ConvertFrom-Json
          Write-Host $NicName, $Nic.primary, $Nic.macAddress
      }
      # Output: wintest767 True 00-0D-3A-E5-1C-C0
      
    5. 如果它们不匹配,请更新路由表,以使主 NIC 和 IP 成为目标。If they don't match, update the routing table so that the primary NIC and IP are targeted.
  • Windows Server 中的故障转移群集Failover clustering in Windows Server

    • 使用故障转移群集查询 IMDS 时,有时需要向路由表添加路由。When you're querying IMDS with failover clustering, it's sometimes necessary to add a route to the routing table. 下面介绍如何操作:Here's how:
    1. 使用管理员特权打开命令提示符。Open a 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
    

    备注

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

    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
    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
    

    运行以下命令并使用网络目标 (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
    

支持Support

如果在多次尝试后无法获取元数据响应,则可以在 Azure 门户中创建支持问题。If you aren't able to get a metadata response after multiple attempts, you can create a support issue in the Azure portal.

产品反馈Product feedback

你可以访问此处,在“虚拟机”>“实例元数据服务”下向我们的用户反馈渠道提供产品反馈和想法You can provide product feedback and ideas to our user feedback channel under Virtual Machines > Instance Metadata Service here

后续步骤Next steps