您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

使用 Resource Graph 浏览 Azure 资源Explore your Azure resources with Resource Graph

Azure Resource Graph 提供快速、大规模浏览和发现 Azure 资源的功能。Azure Resource Graph provides the ability to explore and discover your Azure resources quickly and at scale. 它专为快速响应而设计,是了解你的环境以及构成 Azure 资源的属性的好方法。Engineered for fast responses, it's a great way to learn about your environment and also about the properties that make up your Azure resources.

浏览虚拟机Explore virtual machines

Azure 中的一种常见资源是虚拟机。A common resource in Azure is a virtual machine. 作为资源类型,虚拟机具有许多可以查询的属性。As a resource type, virtual machines have many properties that can be queried. 每个属性都提供了一个筛选或查找你正在寻找的资源的选项。Each property provides an option for filtering or finding exactly the resource you're looking for.

虚拟机发现Virtual machine discovery

让我们从一个简单的查询开始,从环境中获取一个 VM 并查看返回的属性。Let's start with a simple query to get a single VM from our environment and look at the properties returned.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| limit 1
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | limit 1"
Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | limit 1" | ConvertTo-Json -Depth 100

备注

Azure PowerShell Search-AzGraph cmdlet 默认情况下会返回 PSCustomObject。The Azure PowerShell Search-AzGraph cmdlet returns a PSCustomObject by default. 若要让输出与 Azure CLI 返回的内容相同,请使用 ConvertTo-Json cmdlet。To have the output look the same as what is returned by Azure CLI, the ConvertTo-Json cmdlet is used. “深度”的默认值是“2”。The default value for Depth is 2. 将它设置为“100”应转换所有返回的级别。Setting it to 100 should convert all returned levels.

JSON 结果的结构类似于下面的示例:The JSON results are structured similar to the following example:

[
  {
    "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/ContosoVM1",
    "kind": "",
    "location": "westus2",
    "managedBy": "",
    "name": "ContosoVM1",
    "plan": {},
    "properties": {
      "hardwareProfile": {
        "vmSize": "Standard_B2s"
      },
      "networkProfile": {
        "networkInterfaces": [
          {
            "id": "/subscriptions/<subscriptionId>/MyResourceGroup/providers/Microsoft.Network/networkInterfaces/contosovm1535",
            "resourceGroup": "MyResourceGroup"
          }
        ]
      },
      "osProfile": {
        "adminUsername": "localAdmin",
        "computerName": "ContosoVM1",
        "secrets": [],
        "windowsConfiguration": {
          "enableAutomaticUpdates": true,
          "provisionVMAgent": true
        }
      },
      "provisioningState": "Succeeded",
      "storageProfile": {
        "dataDisks": [],
        "imageReference": {
          "offer": "WindowsServer",
          "publisher": "MicrosoftWindowsServer",
          "sku": "2016-Datacenter",
          "version": "latest"
        },
        "osDisk": {
          "caching": "ReadWrite",
          "createOption": "FromImage",
          "diskSizeGB": 127,
          "managedDisk": {
            "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
            "resourceGroup": "MyResourceGroup",
            "storageAccountType": "Premium_LRS"
          },
          "name": "ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
          "osType": "Windows"
        }
      },
      "vmId": "bbb9b451-6dc7-4117-bec5-c971eb1118c6"
    },
    "resourceGroup": "MyResourceGroup",
    "sku": {},
    "subscriptionId": "<subscriptionId>",
    "tags": {},
    "type": "microsoft.compute/virtualmachines"
  }
]

属性告诉我们有关虚拟机资源本身的其他信息,这些信息来自 SKU、OS、磁盘、标记以及其所属的资源组和订阅。The properties tell us additional information about the virtual machine resource itself, everything from SKU, OS, disks, tags, and the resource group and subscription it's a member of.

按位置列出的虚拟机Virtual machines by location

根据我们对虚拟机资源的了解,我们使用“位置”属性按位置计算所有虚拟机。Taking what we learned about the virtual machines resource, let's use the location property to count all virtual machines by location. 要更新查询,我们将删除限制并汇总位置值的计数。To update the query, we'll remove the limit and summarize the count of location values.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| summarize count() by location
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | summarize count() by location"
Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | summarize count() by location"

JSON 结果的结构类似于下面的示例:The JSON results are structured similar to the following example:

