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

Azure 实例元数据服务 (IMDS) 提供有关当前正在运行的虚拟机实例的信息,可用于管理和配置虚拟机。The Azure Instance Metadata Service (IMDS) provides information about currently running virtual machine instances and can be used to manage and configure your virtual machines. 这些信息包括 SKU、存储、网络配置和即将发生的维护事件。This information includes the SKU, storage, network configurations, and upcoming maintenance events. 有关提供的数据的完整列表,请参阅元数据 APIFor a complete list of the data that is available, see metadata APIs. 实例元数据服务适用于运行虚拟机和虚拟机规模集实例。Instance Metadata Service is available for running virtual machine and virtual machine scale set instances. 所有 API 均支持使用 Azure 资源管理器创建/管理的 VM。All APIs support VMs created/managed using Azure Resource Manager. 只有证明和网络终结点才支持经典(非 ARM)VM,而证明终结点支持的范围有限。Only the Attested and Network endpoints support Classic (non-ARM) VMs, and Attested does so only to a limited extent.

Azure 的 IMDS 是一个 REST 终结点,位于已知不可路由的 IP 地址 (169.254.169.254),只能从 VM 中访问。Azure's IMDS is a REST Endpoint that is available at a well-known non-routable IP address (169.254.169.254), it can be accessed only 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.16It is best practice to have 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.

安全性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.

重要

实例元数据服务不是用于敏感数据的通道。Instance Metadata Service is not a channel for sensitive data. 该终结点面向 VM 上的所有进程开放。The end point is 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.

使用情况Usage

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

若要访问实例元数据服务,请从 Azure 资源管理器Azure 门户创建一个 VM,并按照以下示例操作。To access Instance Metadata Service, create a VM from Azure Resource Manager or the Azure portal, and follow the samples below. 有关如何查询 IMDS 的更多示例,请参阅 Azure 实例元数据示例More examples of how to query IMDS can be found at Azure Instance Metadata Samples.

下面是用于检索实例的所有元数据的示例代码。若要访问特定数据源,请参阅元数据 API 部分。Below is the sample code to retrieve all metadata for an instance, to access specific data source, see Metadata API section.

请求Request

curl -H Metadata:true --noproxy "*" "http://169.254.169.254/metadata/instance?api-version=2020-06-01"

响应Response

备注

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

{
    "compute": {
        "azEnvironment": "AzureChinaCloud",
        "isHostCompatibilityLayerVm": "true",
        "location": "chinanorth",
        "name": "examplevmname",
        "offer": "Windows",
        "osType": "linux",
        "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/8d10da13-8125-4ba9-a717-bf7490507b3d/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/virtualMachines/examplevmname",
        "securityProfile": {
            "secureBootEnabled": "true",
            "virtualTpmEnabled": "false"
        },
        "sku": "Windows-Server-2012-R2-Datacenter",
        "storageProfile": {
            "dataDisks": [{
                "caching": "None",
                "createOption": "Empty",
                "diskSizeGB": "1024",
                "image": {
                    "uri": ""
                },
                "lun": "0",
                "managedDisk": {
                    "id": "/subscriptions/8d10da13-8125-4ba9-a717-bf7490507b3d/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampledatadiskname",
                    "storageAccountType": "Standard_LRS"
                },
                "name": "exampledatadiskname",
                "vhd": {
                    "uri": ""
                },
                "writeAcceleratorEnabled": "false"
            }],
            "imageReference": {
                "id": "",
                "offer": "UbuntuServer",
                "publisher": "Canonical",
                "sku": "16.04.0-LTS",
                "version": "latest"
            },
            "osDisk": {
                "caching": "ReadWrite",
                "createOption": "FromImage",
                "diskSizeGB": "30",
                "diffDiskSettings": {
                    "option": "Local"
                },
                "encryptionSettings": {
                    "enabled": "false"
                },
                "image": {
                    "uri": ""
                },
                "managedDisk": {
                    "id": "/subscriptions/8d10da13-8125-4ba9-a717-bf7490507b3d/resourceGroups/macikgo-test-may-23/providers/Microsoft.Compute/disks/exampleosdiskname",
                    "storageAccountType": "Standard_LRS"
                },
                "name": "exampleosdiskname",
                "osType": "Linux",
                "vhd": {
                    "uri": ""
                },
                "writeAcceleratorEnabled": "false"
            }
        },
        "subscriptionId": "8d10da13-8125-4ba9-a717-bf7490507b3d",
        "tags": "baz:bash;foo:bar",
        "version": "15.05.22",
        "vmId": "02aab8a4-74ef-476e-8182-f6d2ba4166a6",
        "vmScaleSetName": "crpteste9vflji9",
        "vmSize": "Standard_A3",
        "zone": ""
    }
}

