分享方式:


使用 Resource Graph 探索您的 Azure 資源

Azure Resource Graph 可協助您快速且大規模地探索及尋找 Azure 資源。 專為快速回應而設計,很適合用來了解您的環境以及您 Azure 資源中的屬性。

注意

根據 Resource Graph 資料表,屬性會與 Azure 入口網站中顯示的大小寫相符,或採用小寫。 例如,查詢 resourceContainers 資料表時的資源群組名稱會與入口網站相符,但資料表 resources 中所含資源的 resourceGroup 屬性將是小寫。 這可能會導致非預期的結果,因應之道是在查詢中使用不區分大小寫的比較運算子 (例如 =~ 而非 ==),以及在與 tolower() 函式聯結時將屬性轉換成小寫。

探索虛擬機器

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 所傳回的內容相同,可於 Data 屬性使用 ConvertTo-Json Cmdlet。 Depth 的預設值為 [2]。 若將其設定為 100,則應該會轉換所有傳回的層級。

JSON 結果的結構類似於下列範例:

[
  {
    "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/contosovm2222",
            "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_11111111111111111111111111111111",
            "resourceGroup": "MyResourceGroup",
            "storageAccountType": "Premium_LRS"
          },
          "name": "ContosoVM1_OsDisk_1_11111111111111111111111111111111",
          "osType": "Windows"
        }
      },
      "vmId": "11111111-1111-1111-1111-111111111111"
    },
    "resourceGroup": "MyResourceGroup",
    "sku": {},
    "subscriptionId": "<subscriptionId>",
    "tags": {},
    "type": "microsoft.compute/virtualmachines"
  }
]

我們能透過這些屬性了解與虛擬機器資源本身相關的額外資訊。 這些屬性包括:作業系統、磁碟、標記,以及其所屬的資源群組和訂閱。

依位置劃分的虛擬機器

根據我們對虛擬機器資源的了解,讓我們使用 location 屬性依位置計算所有虛擬機器。 若要更新查詢,請移除限制並摘要說明位置值的計數。

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": "eastus"
  },
  {
    "count_": 215,
    "location": "southcentralus"
  },
  {
    "count_": 59,
    "location": "westus"
  }
]

我們現在可以看到每個 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 虛擬機器的進階受控磁碟之詳細資料,則展開查詢以傳回這些受控磁碟的資源識別碼。

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

結果是一份磁碟識別碼清單。

受控磁碟探索

藉由上一個查詢中的第一筆記錄,您可探索已連結至第一個虛擬機器的受控磁碟上存在的屬性。 更新的查詢使用磁碟識別碼並變更類型。

上一個查詢的範例輸出,例如:

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

在執行查詢之前,我們如何得知 type 現在應為 Microsoft.Compute/disks? 如果您查看完整識別碼,你會注意到 /providers/Microsoft.Compute/disks/ 是字串的一部分。 此字串片段會為您提供要搜尋之類型的提示。 替代方法是依類型移除限制,而只依 [識別碼] 欄位搜尋。 由於識別碼是唯一的,因此只會傳回一筆記錄,並且其上的 type 屬性會提供詳細資料。

注意

若要使此範例正常運作,必須使用您自己的環境中的結果取代 [識別碼] 欄位。

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

JSON 結果的結構類似於下列範例:

[
  {
    "id": "/subscriptions/<subscriptionId>/resourceGroups/MyResourceGroup/providers/Microsoft.Compute/disks/ContosoVM1_OsDisk_1_11111111111111111111111111111111",
    "kind": "",
    "location": "westus2",
    "managedBy": "",
    "name": "ContosoVM1_OsDisk_1_11111111111111111111111111111111",
    "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] 範例。

下一步