[
  {
    "count_": 386,
    "location": "eastus"
  },
  {
    "count_": 215,
    "location": "southcentralus"
  },
  {
    "count_": 59,
    "location": "westus"
  }
]

现在可以看到每个 Azure 区域中有多少个虚拟机。We can now see how many virtual machines we have in each Azure region.

按 SKU 列出的虚拟机Virtual machines by SKU

回到原始虚拟机属性,尝试查找 SKU 大小为“Standard_B2s”的所有虚拟机。Going back to the original virtual machine properties, let's try to find all the virtual machines that have a SKU size of Standard_B2s. 查看返回的 JSON,我们看到它存储在 properties.hardwareprofile.vmsize中。Looking at the JSON returned, we see that it's stored in properties.hardwareprofile.vmsize. 我们将更新查询以查找与此大小匹配的所有 VM,并仅返回 VM 和区域的名称。We'll update the query to find all VMs that match this size and return just the name of the VM and region.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines' and properties.hardwareProfile.vmSize == 'Standard_B2s'
| project name, resourceGroup"
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | project name, resourceGroup"
Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | project name, resourceGroup"

连接到高级托管磁盘的虚拟机Virtual machines connected to premium-managed disks

如果要获取附加到这些 Standard_B2s 虚拟机的高级托管磁盘的详细信息,可以扩展查询以提供这些托管磁盘的资源 ID。If we wanted to get the details of premium-managed disks that are attached to these Standard_B2s virtual machines, we can expand the query to give us the resource ID of those managed disks.

Resources
| where type =~ 'Microsoft.Compute/virtualmachines' and properties.hardwareProfile.vmSize == 'Standard_B2s'
| extend disk = properties.storageProfile.osDisk.managedDisk
| where disk.storageAccountType == 'Premium_LRS'
| project disk.id

备注

获得 SKU 的另一种方法是使用 aliases 属性 Microsoft.Compute/virtualMachines/sku.name。Another way to get the SKU would have been by using the aliases property Microsoft.Compute/virtualMachines/sku.name. 请参阅显示别名显示不同的别名值示例。See the Show aliases and Show distinct alias values examples.

az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualmachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | extend disk = properties.storageProfile.osDisk.managedDisk | where disk.storageAccountType == 'Premium_LRS' | project disk.id"
Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualmachines' and properties.hardwareProfile.vmSize == 'Standard_B2s' | extend disk = properties.storageProfile.osDisk.managedDisk | where disk.storageAccountType == 'Premium_LRS' | project disk.id"

结果是磁盘 ID 列表。The result is a list of disk IDs.

托管磁盘发现Managed disk discovery

使用从上一个查询获取的第一条记录,我们将浏览已附加到第一个虚拟机的托管磁盘上存在的属性。With the first record from the previous query, we'll explore the properties that exist on the managed disk that was attached to the first virtual machine. 更新的查询使用磁盘 ID 并更改类型。The updated query uses the disk ID and changes the type.

上一个查询的示例输出如下:Example output from the previous query for example:

[
  {
    "disk_id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166"
  }
]
Resources
| where type =~ 'Microsoft.Compute/disks' and id == '/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166'

在运行查询之前,如何知道“类型”现在是 Microsoft.Compute/disks?Before running the query, how did we know the type should now be Microsoft.Compute/disks? 如果查看完整 ID,会看到作为字符串一部分的 /providers/Microsoft.Compute/disks/。If you look at the full ID, you'll see /providers/Microsoft.Compute/disks/ as part of the string. 此字符串片段为你提供了要搜索的类型的提示。This string fragment gives you a hint as to what type to search for. 另一种方法是按类型删除限制,而只搜索 ID 字段。An alternative method would be to remove the limit by type and instead only search by the ID field. 由于 ID 是唯一的,因此只返回一条记录,并且 ID 的 type 属性提供该详细信息。As the ID is unique, only one record would be returned and the type property on it provides that detail.

备注

要使此示例起作用,必须使用自己的环境中的结果替换 ID 字段。For this example to work, you must replace the ID field with a result from your own environment.

az graph query -q "Resources | where type =~ 'Microsoft.Compute/disks' and id == '/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166'"
Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/disks' and id == '/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166'"

JSON 结果的结构类似于下面的示例:The JSON results are structured similar to the following example:

