Resource Graph を使用してご利用の Azure リソースを探索する

Azure Resource Graph は、Azure リソースをすばやく大規模に探索して検出するのに役立ちます。 迅速に応答するよう設計されており、ご利用の環境のほか、Azure リソース上に存在するプロパティの詳細を確認する優れた手段となっています。

注意

Resource Graph テーブルに応じて、プロパティは Azure portal に表示されるように大文字と小文字が一致するか、小文字になります。 たとえば、resourceContainers テーブルをクエリするときのリソース グループの名前はポータルと一致しますが、resources テーブルのリソースの resourceGroup プロパティは小文字になります。 これは予期しない結果を引き起こす可能性があり、関数との結合tolower()でプロパティを小文字に変換する代わりに==、大文字と小文字を区別しない比較演算子=~を使用してクエリで考慮することができます。

仮想マシンの詳細を確認する

Azure の一般的なリソースは仮想マシンです。 リソースの一種である仮想マシンは、クエリの対象になる多数のプロパティを備えています。 各プロパティには、探しているリソースだけをフィルター処理して見つけるためのオプションがあります。

仮想マシンの確認

まずは、環境から 1 つの仮想マシンを取得し、返されるプロパティを確認する簡単なクエリを実行してみましょう。

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

Note

Azure PowerShell Search-AzGraph コマンドレットは、既定で PSResourceGraphResponse を返します。 Azure CLI から返される内容と同様の出力にするには、Data プロパティに対して ConvertTo-Json コマンドレットを使用します。 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/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"
  }
]

プロパティによって、仮想マシン リソース自体に関する追加情報が指定されます。 これらのプロパティには、オペレーティング システム、ディスク、タグ、およびリソース グループとそのメンバーであるサブスクリプションが含まれます。

場所別の仮想マシン

仮想マシンのリソースについて学習した内容を念頭に置き、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 仮想マシンに接続されているプレミアム マネージド ディスクの詳細情報を得るには、これらのマネージド ディスクのリソース 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 は一意なので、1 つのレコードだけが返され、含まれる type プロパティによってその詳細情報が提供されます。

Note

この例を動作させるには、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": "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 アドレスを確認する

この一連のクエリでは、最初に仮想マシンに接続されているすべてのネットワーク インターフェイス (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 演算子を使用して 1 つのクエリでこれらの手順を行う方法については、仮想マシン、ネットワーク インターフェイス、パブリック IP を一覧表示するサンプルを参照してください。

次のステップ