数据输出Data output

默认情况下,实例元数据服务会返回 JSON 格式的数据 (Content-Type: application/json)。By default, the Instance Metadata Service returns data in JSON format (Content-Type: application/json). 但是,某些 API 可以返回不同格式的数据(如果请求)。However, some APIs are able to 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
/attested/attested jsonjson none
/identity/identity jsonjson none
/instance/instance jsonjson texttext
/scheduledevents/scheduledevents jsonjson nonenone

若要访问非默认响应格式,请在请求中将所请求的格式指定为查询字符串参数。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 --noproxy "*" "http://169.254.169.254/metadata/instance?api-version=2017-08-01&format=text"

备注

对于 /metadata/instance 中的叶节点,format=json 不起作用。For leaf nodes in /metadata/instance the format=json doesn't work. 对于这些查询,需要显式指定 format=text,因为默认格式为 json。For these queries format=text needs to be explicitly specified since the default format is json.

版本控制Versioning

实例元数据服务进行了版本控制,因此,必须在 HTTP 请求中指定 API 版本。The Instance Metadata Service is versioned and specifying the API version in the HTTP request is mandatory.

支持的 API 版本有:The supported API versions are:

  • 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

请注意,新版本发布后,需要一段时间才能推广到所有区域。Note when new version is released, it will take a while to roll out to all regions.

在添加更新的版本时,早期版本仍可供访问以保持兼容性(如果脚本依赖于特定的数据格式)。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.

备注

此响应是 JSON 字符串。The response is a JSON string. 下例说明了未指定版本时出现的错误情况,为了便于阅读,响应显示非常清晰。The following example indicates the error condition when version is not specified, the response is pretty-printed for readability.

请求Request

curl -H Metadata:true --noproxy "*" "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"
    ]
}

元数据 APIMetadata APIs

元数据服务包含多个 API(表示不同数据源)。Metadata Service contains multiple APIs representing different data sources.

APIAPI 说明Description 引入的版本Version Introduced
/attested/attested 请参阅证明数据See Attested Data 2018-10-012018-10-01
/identity/identity 请参阅获取访问令牌See Acquire an access token 2018-02-012018-02-01
/instance/instance 请参阅实例 APISee Instance API 2017-04-022017-04-02
/scheduledevents/scheduledevents 请参阅计划事件See Scheduled Events 2017-08-012017-08-01

实例 APIInstance API

实例 API 公开 VM 实例的重要元数据,其中包括 VM、网络和存储。Instance API exposes the important metadata for the VM instances, including the VM, network, and storage. 可以通过实例/计算访问以下类别:The following categories can be accessed through instance/compute:

