Avancerade Resource Graph-frågeexempel

Det första steget mot att förstå frågor med Azure Resource Graph är en grundläggande förståelse för frågespråket. Om du inte redan är bekant med Azure Data Explorer rekommenderar vi att du går igenom grunderna så att du förstår hur man skapar begäranden för de resurser som du letar efter.

Vi går igenom följande avancerade frågor:

Om du inte har någon Azure-prenumeration skapar du ett kostnadsfritt konto innan du börjar.

Språkstöd

Azure CLI (via ett tillägg) och Azure PowerShell (via en modul) har stöd för Azure Resource Graph. Kontrollera att din miljö är redo innan du kör någon av nedanstående frågor. Se Azure CLI och Azure PowerShell för anvisningar om hur du installerar och validerar din valda gränssnittsmiljö.

Visa resurstyper och API-versioner

Resource Graph använder främst den senaste versionen av en resursprovider-API som inte är förhandsversion till GET resursegenskaper under en uppdatering. I vissa fall har den API-version som används åsidosätts för att ge mer aktuella eller allmänt använda egenskaper i resultaten. Följande fråga beskriver DEN API-version som används för att samla in egenskaper för varje resurstyp:

Resources
| distinct type, apiVersion
| where isnotnull(apiVersion)
| order by type asc
az graph query -q "Resources | distinct type, apiVersion | where isnotnull(apiVersion) | order by type asc"

Hämta kapacitet och storlek för skaluppsättning för virtuell dator

Den här frågan söker efter resurser för VM-skalningsuppsättningsresurser och hämtar olika typer av information om t.ex. den virtuella datorns storlek och skalningsuppsättningens kapacitet. Den här frågan använder toint()-funktionen för att konvertera kapaciteten till ett tal, så att den kan sorteras. Slutligen ändras kolumnernas namn till anpassade namngivna egenskaper.

Resources
| where type=~ 'microsoft.compute/virtualmachinescalesets'
| where name contains 'contoso'
| project subscriptionId, name, location, resourceGroup, Capacity = toint(sku.capacity), Tier = sku.name
| order by Capacity desc
az graph query -q "Resources | where type=~ 'microsoft.compute/virtualmachinescalesets' | where name contains 'contoso' | project subscriptionId, name, location, resourceGroup, Capacity = toint(sku.capacity), Tier = sku.name | order by Capacity desc"

Ta bort kolumner från resultat

Följande fråga använder summarize för att räkna resurser efter prenumeration, join kombinera den med prenumerationsinformation från ResourceContainers-tabellen och sedan project-away ta bort några av kolumnerna.