[
  {
    "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
    "kind": "",
    "location": "westus2",
    "managedBy": "",
    "name": "ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
    "plan": {},
    "properties": {
      "creationData": {
        "createOption": "Empty"
      },
      "diskSizeGB": 127,
      "diskState": "ActiveSAS",
      "provisioningState": "Succeeded",
      "timeCreated": "2018-09-14T12:17:32.2570000Z"
    },
    "resourceGroup": "MyResourceGroup",
    "sku": {
      "name": "Premium_LRS",
      "tier": "Premium"
    },
    "subscriptionId": "<subscriptionId>",
    "tags": {
      "environment": "prod"
    },
    "type": "microsoft.compute/disks"
  }
]

浏览虚拟机以查找公共 IP 地址Explore virtual machines to find public IP addresses

这组查询首先查找并存储连接到虚拟机的所有网络接口(NIC)资源。This set of queries first finds and stores all the network interfaces (NIC) resources connected to virtual machines. 然后,查询使用 Nic 列表来查找作为公共 IP 地址的每个 IP 地址资源,并存储这些值。Then the queries use the list of NICs to find each IP address resource that is a public IP address and store those values. 最后,查询提供公共 IP 地址的列表。Finally, the queries provide a list of the public IP addresses.

# Use Resource Graph to get all NICs and store in the 'nics.txt' file
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | project nic = tostring(properties['networkProfile']['networkInterfaces'][0]['id']) | where isnotempty(nic) | distinct nic | limit 20" --output table | tail -n +3 > nics.txt

# Review the output of the query stored in 'nics.txt'
cat nics.txt
# Use Resource Graph to get all NICs and store in the $nics variable
$nics = Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | project nic = tostring(properties['networkProfile']['networkInterfaces'][0]['id']) | where isnotempty(nic) | distinct nic | limit 20"

# Review the output of the query stored in the variable
$nics.nic

使用下一个查询中的文件(Azure CLI)或变量(Azure PowerShell)获取相关的网络接口资源详细信息,其中存在连接到 NIC 的公共 IP 地址。Use the file (Azure CLI) or variable (Azure PowerShell) in the next query to get the related network interface resources details where there's a public IP address attached to the NIC.

# Use Resource Graph with the 'nics.txt' file to get all related public IP addresses and store in 'publicIp.txt' file
az graph query -q="Resources | where type =~ 'Microsoft.Network/networkInterfaces' | where id in ('$(awk -vORS="','" '{print $0}' nics.txt | sed 's/,$//')') | project publicIp = tostring(properties['ipConfigurations'][0]['properties']['publicIPAddress']['id']) | where isnotempty(publicIp) | distinct publicIp" --output table | tail -n +3 > ips.txt

# Review the output of the query stored in 'ips.txt'
cat ips.txt
# Use Resource Graph  with the $nics variable to get all related public IP addresses and store in $ips variable
$ips = Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Network/networkInterfaces' | where id in ('$($nics.nic -join "','")') | project publicIp = tostring(properties['ipConfigurations'][0]['properties']['publicIPAddress']['id']) | where isnotempty(publicIp) | distinct publicIp"

# Review the output of the query stored in the variable
$ips.publicIp

最后,使用存储在文件中的公共 IP 地址资源的列表(Azure CLI)或变量(Azure PowerShell)从相关对象获取实际的公共 IP 地址,并显示。Last, use the list of public IP address resources stored in the file (Azure CLI) or variable (Azure PowerShell) to get the actual public IP address from the related object and display.

# Use Resource Graph with the 'ips.txt' file to get the IP address of the public IP address resources
az graph query -q="Resources | where type =~ 'Microsoft.Network/publicIPAddresses' | where id in ('$(awk -vORS="','" '{print $0}' ips.txt | sed 's/,$//')') | project ip = tostring(properties['ipAddress']) | where isnotempty(ip) | distinct ip" --output table
# Use Resource Graph with the $ips variable to get the IP address of the public IP address resources
Search-AzGraph -Query "Resources | where type =~ 'Microsoft.Network/publicIPAddresses' | where id in ('$($ips.publicIp -join "','")') | project ip = tostring(properties['ipAddress']) | where isnotempty(ip) | distinct ip"

若要了解如何使用 join 运算符在单个查询中完成这些步骤,请参阅使用其网络接口和公共 IP 示例列出虚拟机列表To see how to accomplish these steps in a single query with the join operator, see the List virtual machines with their network interface and public IP sample.

后续步骤Next steps