数据Data 说明Description 引入的版本Version Introduced
azEnvironmentazEnvironment VM 运行时所在的 Azure 环境Azure Environment where the VM is running in 2018-10-012018-10-01
customDatacustomData 此功能目前已禁用。This feature is currently disabled. 当该功能可用时,我们将更新此文档We will update this documentation when it becomes available 2019-02-012019-02-01
isHostCompatibilityLayerVmisHostCompatibilityLayerVm 标识 VM 是否在主机兼容性层上运行Identifies if the VM runs on the Host Compatibility Layer 2020-06-012020-06-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 映像的信息,仅适用于从 Azure 映像库部署的映像Offer information for the VM image and 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
placementGroupIdplacementGroupId 虚拟机规模集的放置组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
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
ResourceIdresourceId 资源的完全限定 IDThe fully qualified ID of the resource 2019-03-112019-03-11
skusku VM 映像的特定 SKUSpecific SKU for the VM image 2017-04-022017-04-02
securityProfile.secureBootEnabledsecurityProfile.secureBootEnabled 标识是否在 VM 上启用了 UEFI 安全启动Identifies if UEFI secure boot is enabled on the VM 2020-06-012020-06-01
securityProfile.virtualTpmEnabledsecurityProfile.virtualTpmEnabled 标识是否在 VM 上启用了虚拟受信任的平台模块 (TPM)Identifies if the virtual Trusted Platform Module (TPM) is enabled on the VM 2020-06-012020-06-01
storageProfilestorageProfile 参阅存储配置文件See Storage Profile 2019-06-012019-06-01
subscriptionIdsubscriptionId 虚拟机的 Azure 订阅Azure subscription for the Virtual Machine 2017-08-012017-08-01
标记tags 虚拟机的标记Tags for your Virtual Machine 2017-08-012017-08-01
tagsListtagsList 格式化为 JSON 数组以方便编程分析的标记Tags formatted as a JSON array for easier programmatic parsing 2019-06-042019-06-04
版本version 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 scale set Name of your virtual machine scale set 2017-12-012017-12-01
vmSizevmSize VM 大小VM size 2017-04-022017-04-02

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

curl -H Metadata:true --noproxy "*" "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 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 --noproxy "*" "http://169.254.169.254/metadata/instance/compute/platformFaultDomain?api-version=2017-08-01&format=text"

响应Response

0

示例 3:在支持案例期间获取有关 VM 的详细信息Sample 3: 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 --noproxy "*" "http://169.254.169.254/metadata/instance/compute?api-version=2019-06-01"

响应Response

备注

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

{
    "azEnvironment": "AzureChinaCloud",
    "customData": "",
    "location": "chinaeast",
    "name": "negasonic",
    "offer": "lampstack",
    "osType": "Linux",
    "placementGroupId": "",
    "plan": {
        "name": "5-6",
        "product": "lampstack",
        "publisher": "bitnami"
    },
    "platformFaultDomain": "0",
    "platformUpdateDomain": "0",
    "provider": "Microsoft.Compute",
    "publicKeys": [],
    "publisher": "bitnami",
    "resourceGroupName": "myrg",
    "resourceId": "/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx/resourceGroups/myrg/providers/Microsoft.Compute/virtualMachines/negasonic",
    "sku": "5-6",
    "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": "UbuntuServer",
          "publisher": "Canonical",
          "sku": "16.04.0-LTS",
          "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": "Linux",
          "vhd": {
            "uri": ""
          },
          "writeAcceleratorEnabled": "false"
        }
    },
    "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
    "tags": "Department:IT;Environment:Test;Role:WebRole",
    "version": "7.1.1902271506",
    "vmId": "13f56399-bd52-4150-9748-7190aae1ff21",
    "vmScaleSetName": "",
    "vmSize": "Standard_A1_v2",
    "zone": ""
}

示例 4:获取 VM 所在的 Azure 环境Sample 4: 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 --noproxy "*" "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 below.

Cloud Azure 环境Azure Environment
全球所有公开上市的 Azure 区域All Generally Available Global Azure Regions AzurePublicCloudAzurePublicCloud
Azure 美国政府版Azure US Government AzureUSGovernmentCloudAzureUSGovernmentCloud
Azure 中国世纪互联Azure China 21Vianet AzureChinaCloudAzureChinaCloud
Azure 德国Azure Germany AzureGermanCloudAzureGermanCloud

网络元数据Network Metadata

网络元数据是实例 API 的一部分。Network metadata is part of the instance API. 可通过实例/网络终结点获取以下网络类别。The following Network categories are available through the instance/network endpoint.

数据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
ipv6/ipAddressipv6/ipAddress VM 的本地 IPv6 地址Local IPv6 address of the VM 2017-04-022017-04-02
macAddressmacAddress VM mac 地址VM mac address 2017-04-022017-04-02

备注

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

示例 1:检索网络信息Sample 1: Retrieving network information

请求Request

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

响应Response

备注

此响应是 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"
    }
  ]
}

示例 2:检索公共 IP 地址Sample 2: Retrieving public IP address

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

存储元数据Storage Metadata

