Utforska dina Azure-resurser med resursgrafer

Azure Resource Graph hjälper dig att utforska och upptäcka dina Azure-resurser snabbt och i stor skala. Det är utformat för snabba svar och är ett bra sätt att lära sig om din miljö och även om de egenskaper som finns på dina Azure-resurser.

Kommentar

Beroende på resource graph-tabellen matchar egenskaperna antingen höljet som visas i Azure-portalen eller sänks ned. Namnet på en resursgrupp när du resourceContainers frågar tabellen matchar till exempel portalen, men resourceGroup egenskapen för resurser från tabellen kommer att vara gemener resources . Detta kan orsaka oväntade resultat och kan redovisas i dina frågor med hjälp av skiftlägesokänsliga jämförelseoperatorer, till exempel =~ i stället för och konvertering av == egenskaper till gemener tolower() i kopplingar till funktionen.

Utforska virtuella datorer

En vanlig resurs i Azure är en virtuell dator. Som resurstyp har virtuella datorer många egenskaper som kan efterfrågas. Varje egenskap ger ett alternativ för att filtrera eller hitta exakt den resurs du letar efter.

Identifiering av virtuell dator

Låt oss börja med en enkel fråga för att hämta en enda virtuell dator från vår miljö och titta på de egenskaper som returneras.

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

Kommentar

Azure PowerShell-cmdleten Search-AzGraph returnerar en PSResourceGraphResponse som standard. För att utdata ska se likadana ut som vad som returneras av Azure CLI används cmdleten ConvertTo-Jsonegenskapen Data . Standardvärdet för Djup är 2. Om du anger 100 ska alla returnerade nivåer konverteras.

JSON-resultaten är strukturerade ungefär som i följande exempel:

[
  {
    "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"
  }
]

Egenskaperna ger oss ytterligare information om själva den virtuella datorresursen. Dessa egenskaper omfattar: operativsystem, diskar, taggar och resursgruppen och prenumerationen som den är medlem i.

Virtuella datorer efter plats

Med det vi har lärt oss om resursen för virtuella datorer ska vi använda platsegenskapen för att räkna alla virtuella datorer efter plats. För att uppdatera frågan tar vi bort gränsen och sammanfattar antalet platsvärden.

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-resultaten är strukturerade ungefär som i följande exempel:

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

Nu kan vi se hur många virtuella datorer vi har i varje Azure-region.

Virtuella datorer efter SKU

Om vi går tillbaka till de ursprungliga egenskaperna för den virtuella datorn ska vi försöka hitta alla virtuella datorer som har en SKU-storlek på Standard_B2s. Den returnerade JSON som returneras visar att den lagras i properties.hardwareprofile.vmsize. Vi uppdaterar frågan för att hitta alla virtuella datorer som matchar den här storleken och returnerar bara namnet på den virtuella datorn och regionen.

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

Virtuella datorer som är anslutna till premiumhanterade diskar

För att få information om premiumhanterade diskar som är anslutna till dessa Standard_B2s virtuella datorer expanderar vi frågan för att returnera resurs-ID för dessa hanterade diskar.

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

Resultatet är en lista över disk-ID:t.

Identifiering av hanterad disk

Med den första posten från föregående fråga utforskar vi de egenskaper som finns på den hanterade disken som var ansluten till den första virtuella datorn. Den uppdaterade frågan använder disk-ID:t och ändrar typen.

Exempel på utdata från föregående fråga, till exempel:

[
  {
    "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'

Hur visste vi att typen nu ska vara Microsoft.Compute/diskar innan du kör frågan? Om du tittar på det fullständiga ID:t ser du /providers/Microsoft.Compute/disks/ som en del av strängen. Det här strängfragmentet ger dig en ledtråd om vilken typ du ska söka efter. En alternativ metod är att ta bort gränsen efter typ och i stället bara söka efter ID-fältet. Eftersom ID:t är unikt returneras bara en post och typens egenskap på den innehåller den informationen.

Kommentar

För att det här exemplet ska fungera måste du ersätta ID-fältet med ett resultat från din egen miljö.

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-resultaten är strukturerade ungefär som i följande exempel:

[
  {
    "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"
  }
]

Utforska virtuella datorer för att hitta offentliga IP-adresser

Den här uppsättningen frågor hittar och lagrar först alla nätverksgränssnittsresurser (NIC) som är anslutna till virtuella datorer. Sedan använder frågorna listan över nätverkskort för att hitta varje IP-adressresurs som är en offentlig IP-adress och lagra dessa värden. Slutligen tillhandahåller frågorna en lista över de offentliga IP-adresserna.

# 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

Använd filen (Azure CLI) eller variabeln (Azure PowerShell) i nästa fråga för att hämta information om relaterade nätverksgränssnittsresurser där det finns en offentlig IP-adress som är kopplad till nätverkskortet.

# 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

Använd slutligen listan över offentliga IP-adressresurser som lagras i filen (Azure CLI) eller variabeln (Azure PowerShell) för att hämta den faktiska offentliga IP-adressen från det relaterade objektet och visning.

# 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

Information om hur du utför de här stegen i en enda fråga med operatorn joinfinns i Lista virtuella datorer med deras nätverksgränssnitt och offentliga IP-exempel .

Nästa steg