使用 Resource Graph 浏览 Azure 资源

Azure Resource Graph 提供快速、大规模浏览和发现 Azure 资源的功能。 它专为快速响应而设计,是了解你的环境以及 Azure 资源中的属性的好方法。

浏览虚拟机

Azure 中的一种常见资源是虚拟机。 作为资源类型,虚拟机具有许多可以查询的属性。 每个属性都提供了一个筛选或查找你正在寻找的资源的选项。

虚拟机发现

让我们从一个简单的查询开始,从环境中获取一个虚拟机并查看返回的属性。

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").Data | ConvertTo-Json -Depth 100

备注

Azure PowerShell Search-AzGraph cmdlet 默认情况下会返回 PSResourceGraphResponse。 若要让输出与 Azure CLI 返回的内容相同,请在“数据”属性上使用 ConvertTo-Json cmdlet。 “深度” 的默认值是“2” 。 将它设置为“100” 应转换所有返回的级别。

JSON 结果的结构类似于下面的示例:

[
  {
    "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/virtualMachines/ContosoVM1",
    "kind": "",
    "location": "chinanorth2",
    "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"
  }
]

这些属性可告知有关虚拟机资源本身的其他信息。 这些属性包括:操作系统、磁盘、标签、资源组及其所属订阅。

按位置列出的虚拟机

根据我们对虚拟机资源的了解,我们使用“位置”属性按位置计算所有虚拟机。 要更新查询,我们将删除限制并汇总位置值的计数。

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").Data | ConvertTo-Json

JSON 结果的结构类似于下面的示例:

[
  {
    "count_": 386,
    "location": "chinaeast"
  },
  {
    "count_": 215,
    "location": "chinaeast2"
  },
  {
    "count_": 59,
    "location": "chinanorth"
  }
]

现在可以看到每个 Azure 区域中有多少个虚拟机。

按 SKU 列出的虚拟机

回到原始虚拟机属性,尝试查找 SKU 大小为“Standard_B2s”的所有虚拟机。 查看返回的 JSON,我们看到它存储在 properties.hardwareprofile.vmsize中。 我们将更新查询以查找与此大小匹配的所有 VM,并仅返回 VM 和区域的名称。

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").Data | ConvertTo-Json

连接到高级托管磁盘的虚拟机

如果要获取附加到这些 Standard_B2s 虚拟机的高级托管磁盘的详细信息,可以扩展查询以返回这些托管磁盘的资源 ID。

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
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").Data | ConvertTo-Json

结果是磁盘 ID 列表。

托管磁盘发现

使用从上一个查询获取的第一条记录,我们将浏览已附加到第一个虚拟机的托管磁盘上存在的属性。 更新的查询使用磁盘 ID 并更改类型。

上一个查询的示例输出如下:

[
  {
    "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? 如果查看完整 ID,会看到作为字符串一部分的 /providers/Microsoft.Compute/disks/。 此字符串片段为你提供了要搜索的类型的提示。 另一种方法是按类型删除限制,而只搜索 ID 字段。 由于 ID 是唯一的,因此只返回一条记录,并且 ID 的 type 属性提供该详细信息。

备注

要使此示例起作用,必须使用自己的环境中的结果替换 ID 字段。

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'").Data | ConvertTo-Json

JSON 结果的结构类似于下面的示例:

[
  {
    "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_9676b7e1b3c44e2cb672338ebe6f5166",
    "kind": "",
    "location": "chinanorth2",
    "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 地址

这一组查询首先查找并存储已连接到虚拟机的所有网络接口 (NIC) 资源。 然后,查询使用 NIC 列表查找是公共 IP 地址的每个 IP 地址资源并存储这些值。 最后,查询提供公共 IP 地址的列表。

# 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").Data

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

在下一个查询中使用文件 (Azure CLI) 或变量 (Azure PowerShell) 获取 NIC 附加了公共 IP 地址的相关网络接口资源详细信息。

# 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").Data

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

最后,使用存储在文件 (Azure CLI) 或变量 (Azure PowerShell) 中的公共 IP 地址资源列表从相关对象获取实际公共 IP 地址并显示。

# 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").Data | ConvertTo-Json

若要了解如何使用 join 运算符在单个查询中完成这些步骤,请参阅列出虚拟机及其网络接口和公共 IP 示例。

后续步骤