存储元数据是实例/计算/storageProfile 终结点下实例 API 的一部分。Storage metadata is part of the instance API under instance/compute/storageProfile endpoint. 它提供与 VM 关联的存储磁盘的详细信息。It provides details about the storage disks associated with the VM.

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
idid 资源 IDResource ID
offeroffer 平台或市场映像的套餐Offer of the platform or marketplace image
publisherpublisher 映像发布者Image publisher
skusku 映像 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
cachingcaching 缓存要求Caching requirements
createOptioncreateOption 有关 VM 创建方式的信息Information about how the VM was created
diffDiskSettingsdiffDiskSettings 临时磁盘设置Ephemeral disk settings
diskSizeGBdiskSizeGB 磁盘大小 (GB)Size of the disk in GB
图像image 源用户映像虚拟硬盘Source user image virtual hard disk
lunlun 磁盘的逻辑单元号Logical unit number of the disk
managedDiskmanagedDisk 托管磁盘参数Managed disk parameters
namename 磁盘名称Disk name
vhdvhd 虚拟硬盘Virtual hard disk
writeAcceleratorEnabledwriteAcceleratorEnabled 磁盘上是否启用了 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
cachingcaching 缓存要求Caching requirements
createOptioncreateOption 有关 VM 创建方式的信息Information about how the VM was created
diffDiskSettingsdiffDiskSettings 临时磁盘设置Ephemeral disk settings
diskSizeGBdiskSizeGB 磁盘大小 (GB)Size of the disk in GB
encryptionSettingsencryptionSettings 磁盘的加密设置Encryption settings for the disk
imageimage 源用户映像虚拟硬盘Source user image virtual hard disk
managedDiskmanagedDisk 托管磁盘参数Managed disk parameters
namename 磁盘名称Disk name
osTypeosType 磁盘中包含的 OS 类型Type of OS included in the disk
vhdvhd 虚拟硬盘Virtual hard disk
writeAcceleratorEnabledwriteAcceleratorEnabled 磁盘上是否启用了 writeAcceleratorWhether or not writeAccelerator is enabled on the disk

以下示例演示如何查询 VM 的存储信息。The following example shows how to query the VM's storage information.

请求Request

curl -H Metadata:true --noproxy "*" "http://169.254.169.254/metadata/instance/compute/storageProfile?api-version=2019-06-01"

响应Response

备注

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

{
    "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": "UbuntuServer",
      "publisher": "Canonical",
      "sku": "16.04.0-LTS",
      "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": "Linux",
      "vhd": {
        "uri": ""
      },
      "writeAcceleratorEnabled": "false"
    }
}

VM 标记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

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

响应Response

Department:IT;Environment:Test;Role:WebRole

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.

请求Request

curl -H Metadata:true --noproxy "*" "http://169.254.169.254/metadata/instance/compute/tagsList?api-version=2019-06-04"

响应Response

[
  {
    "name": "Department",
    "value": "IT"
  },
  {
    "name": "Environment",
    "value": "Test"
  },
  {
    "name": "Role",
    "value": "WebRole"
  }
]

证明数据Attested Data

实例元数据服务提供的部分方案是为了保证提供的数据来自 Azure。Part of the scenario served by Instance Metadata Service is to provide guarantees that the data provided 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.

示例 1:获取证明数据Sample 1: Getting attested Data

备注

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

请求Request

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

Api-version 是必填字段。Api-version is a mandatory field. 有关支持的 API 版本的信息,请参阅使用部分Refer to the usage section for supported API versions. Nonce 是一个可选的 10 位字符串。Nonce is an optional 10-digit string. 如果未提供,IMDS 将在其所在位置返回当前 UTC 时间戳。If not provided, IMDS returns the current UTC timestamp in its place.

备注

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

响应Response

备注

此响应是 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 的详细信息。 对于 ARM VM,这包括 vmId、sku、nonce、subscriptionId、文档创建和到期的时间戳以及关于映像的计划信息。 该计划信息只针对 Azure 市场映像进行填充。 对于经典(非 ARM)VM,只保证填充 vmId。 证书可从响应中提取,用于验证响应是否有效、是否来自 Azure。The certificate can be extracted from the response and used to validate that the response is valid and is coming from Azure. 该文档包含以下字段:The document contains the following fields:

数据Data 说明Description
noncenonce 可以随请求提供的可选字符串。A string that can be optionally provided with the request. 如果未提供 nonce,则会使用当前 UTC 时间戳If no nonce was supplied, the current UTC timestamp is used
planplan Azure 市场映像计划The Azure Marketplace Image plan. 包含计划 ID(名称)、产品映像或产品/服务(产品)和发布者 ID(发布者)。Contains the plan id (name), product image or offer (product), and publisher id (publisher).
timestamp/createdOntimestamp/createdOn 创建签名文档时的 UTC 时间戳The UTC timestamp for when the signed document was created
timestamp/expiresOntimestamp/expiresOn 签名文档到期时的 UTC 时间戳The UTC timestamp for when the signed document expires
vmIdvmId VM 的唯一标识符Unique identifier for the VM
subscriptionIdsubscriptionId 虚拟机的 Azure 订阅,引入自 2019-04-30Azure subscription for the Virtual Machine, introduced in 2019-04-30
skusku 2019-11-01 中介绍了 VM 映像的特定 SKUSpecific SKU for the VM image, introduced in 2019-11-01

备注

对于经典(非 ARM)VM,只保证填充 vmId。For Classic (non-ARM) VMs, only the vmId is guaranteed to be populated.

示例 2:验证 VM 是否在 Azure 中运行Sample 2: 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.

备注

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

请求Request

# Get the signature
curl --silent -H Metadata:True --noproxy "*" "http://169.254.169.254/metadata/attested/document?api-version=2019-04-30" | 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
curl -s -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",
  "subscriptionId": "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
  "sku": "RS3-Pro"
}

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

# 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, for Azure China 21Vianet the intermediate certificate will be from DigiCert Global Root CA
openssl verify -verbose -CAfile /etc/ssl/certs/Baltimore_CyberTrust_Root.pem -untrusted intermediate.pem signer.pem

备注

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

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

备注

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

Cloud 证书Certificate
全球所有公开上市的 Azure 区域All Generally Available Global Azure Regions *.metadata.azure.com*.metadata.azure.com
Azure 美国政府版Azure US Government *.metadata.azure.us*.metadata.azure.us
Azure 中国世纪互联Azure China 21Vianet *.metadata.azure.cn*.metadata.azure.cn
Azure 德国Azure Germany *.metadata.microsoftazure.de*.metadata.microsoftazure.de

备注

用于签名的证书有一个已知问题。There is a known issue around the certificate used for signing. 对于公有云,证书可能不完全匹配 metadata.azure.comThe certificates may not have an exact match of metadata.azure.com for public cloud. 因此,证书验证应允许任何 .metadata.azure.com 子域中的公用名称。Hence the certification validation should allow a common name from any .metadata.azure.com subdomain.

在验证期间,如果网络限制导致无法下载中间证书,则可以固定中间证书。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 rollover 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.

备注

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

通过元数据服务使用托管标识Managed Identity via Metadata Service

可以在 VM 上启用系统分配的托管标识,也可以向 VM 分配一个或多个用户分配的托管标识。A system assigned managed identity can be enabled on the VM or one or more user assigned managed identities can be assigned to the VM. 然后,可以从实例元数据服务请求托管标识的令牌。Tokens for managed identities can then be requested from Instance Metadata Service. 这些令牌可用于通过其他 Azure 服务(如 Azure Key Vault)进行身份验证。These tokens can be used to authenticate with other Azure services such as Azure Key Vault.

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

通过元数据服务使用计划事件Scheduled Events via Metadata Service

可以通过元数据服务获取计划事件的状态,然后用户可以指定要对这些事件执行的一组操作。You can obtain the status of the scheduled events via metadata service, then user can specify a set of action to execute upon these events. 有关详细信息,请参阅计划事件See Scheduled Events for details.

区域可用性Regional Availability

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

不同语言的示例代码Sample Code in Different Languages

在 VM 内使用不同语言调用元数据服务的示例:Samples of calling metadata service 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

错误和调试Error 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 正常200 OK
400 错误的请求400 Bad Request 查询叶节点时缺少 Metadata: true 标头或缺少参数 format=jsonMissing Metadata: true header or missing parameter format=json when querying a leaf node
404 未找到404 Not Found 请求的元素不存在The requested element doesn't exist
不允许 405 方法405 Method Not Allowed 仅支持 GET 请求Only GET requests are supported
410 不存在410 Gone 在一段时间后重试最长 70 秒Retry after some time for a max of 70 seconds
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