Resources
| summarize resourceCount=count() by subscriptionId
| join (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId
| project-away subscriptionId, subscriptionId1
az graph query -q "Resources | summarize resourceCount=count() by subscriptionId | join (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId| project-away subscriptionId, subscriptionId1"

Lista alla taggnamn

Den här frågan börjar med taggen och skapar ett JSON-objekt med alla unika taggnamn och deras motsvarande typer.

Resources
| project tags
| summarize buildschema(tags)
az graph query -q "Resources | project tags | summarize buildschema(tags)"

Virtuella datorer matchade av regex

Den här frågan söker efter virtuella datorer som matchar ett reguljärt uttryck (även kallat regex). Med matches regex @ kan vi definiera regex så att det matchar, vilket är ^Contoso(.*)[0-9]+$. Den regex-definitionen förklaras så här:

  • ^ – Matchningen måste börja i början av strängen.
  • Contoso – Skiftlägeskänslig sträng.
  • (.*) - En underuttrycksmatchning:
    • . – Matchar varje enskilt tecken (förutom ny rad).
    • * – Matchar föregående element noll eller flera gånger.
  • [0-9] – Teckengruppsmatchning för siffrorna 0-9.
  • + – Matchar föregående element en eller flera gånger.
  • $ – Matchning av föregående element måste ske i slutet av strängen.

När matchningen efter namn är klar projicerar frågan namnet och sorterar efter namn, i stigande ordning.

Resources
| where type =~ 'microsoft.compute/virtualmachines' and name matches regex @'^Contoso(.*)[0-9]+$'
| project name
| order by name asc
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' and name matches regex @'^Contoso(.*)[0-9]+\$' | project name | order by name asc"

Lista Azure Cosmos DB med specifika skrivplatser

Följande frågegränser för Azure Cosmos DB-resurser används mv-expand för att expandera egenskapsväskan för properties.writeLocations, sedan projicera specifika fält och begränsa resultatet ytterligare till properties.writeLocations.locationName-värden som matchar antingen "USA, östra" eller "USA, västra".

Resources
| where type =~ 'microsoft.documentdb/databaseaccounts'
| project id, name, writeLocations = (properties.writeLocations)
| mv-expand writeLocations
| project id, name, writeLocation = tostring(writeLocations.locationName)
| where writeLocation in ('East US', 'West US')
| summarize by id, name
az graph query -q "Resources | where type =~ 'microsoft.documentdb/databaseaccounts' | project id, name, writeLocations = (properties.writeLocations) | mv-expand writeLocations | project id, name, writeLocation = tostring(writeLocations.locationName) | where writeLocation in ('East US', 'West US') | summarize by id, name"

Nyckelvalv med prenumerationsnamn

Följande fråga visar en komplex användning av join med sort som leftouter. Frågan begränsar den anslutna tabellen till prenumerationsresurser och med project för att endast inkludera det ursprungliga fältet subscriptionId och namnfältet som har bytt namn till Undernamn. Namnbytet på fältet undviker join att lägga till det som namn1 eftersom fältet redan finns i resurser. Den ursprungliga tabellen filtreras med where och följande project innehåller kolumner från båda tabellerna. Frågeresultatet är alla nyckelvalv som visar typ, namnet på nyckelvalvet och namnet på den prenumeration som det finns i.

Resources
| join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId
| where type == 'microsoft.keyvault/vaults'
| project type, name, SubName
az graph query -q "Resources | join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId | where type == 'microsoft.keyvault/vaults' | project type, name, SubName"

Visa en lista över SQL-databaser och deras elastiska pooler

Följande fråga använder leftouterjoin för att sammanföra SQL Database-resurser och deras relaterade elastiska pooler, om de har några.

Resources
| where type =~ 'microsoft.sql/servers/databases'
| project databaseId = id, databaseName = name, elasticPoolId = tolower(tostring(properties.elasticPoolId))
| join kind=leftouter (
    Resources
    | where type =~ 'microsoft.sql/servers/elasticpools'
    | project elasticPoolId = tolower(id), elasticPoolName = name, elasticPoolState = properties.state)
on elasticPoolId
| project-away elasticPoolId1
az graph query -q "Resources | where type =~ 'microsoft.sql/servers/databases' | project databaseId = id, databaseName = name, elasticPoolId = tolower(tostring(properties.elasticPoolId)) | join kind=leftouter ( Resources | where type =~ 'microsoft.sql/servers/elasticpools' | project elasticPoolId = tolower(id), elasticPoolName = name, elasticPoolState = properties.state) on elasticPoolId | project-away elasticPoolId1"

Lista virtuella datorer med deras nätverksgränssnitt och offentliga IP-adress

Den här frågan använder två vänsterkommandonjoin för att sammanföra virtuella datorer som skapats med Resource Manager-distributionsmodellen, deras relaterade nätverksgränssnitt och alla offentliga IP-adresser som är relaterade till dessa nätverksgränssnitt.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| extend nics=array_length(properties.networkProfile.networkInterfaces)
| mv-expand nic=properties.networkProfile.networkInterfaces
| where nics == 1 or nic.properties.primary =~ 'true' or isempty(nic)
| project vmId = id, vmName = name, vmSize=tostring(properties.hardwareProfile.vmSize), nicId = tostring(nic.id)
| join kind=leftouter (
    Resources
    | where type =~ 'microsoft.network/networkinterfaces'
    | extend ipConfigsCount=array_length(properties.ipConfigurations)
    | mv-expand ipconfig=properties.ipConfigurations
    | where ipConfigsCount == 1 or ipconfig.properties.primary =~ 'true'
    | project nicId = id, publicIpId = tostring(ipconfig.properties.publicIPAddress.id))
on nicId
| project-away nicId1
| summarize by vmId, vmName, vmSize, nicId, publicIpId
| join kind=leftouter (
    Resources
    | where type =~ 'microsoft.network/publicipaddresses'
    | project publicIpId = id, publicIpAddress = properties.ipAddress)
on publicIpId
| project-away publicIpId1
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | extend nics=array_length(properties.networkProfile.networkInterfaces) | mv-expand nic=properties.networkProfile.networkInterfaces | where nics == 1 or nic.properties.primary =~ 'true' or isempty(nic) | project vmId = id, vmName = name, vmSize=tostring(properties.hardwareProfile.vmSize), nicId = tostring(nic.id) | join kind=leftouter ( Resources | where type =~ 'microsoft.network/networkinterfaces' | extend ipConfigsCount=array_length(properties.ipConfigurations) | mv-expand ipconfig=properties.ipConfigurations | where ipConfigsCount == 1 or ipconfig.properties.primary =~ 'true' | project nicId = id, publicIpId = tostring(ipconfig.properties.publicIPAddress.id)) on nicId | project-away nicId1 | summarize by vmId, vmName, vmSize, nicId, publicIpId | join kind=leftouter ( Resources | where type =~ 'microsoft.network/publicipaddresses' | project publicIpId = id, publicIpAddress = properties.ipAddress) on publicIpId | project-away publicIpId1"

Visa en lista över alla tillägg som är installerade på en virtuell dator

Först använder extend den här frågan på resurstypen virtuella datorer för att hämta ID:t i versaler (toupper()) ID:t, hämta operativsystemets namn och typ och hämta storleken på den virtuella datorn. Att hämta resurs-ID:t i versaler är ett bra sätt att förbereda för att ansluta till en annan egenskap. Sedan använder join frågan med typ som leftouter för att hämta tillägg för virtuella datorer genom att matcha en versal i tilläggs-ID substring :t. Delen av ID:t före "/extensions/<ExtensionName>" är samma format som ID:t för virtuella datorer, så vi använder den här egenskapen för join. summarize används sedan med make_list på namnet på tillägget för den virtuella datorn för att kombinera namnet på varje tillägg där ID, OSName, OSType och VMSize är samma i en enda matrisegenskap. Slutligen har vi order by det gemena OSName med asc. Som standard order by är fallande.

Resources
| where type == 'microsoft.compute/virtualmachines'
| extend
    JoinID = toupper(id),
    OSName = tostring(properties.osProfile.computerName),
    OSType = tostring(properties.storageProfile.osDisk.osType),
    VMSize = tostring(properties.hardwareProfile.vmSize)
| join kind=leftouter(
    Resources
    | where type == 'microsoft.compute/virtualmachines/extensions'
    | extend
        VMId = toupper(substring(id, 0, indexof(id, '/extensions'))),
        ExtensionName = name
) on $left.JoinID == $right.VMId
| summarize Extensions = make_list(ExtensionName) by id, OSName, OSType, VMSize
| order by tolower(OSName) asc
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | extend JoinID = toupper(id), OSName = tostring(properties.osProfile.computerName), OSType = tostring(properties.storageProfile.osDisk.osType), VMSize = tostring(properties.hardwareProfile.vmSize) | join kind=leftouter( Resources | where type == 'microsoft.compute/virtualmachines/extensions' | extend VMId = toupper(substring(id, 0, indexof(id, '/extensions'))), ExtensionName = name ) on \$left.JoinID == \$right.VMId | summarize Extensions = make_list(ExtensionName) by id, OSName, OSType, VMSize | order by tolower(OSName) asc"

Hitta lagringskonton med en specifik tagg i resursgruppen

Följande fråga använder ett inrejoin för att ansluta lagringskonton med resursgrupper som har ett angivet skiftlägeskänsligt taggnamn och taggvärde.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
    ResourceContainers
    | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
    | where tags['Key1'] =~ 'Value1'
    | project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | where tags['Key1'] =~ 'Value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

Om du behöver leta efter ett skiftlägesokänsligt taggnamn och taggvärde använder du mv-expand med parametern bagexpansion . Den här frågan använder mer kvot än föregående fråga, så använd mv-expand endast om det behövs.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
    ResourceContainers
    | where type =~ 'microsoft.resources/subscriptions/resourcegroups'
    | mv-expand bagexpansion=array tags
    | where isnotempty(tags)
    | where tags[0] =~ 'key1' and tags[1] =~ 'value1'
    | project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | mv-expand bagexpansion=array tags | where isnotempty(tags) | where tags[0] =~ 'key1' and tags[1] =~ 'value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

Kombinera resultat från två frågor till ett enda resultat

Följande fråga används union för att hämta resultat från tabellen ResourceContainers och lägga till dem i resultat från tabellen Resurser .

ResourceContainers
| where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type  | limit 5
| union  (Resources | project name, type | limit 5)
az graph query -q "ResourceContainers | where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type  | limit 5 | union  (Resources | project name, type | limit 5)"

Hämta virtuella nätverk och undernät för nätverksgränssnitt

Använd ett reguljärt uttryck parse för att hämta det virtuella nätverket och undernätsnamnen från resurs-ID-egenskapen. Även om parse gör det möjligt att hämta data från ett komplext fält är det optimalt att komma åt egenskaper direkt om de finns i stället för att använda parse.

Resources
| where type =~ 'microsoft.network/networkinterfaces'
| project id, ipConfigurations = properties.ipConfigurations
| mvexpand ipConfigurations
| project id, subnetId = tostring(ipConfigurations.properties.subnet.id)
| parse kind=regex subnetId with '/virtualNetworks/' virtualNetwork '/subnets/' subnet
| project id, virtualNetwork, subnet
az graph query -q "Resources | where type =~ 'microsoft.network/networkinterfaces' | project id, ipConfigurations = properties.ipConfigurations | mvexpand ipConfigurations | project id, subnetId = tostring(ipConfigurations.properties.subnet.id) | parse kind=regex subnetId with '/virtualNetworks/' virtualNetwork '/subnets/' subnet | project id, virtualNetwork, subnet"

Sammanfatta den virtuella datorn efter den utökade egenskapen power states

Den här frågan använder utökade egenskaper på virtuella datorer för att sammanfatta efter energispartillstånd.

Resources
| where type == 'microsoft.compute/virtualmachines'
| summarize count() by tostring(properties.extended.instanceView.powerState.code)
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | summarize count() by tostring(properties.extended.instanceView.powerState.code)"

Nästa steg