已知问题和常见问题解答Known issues and 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),请在 VM 实例中添加/删除扩展或数据磁盘以刷新元数据。For older VMs (created before Sep 2016), add/remove extensions or data disks to the VM instance(s) 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),请在 VM 实例中添加/删除扩展或数据磁盘以刷新元数据。For older VMs (created before Sep 2016), add/remove extensions or data disks to the VM instance(s) to refresh metadata.
  5. 我为什么会收到错误 500 Internal Server Error410 Resource GoneWhy am I getting the error 500 Internal Server Error or 410 Resource Gone?
    • 基于指数回退系统或暂时性故障处理中所述的其他方法重试请求。Retry your request based on exponential back off system or other methods described in Transient fault handling. 如果问题仍然存在,请在 Azure 门户中为 VM 创建支持问题。If the issue persists create a support issue in Azure portal for the VM.
  6. 这是否适用于虚拟机规模集实例?Would this work for Virtual Machine Scale Set instances?
    • 是的,元数据服务可用于规模集实例。Yes Metadata service is available for Scale Set instances.
  7. 我在虚拟机规模集中更新了我的标记,但与单实例 VM 不同,这些标记未出现在实例中,这是怎么回事?I updated my tags in Virtual Machine Scale Sets but they don't appear in the instances unlike single instance VMs?
    • 目前,规模集的标记仅在重启、重置映像或更改实例的磁盘时向 VM 显示。Currently tags for Scale Sets only show to the VM on a reboot, reimage, or disk change to the instance.
  8. 调用服务时请求超时?I get 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 in the case you have changed your routes, there must be a route for the 169.254.169.254/32 address in your VM's local routing table.

    • 验证路由表Verifying your routing table
      1. 使用诸如 netstat -r 等命令转储本地路由表,并查找 IMDS 条目(例如):Dump your local routing table with a command such as netstat -r and look for the IMDS entry (e.g.):
        ~$ netstat -r
        Kernel IP routing table
        Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
        default         _gateway        0.0.0.0         UG        0 0          0 eth0
        168.63.129.16   _gateway        255.255.255.255 UGH       0 0          0 eth0
        169.254.169.254 _gateway        255.255.255.255 UGH       0 0          0 eth0
        172.16.69.0     0.0.0.0         255.255.255.0   U         0 0          0 eth0
        
      2. 验证是否存在 169.254.169.254 的路由,并记下相应的网络接口(例如 eth0)。Verify that a route exists for 169.254.169.254, and note the corresponding network interface (e.g. eth0).
      3. 转储路由表中相应接口的接口配置(请注意,配置文件的确切名称可能有所不同)Dump the interface configuration for the corresponding interface in the routing table (note the exact name of the configuration file may vary)
        ~$ cat /etc/netplan/50-cloud-init.yaml
        network:
        ethernets:
            eth0:
                dhcp4: true
                dhcp4-overrides:
                    route-metric: 100
                dhcp6: false
                match:
                    macaddress: 00:0d:3a:e4:c7:2e
                set-name: eth0
        version: 2
        
      4. 如果使用的是动态 IP,请记下 MAC 地址。If you are using a dynamic IP, note the MAC address. 如果使用的是静态 IP,可以记下列出的 IP 和/或 MAC 地址。If you are using a static IP, you may note the listed IP(s) and/or the MAC address.
      5. 确认该接口对应于 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/IP by looking at the network configuration in Azure Portal or by looking it up with the Azure CLI. 记下公共和专用 IP(如果使用 cli,还要记下 MAC 地址)。Note the public and private IPs (and the MAC address if using the cli). PowerShell CLI 示例: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: ipexample606 True 00-0D-3A-E4-C7-2E
        
      6. 如果它们不匹配,请更新路由表,以使主 NIC/IP 成为目标。If they do not match, update the routing table such that the primary NIC/IP are targeted.

后续步骤Next Steps

了解有关以下方面的详细信息:Learn more about:

  1. 获取 VM 的访问令牌Acquire an access token for the VM.
  2. 计划事件Scheduled Events