Query di esempio di Azure Resource Graph per categoria
Questa pagina è una raccolta di query di esempio di Azure Resource Graph raggruppate per categorie generali e di servizio. Per passare a una categoria specifica, usare il menu sul lato destro della pagina. Altrimenti, premere CTRL-F per usare la funzionalità di ricerca del browser.
Azure Advisor
Ottenere un riepilogo dei risparmi sui costi da Azure Advisor
Questa query riepiloga i risparmi sui costi di ogni raccomandazione di Azure Advisor.
AdvisorResources
| where type == 'microsoft.advisor/recommendations'
| where properties.category == 'Cost'
| extend
resources = tostring(properties.resourceMetadata.resourceId),
savings = todouble(properties.extendedProperties.savingsAmount),
solution = tostring(properties.shortDescription.solution),
currency = tostring(properties.extendedProperties.savingsCurrency)
| summarize
dcount(resources),
bin(sum(savings), 0.01)
by solution, currency
| project solution, dcount_resources, sum_savings, currency
| order by sum_savings desc
az graph query -q "AdvisorResources | where type == 'microsoft.advisor/recommendations' | where properties.category == 'Cost' | extend resources = tostring(properties.resourceMetadata.resourceId), savings = todouble(properties.extendedProperties.savingsAmount), solution = tostring(properties.shortDescription.solution), currency = tostring(properties.extendedProperties.savingsCurrency) | summarize dcount(resources), bin(sum(savings), 0.01) by solution, currency | project solution, dcount_resources, sum_savings, currency | order by sum_savings desc"
Azure Arc
Ottenere i tipi di risorse abilitati per i percorsi personalizzati abilitati per Azure Arc
Fornisce un elenco dei tipi di risorse abilitati per le posizioni personalizzate abilitate per Azure Arc.
ExtendedLocationResources
| where type == 'microsoft.extendedlocation/customlocations/enabledresourcetypes'
az graph query -q "ExtendedLocationResources | where type == 'microsoft.extendedlocation/customlocations/enabledresourcetypes'"
Elencare le posizioni personalizzate abilitate per Azure Arc con VMware o SCVMM abilitato
Fornisce un elenco di tutte le posizioni personalizzate abilitate per Azure Arc con tipi di risorse VMware o SCVMM abilitati.
Resources
| where type =~ 'microsoft.extendedlocation/customlocations' and properties.provisioningState =~ 'succeeded'
| extend clusterExtensionIds=properties.clusterExtensionIds
| mvexpand clusterExtensionIds
| extend clusterExtensionId = tolower(clusterExtensionIds)
| join kind=leftouter(
ExtendedLocationResources
| where type =~ 'microsoft.extendedlocation/customLocations/enabledResourcetypes'
| project clusterExtensionId = tolower(properties.clusterExtensionId), extensionType = tolower(properties.extensionType)
| where extensionType in~ ('microsoft.scvmm','microsoft.vmware')
) on clusterExtensionId
| where extensionType in~ ('microsoft.scvmm','microsoft.vmware')
| summarize virtualMachineKindsEnabled=make_set(extensionType) by id,name,location
| sort by name asc
az graph query -q "Resources | where type =~ 'microsoft.extendedlocation/customlocations' and properties.provisioningState =~ 'succeeded' | extend clusterExtensionIds=properties.clusterExtensionIds | mvexpand clusterExtensionIds | extend clusterExtensionId = tolower(clusterExtensionIds) | join kind=leftouter( ExtendedLocationResources | where type =~ 'microsoft.extendedlocation/customLocations/enabledResourcetypes' | project clusterExtensionId = tolower(properties.clusterExtensionId), extensionType = tolower(properties.extensionType) | where extensionType in~ ('microsoft.scvmm','microsoft.vmware') ) on clusterExtensionId | where extensionType in~ ('microsoft.scvmm','microsoft.vmware') | summarize virtualMachineKindsEnabled=make_set(extensionType) by id,name,location | sort by name asc"
Kubernetes con abilitazione di Azure Arc
Elencare tutti i cluster Kubernetes abilitati per Azure Arc con l'estensione Monitoraggio di Azure
Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc in cui è installata l'estensione Monitoraggio di Azure.
KubernetesConfigurationResources
| where type == 'microsoft.kubernetesconfiguration/extensions'
| where properties.ExtensionType == 'microsoft.azuremonitor.containers'
| parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' *
| project connectedClusterId
az graph query -q "KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' * | project connectedClusterId"
Elencare tutti i cluster Kubernetes abilitati per Azure Arc senza l'estensione Monitoraggio di Azure
Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc che manca l'estensione Monitoraggio di Azure.
Resources
| where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId
| join kind = leftouter
(KubernetesConfigurationResources
| where type == 'microsoft.kubernetesconfiguration/extensions'
| where properties.ExtensionType == 'microsoft.azuremonitor.containers'
| parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' *
| project connectedClusterId
) on connectedClusterId
| where connectedClusterId1 == ''
| project connectedClusterId
az graph query -q "Resources | where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId | join kind = leftouter (KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' * | project connectedClusterId ) on connectedClusterId | where connectedClusterId1 == '' | project connectedClusterId"
Elencare tutte le risorse Kubernetes abilitate per Azure Arc
Restituisce un elenco di ogni cluster Kubernetes abilitato per Azure Arc e dei metadati pertinenti per ogni cluster.
Resources
| project id, subscriptionId, location, type, properties.agentVersion, properties.kubernetesVersion, properties.distribution, properties.infrastructure, properties.totalNodeCount, properties.totalCoreCount
| where type =~ 'Microsoft.Kubernetes/connectedClusters'
az graph query -q "Resources | project id, subscriptionId, location, type, properties.agentVersion, properties.kubernetesVersion, properties.distribution, properties.infrastructure, properties.totalNodeCount, properties.totalCoreCount | where type =~ 'Microsoft.Kubernetes/connectedClusters'"
Elencare tutti i ConnectedClusters e ManagedCluster che contengono una configurazione Flux
Restituisce gli ID connectedCluster e managedCluster per i cluster che contengono almeno un fluxConfiguration.
resources
| where type =~ 'Microsoft.Kubernetes/connectedClusters' or type =~ 'Microsoft.ContainerService/managedClusters' | extend clusterId = tolower(id) | project clusterId
| join
( kubernetesconfigurationresources
| where type == 'microsoft.kubernetesconfiguration/fluxconfigurations'
| parse tolower(id) with clusterId '/providers/microsoft.kubernetesconfiguration/fluxconfigurations' *
| project clusterId
) on clusterId
| project clusterId
az graph query -q "resources | where type =~ 'Microsoft.Kubernetes/connectedClusters' or type =~ 'Microsoft.ContainerService/managedClusters' | extend clusterId = tolower(id) | project clusterId | join ( kubernetesconfigurationresources | where type == 'microsoft.kubernetesconfiguration/fluxconfigurations' | parse tolower(id) with clusterId '/providers/microsoft.kubernetesconfiguration/fluxconfigurations' * | project clusterId ) on clusterId | project clusterId"
Elencare tutte le configurazioni Flux che si trovano in uno stato non conforme
Restituisce gli ID fluxConfiguration delle configurazioni che non riescono a sincronizzare le risorse nel cluster.
kubernetesconfigurationresources
| where type == 'microsoft.kubernetesconfiguration/fluxconfigurations'
| where properties.complianceState == 'Non-Compliant'
| project id
az graph query -q "kubernetesconfigurationresources | where type == 'microsoft.kubernetesconfiguration/fluxconfigurations' | where properties.complianceState == 'Non-Compliant' | project id"
Server abilitati per Azure Arc
Ottenere il conteggio e la percentuale di server abilitati per Arc per dominio
Questa query riepiloga la proprietà domainName nei server abilitati per Azure Arc e usa un calcolo con bin
per creare una colonna Pct per la percentuale di server abilitati per Arc per dominio.
Resources
| where type == 'microsoft.hybridcompute/machines'
| project domain=tostring(properties.domainName)
| summarize Domains=make_list(domain), TotalMachineCount=sum(1)
| mvexpand EachDomain = Domains
| summarize PerDomainMachineCount = count() by tostring(EachDomain), TotalMachineCount
| extend Pct = 100 * bin(todouble(PerDomainMachineCount) / todouble(TotalMachineCount), 0.001)
az graph query -q "Resources | where type == 'microsoft.hybridcompute/machines' | project domain=tostring(properties.domainName) | summarize Domains=make_list(domain), TotalMachineCount=sum(1) | mvexpand EachDomain = Domains | summarize PerDomainMachineCount = count() by tostring(EachDomain), TotalMachineCount | extend Pct = 100 * bin(todouble(PerDomainMachineCount) / todouble(TotalMachineCount), 0.001)"
Elencare tutte le estensioni installate in un server abilitato per Azure Arc
In primo luogo, questa query usa project
nel tipo di risorsa del computer ibrido per ottenere l'ID in maiuscolo (toupper()
), ottenere il nome del computer e il sistema operativo in esecuzione nel computer. Ottenere l'ID risorsa in lettere maiuscole è un buon modo per prepararsi a join
un'altra proprietà. La query usa join
quindi con il tipoleftouter per ottenere le estensioni associando una maiuscola substring
dell'ID estensione. La parte dell'ID precedente /extensions/<ExtensionName>
è lo stesso formato dell'ID computer ibrido, quindi viene usata questa proprietà per .join
summarize
viene quindi usato con make_list
sul nome dell'estensione macchina virtuale per combinare il nome di ogni estensione in cui id, OSName e ComputerName sono uguali in una singola proprietà di matrice. Infine, ordiniamo in base a OSName minuscolo con asc. Per impostazione predefinita, order by
è decrescente.
Resources
| where type == 'microsoft.hybridcompute/machines'
| project
id,
JoinID = toupper(id),
ComputerName = tostring(properties.osProfile.computerName),
OSName = tostring(properties.osName)
| join kind=leftouter(
Resources
| where type == 'microsoft.hybridcompute/machines/extensions'
| project
MachineId = toupper(substring(id, 0, indexof(id, '/extensions'))),
ExtensionName = name
) on $left.JoinID == $right.MachineId
| summarize Extensions = make_list(ExtensionName) by id, ComputerName, OSName
| order by tolower(OSName) asc
az graph query -q "Resources | where type == 'microsoft.hybridcompute/machines' | project id, JoinID = toupper(id), ComputerName = tostring(properties.osProfile.computerName), OSName = tostring(properties.osName) | join kind=leftouter( Resources | where type == 'microsoft.hybridcompute/machines/extensions' | project MachineId = toupper(substring(id, 0, indexof(id, '/extensions'))), ExtensionName = name ) on \$left.JoinID == \$right.MachineId | summarize Extensions = make_list(ExtensionName) by id, ComputerName, OSName | order by tolower(OSName) asc"
Elencare i server abilitati per Arc che non eseguono la versione più recente dell'agente rilasciato
Questa query restituisce tutti i server abilitati per Arc che eseguono una versione obsoleta dell'agente di computer connesso. Gli agenti con stato Scaduto vengono esclusi dai risultati. La query usa leftouterjoin
per riunire le raccomandazioni di Advisor generate su qualsiasi agente di computer connesso identificato come non aggiornato e computer ibridi per filtrare qualsiasi agente che non ha comunicato con Azure in un periodo di tempo.
AdvisorResources
| where type == 'microsoft.advisor/recommendations'
| where properties.category == 'HighAvailability'
| where properties.shortDescription.solution == 'Upgrade to the latest version of the Azure Connected Machine agent'
| project
id,
JoinId = toupper(properties.resourceMetadata.resourceId),
machineName = tostring(properties.impactedValue),
agentVersion = tostring(properties.extendedProperties.installedVersion),
expectedVersion = tostring(properties.extendedProperties.latestVersion)
| join kind=leftouter(
Resources
| where type == 'microsoft.hybridcompute/machines'
| project
machineId = toupper(id),
status = tostring (properties.status)
) on $left.JoinId == $right.machineId
| where status != 'Expired'
| summarize by id, machineName, agentVersion, expectedVersion
| order by tolower(machineName) asc
az graph query -q "AdvisorResources | where type == 'microsoft.advisor/recommendations' | where properties.category == 'HighAvailability' | where properties.shortDescription.solution == 'Upgrade to the latest version of the Azure Connected Machine agent' | project id, JoinId = toupper(properties.resourceMetadata.resourceId), machineName = tostring(properties.impactedValue), agentVersion = tostring(properties.extendedProperties.installedVersion), expectedVersion = tostring(properties.extendedProperties.latestVersion) | join kind=leftouter( Resources | where type == 'microsoft.hybridcompute/machines' | project machineId = toupper(id), status = tostring (properties.status) ) on \$left.JoinId == \$right.machineId | where status != 'Expired' | summarize by id, machineName, agentVersion, expectedVersion | order by tolower(machineName) asc"
Registro Azure Container
Elencare i risultati della valutazione della vulnerabilità del Registro contenitori
Restituisce tutte le vulnerabilità trovate nelle immagini del contenitore. Microsoft Defender per i contenitori deve essere abilitato per visualizzare questi risultati di sicurezza.
SecurityResources
| where type == 'microsoft.security/assessments'
| where properties.displayName contains 'Container registry images should have vulnerability findings resolved'
| summarize by assessmentKey=name //the ID of the assessment
| join kind=inner (
securityresources
| where type == 'microsoft.security/assessments/subassessments'
| extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id)
) on assessmentKey
| project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId
| extend description = properties.description,
displayName = properties.displayName,
resourceId = properties.resourceDetails.id,
resourceSource = properties.resourceDetails.source,
category = properties.category,
severity = properties.status.severity,
code = properties.status.code,
timeGenerated = properties.timeGenerated,
remediation = properties.remediation,
impact = properties.impact,
vulnId = properties.id,
additionalData = properties.additionalData
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | where properties.displayName contains 'Container registry images should have vulnerability findings resolved' | summarize by assessmentKey=name //the ID of the assessment | join kind=inner ( securityresources | where type == 'microsoft.security/assessments/subassessments' | extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id) ) on assessmentKey | project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId | extend description = properties.description, displayName = properties.displayName, resourceId = properties.resourceDetails.id, resourceSource = properties.resourceDetails.source, category = properties.category, severity = properties.status.severity, code = properties.status.code, timeGenerated = properties.timeGenerated, remediation = properties.remediation, impact = properties.impact, vulnId = properties.id, additionalData = properties.additionalData"
Azure Cosmos DB
Elencare Azure Cosmos DB con percorsi di scrittura specifici
La query seguente limita le risorse di Azure Cosmos DB, usa mv-expand
per espandere il contenitore delle proprietà per proprietà.writeLocations, quindi proiettare campi specifici e limitare i risultati ulteriormente ai valori properties.writeLocations.locationName corrispondenti a "Stati Uniti orientali" o "Stati Uniti occidentali".
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"
Insieme di credenziali chiave di Azure
Contare le risorse dell'insieme di credenziali delle chiavi
Questa query usa count
invece di summarize
per contare il numero di record restituiti. Nel conteggio sono inclusi solo gli insiemi di credenziali delle chiavi.
Resources
| where type =~ 'microsoft.keyvault/vaults'
| count
az graph query -q "Resources | where type =~ 'microsoft.keyvault/vaults' | count"
Insieme di credenziali delle chiavi con il nome della sottoscrizione
La query seguente illustra un uso complesso di join
con kind come leftouter. La query limita la tabella aggiunta alle risorse della sottoscrizione e usa project
per includere solo il campo subscriptionId originale e il campo name rinominato in SubName. La ridenominazione del campo evita che join
lo aggiunga come name1, perché il campo esiste già in resources. La tabella originale viene filtrata con where
e l'elemento project
seguente include colonne di entrambe le tabelle. Il risultato della query è che tutti gli insiemi di credenziali delle chiavi visualizzano il tipo, il nome dell'insieme di credenziali delle chiavi e il nome della sottoscrizione in cui è incluso.
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"
Monitoraggio di Azure
Visualizzare gli avvisi recenti di Monitoraggio di Azure
Questa query di esempio ottiene tutti gli avvisi di Monitoraggio di Azure generati negli ultimi 12 ore ed estrae le proprietà comunemente usate.
alertsmanagementresources
| where properties.essentials.startDateTime > ago(12h)
| project
alertId = id,
name,
monitorCondition = tostring(properties.essentials.monitorCondition),
severity = tostring(properties.essentials.severity),
monitorService = tostring(properties.essentials.monitorService),
alertState = tostring(properties.essentials.alertState),
targetResourceType = tostring(properties.essentials.targetResourceType),
targetResource = tostring(properties.essentials.targetResource),
subscriptionId,
startDateTime = todatetime(properties.essentials.startDateTime),
lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime),
dimensions = properties.context.context.condition.allOf[0].dimensions, properties
az graph query -q "alertsmanagementresources | where properties.essentials.startDateTime > ago(12h) | project alertId = id, name, monitorCondition = tostring(properties.essentials.monitorCondition), severity = tostring(properties.essentials.severity), monitorService = tostring(properties.essentials.monitorService), alertState = tostring(properties.essentials.alertState), targetResourceType = tostring(properties.essentials.targetResourceType), targetResource = tostring(properties.essentials.targetResource), subscriptionId, startDateTime = todatetime(properties.essentials.startDateTime), lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime), dimensions = properties.context.context.condition.allOf[0].dimensions, properties"
Visualizzare gli avvisi recenti di Monitoraggio di Azure arricchiti con i tag di risorsa
Questa query di esempio ottiene tutti gli avvisi di Monitoraggio di Azure generati negli ultimi 12 ore, estrae le proprietà comunemente usate e aggiunge i tag della risorsa di destinazione.
alertsmanagementresources
| where properties.essentials.startDateTime > ago(12h)
| where tostring(properties.essentials.monitorService) <> "ActivityLog Administrative"
| project // converting extracted fields to string / datetime to allow grouping
alertId = id,
name,
monitorCondition = tostring(properties.essentials.monitorCondition),
severity = tostring(properties.essentials.severity),
monitorService = tostring(properties.essentials.monitorService),
alertState = tostring(properties.essentials.alertState),
targetResourceType = tostring(properties.essentials.targetResourceType),
targetResource = tostring(properties.essentials.targetResource),
subscriptionId,
startDateTime = todatetime(properties.essentials.startDateTime),
lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime),
dimensions = properties.context.context.condition.allOf[0].dimensions, // usefor metric alerts and log search alerts
properties
| extend targetResource = tolower(targetResource)
| join kind=leftouter
( resources | project targetResource = tolower(id), targetResourceTags = tags) on targetResource
| project-away targetResource1
az graph query -q "alertsmanagementresources | where properties.essentials.startDateTime > ago(12h) | where tostring(properties.essentials.monitorService) <> "ActivityLog Administrative" | project // converting extracted fields to string / datetime to allow grouping alertId = id, name, monitorCondition = tostring(properties.essentials.monitorCondition), severity = tostring(properties.essentials.severity), monitorService = tostring(properties.essentials.monitorService), alertState = tostring(properties.essentials.alertState), targetResourceType = tostring(properties.essentials.targetResourceType), targetResource = tostring(properties.essentials.targetResource), subscriptionId, startDateTime = todatetime(properties.essentials.startDateTime), lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime), dimensions = properties.context.context.condition.allOf[0].dimensions, // usefor metric alerts and log search alerts properties | extend targetResource = tolower(targetResource) | join kind=leftouter ( resources | project targetResource = tolower(id), targetResourceTags = tags) on targetResource | project-away targetResource1"
Elencare tutti i cluster Kubernetes abilitati per Azure Arc con l'estensione Monitoraggio di Azure
Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc con estensione monitoraggio di Azure installato.
KubernetesConfigurationResources
| where type == 'microsoft.kubernetesconfiguration/extensions'
| where properties.ExtensionType == 'microsoft.azuremonitor.containers'
| parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' *
| project connectedClusterId
az graph query -q "KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' * | project connectedClusterId"
Elencare tutti i cluster Kubernetes abilitati per Azure Arc senza l'estensione monitoraggio di Azure
Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc mancante dell'estensione Monitoraggio di Azure.
Resources
| where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId
| join kind = leftouter
(KubernetesConfigurationResources
| where type == 'microsoft.kubernetesconfiguration/extensions'
| where properties.ExtensionType == 'microsoft.azuremonitor.containers'
| parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' *
| project connectedClusterId
) on connectedClusterId
| where connectedClusterId1 == ''
| project connectedClusterId
az graph query -q "Resources | where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId | join kind = leftouter (KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' * | project connectedClusterId ) on connectedClusterId | where connectedClusterId1 == '' | project connectedClusterId"
Restituisce tutti gli avvisi di Monitoraggio di Azure in una sottoscrizione nell'ultimo giorno
{
"subscriptions": [
<subscriptionId>
],
"query": "alertsmanagementresources | where properties.essentials.lastModifiedDateTime > ago(1d) | project alertInstanceId = id, parentRuleId = tolower(tostring(properties['essentials']['alertRule'])), sourceId = properties['essentials']['sourceCreatedId'], alertName = name, severity = properties.essentials.severity, status = properties.essentials.monitorCondition, state = properties.essentials.alertState, affectedResource = properties.essentials.targetResourceName, monitorService = properties.essentials.monitorService, signalType = properties.essentials.signalType, firedTime = properties['essentials']['startDateTime'], lastModifiedDate = properties.essentials.lastModifiedDateTime, lastModifiedBy = properties.essentials.lastModifiedUserName"
}
Criteri di Azure
Conformità in base all'assegnazione di criteri
Fornisce lo stato di conformità, la percentuale di conformità e il numero di risorse per ogni assegnazione di Criteri di Azure.
PolicyResources
| where type =~ 'Microsoft.PolicyInsights/PolicyStates'
| extend complianceState = tostring(properties.complianceState)
| extend
resourceId = tostring(properties.resourceId),
policyAssignmentId = tostring(properties.policyAssignmentId),
policyAssignmentScope = tostring(properties.policyAssignmentScope),
policyAssignmentName = tostring(properties.policyAssignmentName),
policyDefinitionId = tostring(properties.policyDefinitionId),
policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId),
stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0)))))
| summarize max(stateWeight) by resourceId, policyAssignmentId, policyAssignmentScope, policyAssignmentName
| summarize counts = count() by policyAssignmentId, policyAssignmentScope, max_stateWeight, policyAssignmentName
| summarize overallStateWeight = max(max_stateWeight),
nonCompliantCount = sumif(counts, max_stateWeight == 300),
compliantCount = sumif(counts, max_stateWeight == 200),
conflictCount = sumif(counts, max_stateWeight == 100),
exemptCount = sumif(counts, max_stateWeight == 50) by policyAssignmentId, policyAssignmentScope, policyAssignmentName
| extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount)
| extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources)
| project policyAssignmentName, scope = policyAssignmentScope,
complianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))),
compliancePercentage,
compliantCount,
nonCompliantCount,
conflictCount,
exemptCount
az graph query -q "PolicyResources | where type =~ 'Microsoft.PolicyInsights/PolicyStates' | extend complianceState = tostring(properties.complianceState) | extend resourceId = tostring(properties.resourceId), policyAssignmentId = tostring(properties.policyAssignmentId), policyAssignmentScope = tostring(properties.policyAssignmentScope), policyAssignmentName = tostring(properties.policyAssignmentName), policyDefinitionId = tostring(properties.policyDefinitionId), policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId), stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0))))) | summarize max(stateWeight) by resourceId, policyAssignmentId, policyAssignmentScope, policyAssignmentName | summarize counts = count() by policyAssignmentId, policyAssignmentScope, max_stateWeight, policyAssignmentName | summarize overallStateWeight = max(max_stateWeight), nonCompliantCount = sumif(counts, max_stateWeight == 300), compliantCount = sumif(counts, max_stateWeight == 200), conflictCount = sumif(counts, max_stateWeight == 100), exemptCount = sumif(counts, max_stateWeight == 50) by policyAssignmentId, policyAssignmentScope, policyAssignmentName | extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount) | extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources) | project policyAssignmentName, scope = policyAssignmentScope, complianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))), compliancePercentage, compliantCount, nonCompliantCount, conflictCount, exemptCount"
Conformità per tipo di risorsa
Fornisce lo stato di conformità, la percentuale di conformità e il numero di risorse per ogni tipo di risorsa.
PolicyResources
| where type =~ 'Microsoft.PolicyInsights/PolicyStates'
| extend complianceState = tostring(properties.complianceState)
| extend
resourceId = tostring(properties.resourceId),
resourceType = tolower(tostring(properties.resourceType)),
policyAssignmentId = tostring(properties.policyAssignmentId),
policyDefinitionId = tostring(properties.policyDefinitionId),
policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId),
stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0)))))
| summarize max(stateWeight) by resourceId, resourceType
| summarize counts = count() by resourceType, max_stateWeight
| summarize overallStateWeight = max(max_stateWeight),
nonCompliantCount = sumif(counts, max_stateWeight == 300),
compliantCount = sumif(counts, max_stateWeight == 200),
conflictCount = sumif(counts, max_stateWeight == 100),
exemptCount = sumif(counts, max_stateWeight == 50) by resourceType
| extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount)
| extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources)
| project resourceType,
overAllComplianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))),
compliancePercentage,
compliantCount,
nonCompliantCount,
conflictCount,
exemptCount
az graph query -q "PolicyResources | where type =~ 'Microsoft.PolicyInsights/PolicyStates' | extend complianceState = tostring(properties.complianceState) | extend resourceId = tostring(properties.resourceId), resourceType = tolower(tostring(properties.resourceType)), policyAssignmentId = tostring(properties.policyAssignmentId), policyDefinitionId = tostring(properties.policyDefinitionId), policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId), stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0))))) | summarize max(stateWeight) by resourceId, resourceType | summarize counts = count() by resourceType, max_stateWeight | summarize overallStateWeight = max(max_stateWeight), nonCompliantCount = sumif(counts, max_stateWeight == 300), compliantCount = sumif(counts, max_stateWeight == 200), conflictCount = sumif(counts, max_stateWeight == 100), exemptCount = sumif(counts, max_stateWeight == 50) by resourceType | extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount) | extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources) | project resourceType, overAllComplianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))), compliancePercentage, compliantCount, nonCompliantCount, conflictCount, exemptCount"
Elencare tutte le risorse non conformi
Fornisce un elenco di tutti i tipi di risorse in uno NonCompliant
stato.
PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| where properties.complianceState == 'NonCompliant'
| extend NonCompliantResourceId = properties.resourceId, PolicyAssignmentName = properties.policyAssignmentName
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | where properties.complianceState == 'NonCompliant' | extend NonCompliantResourceId = properties.resourceId, PolicyAssignmentName = properties.policyAssignmentName"
Riepilogare la conformità delle risorse in base allo stato
Dettagli sul numero di risorse in ogni stato di conformità.
PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| extend complianceState = tostring(properties.complianceState)
| summarize count() by complianceState
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | extend complianceState = tostring(properties.complianceState) | summarize count() by complianceState"
Riepilogare la conformità delle risorse in base allo stato per posizione
Dettaglia il numero di risorse in ogni stato di conformità per posizione.
PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| extend complianceState = tostring(properties.complianceState)
| extend resourceLocation = tostring(properties.resourceLocation)
| summarize count() by resourceLocation, complianceState
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | extend complianceState = tostring(properties.complianceState) | extend resourceLocation = tostring(properties.resourceLocation) | summarize count() by resourceLocation, complianceState"
Esenzioni dei criteri per assegnazione
Elenca il numero di esenzioni per ogni assegnazione.
PolicyResources
| where type == 'microsoft.authorization/policyexemptions'
| summarize count() by tostring(properties.policyAssignmentId)
Per altre informazioni sull'uso di ambiti con l'interfaccia della riga di comando di Azure o Azure PowerShell, passare a Conteggio delle risorse di Azure.
Usare il --management-groups
parametro con un ID gruppo di gestione di Azure o un ID tenant. In questo esempio la tenantid
variabile archivia l'ID tenant.
tenantid="$(az account show --query tenantId --output tsv)"
az graph query -q "policyresources | where type == 'microsoft.authorization/policyexemptions' | summarize count() by tostring(properties.policyAssignmentId)" --management-groups $tenantid
Esenzioni dei criteri che scadono entro 90 giorni
Elenca il nome e la data di scadenza.
PolicyResources
| where type == 'microsoft.authorization/policyexemptions'
| extend expiresOnC = todatetime(properties.expiresOn)
| where isnotnull(expiresOnC)
| where expiresOnC >= now() and expiresOnC < now(+90d)
| project name, expiresOnC
az graph query -q "policyresources | where type == 'microsoft.authorization/policyexemptions' | extend expiresOnC = todatetime(properties.expiresOn) | where isnotnull(expiresOnC) | where expiresOnC >= now() and expiresOnC < now(+90d) | project name, expiresOnC"
Configurazione di guest di Criteri di Azure
Conteggio dei computer nell'ambito dei criteri di configurazione guest
Visualizza il conteggio delle macchine virtuali di Azure e dei server connessi Arc nell'ambito delle assegnazioni di configurazione guest Criteri di Azure.
GuestConfigurationResources
| where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments'
| extend vmid = split(properties.targetResourceId,'/')
| mvexpand properties.latestAssignmentReport.resources
| where properties_latestAssignmentReport_resources.resourceId != 'Invalid assignment package.'
| project machine = tostring(vmid[(-1)]),type = tostring(vmid[(-3)])
| distinct machine, type
| summarize count() by type
az graph query -q "GuestConfigurationResources | where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments' | extend vmid = split(properties.targetResourceId,'/') | mvexpand properties.latestAssignmentReport.resources | where properties_latestAssignmentReport_resources.resourceId != 'Invalid assignment package.' | project machine = tostring(vmid[(-1)]),type = tostring(vmid[(-3)]) | distinct machine, type | summarize count() by type"
Conteggio delle assegnazioni di configurazione guest non conformi
Visualizza un numero di computer non conformi per ogni motivo di assegnazione di configurazione guest. Limita i risultati ai primi 100 per le prestazioni.
GuestConfigurationResources
| where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments'
| project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| project id, vmid, name, status, resource = tostring(resources.resourceId), reason = reasons.phrase
| summarize count() by resource, name
| order by count_
| limit 100
az graph query -q "GuestConfigurationResources | where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments' | project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | project id, vmid, name, status, resource = tostring(resources.resourceId), reason = reasons.phrase | summarize count() by resource, name | order by count_ | limit 100"
Trovare tutti i motivi per cui un computer non è conforme alle assegnazioni di configurazione guest
Visualizzare tutti i motivi di assegnazione di configurazione guest per un computer specifico. Rimuovere la prima clausola where
per includere anche i controlli in cui il computer è conforme.
GuestConfigurationResources
| where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments'
| where properties.complianceStatus == 'NonCompliant'
| project id, name, resources = properties.latestAssignmentReport.resources, machine = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| where machine == 'MACHINENAME'
| project id, machine, name, status, resource = resources.resourceId, reason = reasons.phrase
az graph query -q "GuestConfigurationResources | where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments' | where properties.complianceStatus == 'NonCompliant' | project id, name, resources = properties.latestAssignmentReport.resources, machine = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | where machine == 'MACHINENAME' | project id, machine, name, status, resource = resources.resourceId, reason = reasons.phrase"
Elencare i computer e lo stato del riavvio in sospeso
Fornisce un elenco di computer con i dettagli di configurazione relativi all'eventuale riavvio in sospeso.
GuestConfigurationResources
| where name in ('WindowsPendingReboot')
| project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/'), status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase
| summarize name = any(name), status = any(status), vmid = any(vmid), resources = make_list_if(resource, isnotnull(resource)), reasons = make_list_if(reason, isnotnull(reason)) by id = tolower(id)
| project id, machine = tostring(vmid[(-1)]), type = tostring(vmid[(-3)]), name, status, reasons
az graph query -q "GuestConfigurationResources | where name in ('WindowsPendingReboot') | project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/'), status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase | summarize name = any(name), status = any(status), vmid = any(vmid), resources = make_list_if(resource, isnotnull(resource)), reasons = make_list_if(reason, isnotnull(reason)) by id = tolower(id) | project id, machine = tostring(vmid[(-1)]), type = tostring(vmid[(-3)]), name, status, reasons"
Elencare i computer che non sono in esecuzione e l'ultimo stato di conformità
Fornisce un elenco di computer che non sono accesi con le assegnazioni di configurazione e l'ultimo stato di conformità segnalato.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| where properties.extended.instanceView.powerState.code != 'PowerState/running'
| project vmName = name, power = properties.extended.instanceView.powerState.code
| join kind = leftouter (GuestConfigurationResources
| extend vmName = tostring(split(properties.targetResourceId,'/')[(-1)])
| project vmName, name, compliance = properties.complianceStatus) on vmName | project-away vmName1
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | where properties.extended.instanceView.powerState.code != 'PowerState/running' | project vmName = name, power = properties.extended.instanceView.powerState.code | join kind = leftouter (GuestConfigurationResources | extend vmName = tostring(split(properties.targetResourceId,'/')[(-1)]) | project vmName, name, compliance = properties.complianceStatus) on vmName | project-away vmName1"
Dettagli delle query dei report di assegnazione della configurazione guest
Visualizzare il report dai dettagli del motivo dell'assegnazione della configurazione guest . Nell'esempio seguente la query restituisce solo i risultati in cui il nome dell'assegnazione guest è installed_application_linux
e l'output contiene la stringa Chrome
per elencare tutti i computer Linux in cui è installato un pacchetto che include il nome Chrome.
GuestConfigurationResources
| where name in ('installed_application_linux')
| project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| where reasons.phrase contains 'chrome'
| project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase
az graph query -q "GuestConfigurationResources | where name in ('installed_application_linux') | project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | where reasons.phrase contains 'chrome' | project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase"
Controllo degli accessi in base al ruolo di Azure
Risolvere i problemi relativi ai limiti del controllo degli accessi in base al ruolo di Azure
La authorizationresources
tabella può essere usata per risolvere i problemi relativi al controllo degli accessi in base al ruolo di Azure se si superano i limiti. Per altre informazioni, vedere Risolvere i problemi relativi ai limiti del controllo degli accessi in base al ruolo di Azure.
Ottenere assegnazioni di ruolo con le proprietà chiave
Fornisce un esempio di assegnazioni di ruolo e alcune delle risorse pertinenti.
authorizationresources
| where type =~ 'microsoft.authorization/roleassignments'
| extend roleDefinitionId = properties.roleDefinitionId
| extend principalType = properties.principalType
| extend principalId = properties.principalId
| extend scope = properties.scope
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roleassignments' | extend roleDefinitionId = properties.roleDefinitionId | extend principalType = properties.principalType | extend principalId = properties.principalId | extend scope = properties.scope | take 5"
Ottenere definizioni di ruolo con proprietà chiave
Fornisce un esempio di definizioni di ruolo e alcune delle risorse pertinenti.
authorizationresources
| where type =~ 'microsoft.authorization/roledefinitions'
| extend assignableScopes = properties.assignableScopes
| extend permissionsList = properties.permissions
| extend isServiceRole = properties.isServiceRole
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roledefinitions' | extend assignableScopes = properties.assignableScopes | extend permissionsList = properties.permissions | extend isServiceRole = properties.isServiceRole | take 5"
Ottenere definizioni di ruolo con azioni
Visualizza un esempio di definizioni di ruolo con un elenco espanso di azioni e non azioni per l'elenco delle autorizzazioni di ogni definizione di ruolo.
authorizationresources
| where type =~ 'microsoft.authorization/roledefinitions'
| extend assignableScopes = properties.assignableScopes
| extend permissionsList = properties.permissions
| extend isServiceRole = properties.isServiceRole
| mv-expand permissionsList
| extend Actions = permissionsList.Actions
| extend notActions = permissionsList.notActions
| extend DataActions = permissionsList.DataActions
| extend notDataActions = permissionsList.notDataActions
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roledefinitions' | extend assignableScopes = properties.assignableScopes | extend permissionsList = properties.permissions | extend isServiceRole = properties.isServiceRole | mv-expand permissionsList | extend Actions = permissionsList.Actions | extend notActions = permissionsList.notActions | extend DataActions = permissionsList.DataActions | extend notDataActions = permissionsList.notDataActions | take 5"
Ottenere le definizioni di ruolo con le autorizzazioni elencate
Visualizza un riepilogo di e notActions
per ogni definizione di Actions
ruolo univoca.
authorizationresources
| where type =~ 'microsoft.authorization/roledefinitions'
| extend assignableScopes = properties.assignableScopes
| extend permissionsList = properties.permissions
| extend isServiceRole = properties.isServiceRole
| mv-expand permissionsList
| extend Actions = permissionsList.Actions
| extend notActions = permissionsList.notActions
| extend DataActions = permissionsList.DataActions
| extend notDataActions = permissionsList.notDataActions
| summarize make_set(Actions), make_set(notActions), make_set(DataActions), make_set(notDataActions), any(assignableScopes, isServiceRole) by id
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roledefinitions' | extend assignableScopes = properties.assignableScopes | extend permissionsList = properties.permissions | extend isServiceRole = properties.isServiceRole | mv-expand permissionsList | extend Actions = permissionsList.Actions | extend notActions = permissionsList.notActions | extend DataActions = permissionsList.DataActions | extend notDataActions = permissionsList.notDataActions | summarize make_set(Actions), make_set(notActions), make_set(DataActions), make_set(notDataActions), any(assignableScopes, isServiceRole) by id"
Ottenere gli amministratori classici con proprietà chiave
Fornisce un esempio di amministratori classici e di alcune delle risorse pertinenti.
authorizationresources
| where type =~ 'microsoft.authorization/classicadministrators'
| extend state = properties.adminState
| extend roles = split(properties.role, ';')
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/classicadministrators' | extend state = properties.adminState | extend roles = split(properties.role, ';') | take 5"
Integrità dei servizi di Azure
Impatto della sottoscrizione degli eventi di Integrità dei servizi attivi
Restituisce tutti gli eventi attivi di Integrità dei servizi, inclusi i problemi del servizio, la manutenzione pianificata, gli avvisi di integrità e gli avvisi di sicurezza, raggruppati per tipo di evento e incluso il numero di sottoscrizioni interessate.
ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = tostring(properties.EventType), status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime))
| where properties.Status == 'Active' and tolong(impactStartTime) > 1
| summarize count(subscriptionId) by name, eventType
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = tostring(properties.EventType), status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where properties.Status == 'Active' and tolong(impactStartTime) > 1 | summarize count(subscriptionId) by name, eventType"
Tutti gli eventi di consulenza sull'integrità attiva
Restituisce tutti gli eventi di integrità attiva di Integrità dei servizi in tutte le sottoscrizioni a cui l'utente ha accesso.
ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime))
| where properties.Status == 'Active' and tolong(impactStartTime) > 1 and eventType == 'HealthAdvisory'
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where properties.Status == 'Active' and tolong(impactStartTime) > 1 and eventType == 'HealthAdvisory'"
Tutti gli eventi di manutenzione pianificata attiva
Restituisce tutti gli eventi di integrità dei servizi di manutenzione pianificata attiva in tutte le sottoscrizioni a cui l'utente ha accesso.
ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime))
| where properties.Status == 'Active' and tolong(impactStartTime) > 1 and eventType == 'PlannedMaintenance'
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where properties.Status == 'Active' and tolong(impactStartTime) > 1 and eventType == 'PlannedMaintenance'"
Tutti gli eventi di integrità dei servizi attivi
Restituisce tutti gli eventi di integrità dei servizi attivi in tutte le sottoscrizioni a cui l'utente ha accesso, inclusi problemi di servizio, manutenzione pianificata, avvisi di integrità e avvisi di sicurezza.
ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime))
| where properties.Status == 'Active' and tolong(impactStartTime) > 1
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where properties.Status == 'Active' and tolong(impactStartTime) > 1"
Tutti gli eventi di problema del servizio attivo
Restituisce tutti gli eventi di integrità dei servizi attivi (interruzione) in tutte le sottoscrizioni a cui l'utente ha accesso.
ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime))
| where properties.Status == 'Active' and tolong(impactStartTime) > 1 and eventType == 'ServiceIssue'
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where properties.Status == 'Active' and tolong(impactStartTime) > 1 and eventType == 'ServiceIssue'"
SQL di Azure
Visualizzare i database SQL e i relativi pool elastici
La query seguente usa leftouterjoin
per riunire database SQL risorse e i pool elastici correlati, se presenti.
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"
Archiviazione di Azure
Trovare gli account di archiviazione con un tag specifico senza distinzione tra maiuscole e minuscole nel gruppo di risorse
Analogamente alla query "Trova account di archiviazione con un tag con distinzione tra maiuscole e minuscole nella query del gruppo di risorse", ma quando è necessario cercare un nome di tag senza distinzione tra maiuscole e minuscole e un valore di tag, usare mv-expand
con il parametro bagexpansion . Questa query usa una quota maggiore rispetto alla query originale, quindi usare mv-expand
solo se necessario.
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"
Trovare gli account di archiviazione con un tag specifico con distinzione tra maiuscole e minuscole nel gruppo di risorse
La query seguente usa un elemento internojoin
per connettere gli account di archiviazione ai gruppi di risorse con un nome di tag e un valore di tag con distinzione tra maiuscole e minuscole specificati.
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"
Elencare tutti gli account di archiviazione con un valore di tag specifico
Combinare la funzionalità di filtro dell'esempio precedente e filtrare il tipo di risorsa di Azure per la proprietà type. Questa query limita anche la ricerca di tipi specifici di risorse di Azure con un nome di tag e un valore specifici.
Resources
| where type =~ 'Microsoft.Storage/storageAccounts'
| where tags['tag with a space']=='Custom value'
az graph query -q "Resources | where type =~ 'Microsoft.Storage/storageAccounts' | where tags['tag with a space']=='Custom value'"
Mostrare le risorse che contengono archivi
Invece di definire in modo esplicito il tipo da individuare, questa query di esempio troverà tutte le risorse di Azure che contengono (contains
) la parola storage.
Resources
| where type contains 'storage' | distinct type
az graph query -q "Resources | where type contains 'storage' | distinct type"
Macchine virtuali di Azure
Conteggio dell'installazione dell'aggiornamento del sistema operativo completata
Restituisce un elenco di stato delle esecuzioni di installazione degli aggiornamenti del sistema operativo eseguite per i computer negli ultimi 7 giorni.
PatchAssessmentResources
| where type !has 'softwarepatches'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), OS = tostring(prop.osType), installedPatchCount = tostring(prop.installedPatchCount), failedPatchCount = tostring(prop.failedPatchCount), pendingPatchCount = tostring(prop.pendingPatchCount), excludedPatchCount = tostring(prop.excludedPatchCount), notSelectedPatchCount = tostring(prop.notSelectedPatchCount)
| where lTime > ago(7d)
| project lTime, RunID=name,machineName, rgName, resourceType, OS, installedPatchCount, failedPatchCount, pendingPatchCount, excludedPatchCount, notSelectedPatchCount
az graph query -q "PatchAssessmentResources | where type !has 'softwarepatches' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), OS = tostring(prop.osType), installedPatchCount = tostring(prop.installedPatchCount), failedPatchCount = tostring(prop.failedPatchCount), pendingPatchCount = tostring(prop.pendingPatchCount), excludedPatchCount = tostring(prop.excludedPatchCount), notSelectedPatchCount = tostring(prop.notSelectedPatchCount) | where lTime > ago(7d) | project lTime, RunID=name,machineName, rgName, resourceType, OS, installedPatchCount, failedPatchCount, pendingPatchCount, excludedPatchCount, notSelectedPatchCount"
Numero di macchine virtuali per stato di disponibilità e ID sottoscrizione
Restituisce il numero di macchine virtuali (tipo Microsoft.Compute/virtualMachines
) aggregate in base al relativo stato di disponibilità in ogni sottoscrizione.
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)"
Numero di macchine virtuali per stato di alimentazione
Restituisce il numero di macchine virtuali (tipo Microsoft.Compute/virtualMachines
) classificate in base al relativo stato di alimentazione. Per altre informazioni sugli stati di alimentazione, vedere Panoramica degli stati di Alimentazione.
Resources
| where type == 'microsoft.compute/virtualmachines'
| summarize count() by PowerState = tostring(properties.extended.instanceView.powerState.code)
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | summarize count() by PowerState = tostring(properties.extended.instanceView.powerState.code)"
Contare le macchine virtuali per tipo di sistema operativo
Continuando dalla query precedente, le risorse sono ancora limitate al tipo Microsoft.Compute/virtualMachines
, ma non è più presente il limite sul numero di record restituiti. Invece, sono stati usati summarize
e count()
per definire come raggruppare e aggregare i valori in base a una proprietà, che in questo esempio è properties.storageProfile.osDisk.osType
. Per un esempio dell'aspetto di questa stringa nell'oggetto completo, vedere le informazioni sull'esplorazione delle risorse e l'individuazione delle macchine virtuali.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| summarize count() by tostring(properties.storageProfile.osDisk.osType)
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | summarize count() by tostring(properties.storageProfile.osDisk.osType)"
Conteggia le macchine virtuali per tipo di sistema operativo con estensione
Un modo diverso per scrivere la query "Conteggio macchine virtuali per tipo di sistema operativo" è una extend
proprietà e assegnargli un nome temporaneo da usare all'interno della query, in questo caso sistema operativo. os viene quindi usato da summarize
e count()
come nell'esempio a cui si fa riferimento.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| extend os = properties.storageProfile.osDisk.osType
| summarize count() by tostring(os)
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | extend os = properties.storageProfile.osDisk.osType | summarize count() by tostring(os)"
Ottenere tutti gli avvisi nuovi dagli ultimi 30 giorni
Questa query fornisce un elenco di tutti gli avvisi Nuovi dell'utente, negli ultimi 30 giorni.
iotsecurityresources
| where type == 'microsoft.iotsecurity/locations/devicegroups/alerts'
| where todatetime(properties.startTimeUtc) > ago(30d) and properties.status == 'New'
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/locations/devicegroups/alerts' | where todatetime(properties.startTimeUtc) > ago(30d) and properties.status == 'New'"
Ottenere la capacità e le dimensioni di un set di scalabilità di macchine virtuali
Questa query cerca risorse di set di scalabilità di macchine virtuali e ottiene vari dettagli fra cui le dimensioni della macchina virtuale e la capacità del set di scalabilità. Questa query usa la funzione toint()
per eseguire il cast della capacità in un numero, in modo che possa essere ordinato. Infine, le colonne vengono rinominate in proprietà denominate personalizzate.
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"
Elencare tutte le estensioni installate in una macchina virtuale
Prima di tutto, questa query usa extend
nel tipo di risorsa macchine virtuali per ottenere l'ID in lettere maiuscole (toupper()
), il nome e il tipo del sistema operativo e le dimensioni della macchina virtuale. Ottenere l'ID risorsa in maiuscolo è un buon modo per preparare l'aggiunta a un'altra proprietà. Quindi, la query usa join
con tipo di tipoleftouter per ottenere le estensioni della macchina virtuale corrispondenti a un ID di estensione maiuscolo substring
. La parte dell'ID prima di "/extensions/<ExtensionName>" è lo stesso formato dell'ID delle macchine virtuali, quindi viene usata questa proprietà per .join
Viene quindi usato summarize
con make_list
nel nome dell'estensione della macchina virtuale per combinare il nome di ogni estensione in cui i valori di id, OSName, OSType e VMSize sono uguali in una singola proprietà della matrice. Infine, osNameorder by
minuscolo con asc. Per impostazione predefinita, order by
è decrescente.
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"
Elencare gli aggiornamenti del sistema operativo disponibili per tutti i computer raggruppati in base alla categoria di aggiornamento
Restituisce un elenco di sistemi operativi in sospeso per i computer.
PatchAssessmentResources
| where type !has 'softwarepatches'
| extend prop = parse_json(properties)
| extend lastTime = properties.lastModifiedDateTime
| extend updateRollupCount = prop.availablePatchCountByClassification.updateRollup, featurePackCount = prop.availablePatchCountByClassification.featurePack, servicePackCount = prop.availablePatchCountByClassification.servicePack, definitionCount = prop.availablePatchCountByClassification.definition, securityCount = prop.availablePatchCountByClassification.security, criticalCount = prop.availablePatchCountByClassification.critical, updatesCount = prop.availablePatchCountByClassification.updates, toolsCount = prop.availablePatchCountByClassification.tools, otherCount = prop.availablePatchCountByClassification.other, OS = prop.osType
| project lastTime, id, OS, updateRollupCount, featurePackCount, servicePackCount, definitionCount, securityCount, criticalCount, updatesCount, toolsCount, otherCount
az graph query -q "PatchAssessmentResources | where type !has 'softwarepatches' | extend prop = parse_json(properties) | extend lastTime = properties.lastModifiedDateTime | extend updateRollupCount = prop.availablePatchCountByClassification.updateRollup, featurePackCount = prop.availablePatchCountByClassification.featurePack, servicePackCount = prop.availablePatchCountByClassification.servicePack, definitionCount = prop.availablePatchCountByClassification.definition, securityCount = prop.availablePatchCountByClassification.security, criticalCount = prop.availablePatchCountByClassification.critical, updatesCount = prop.availablePatchCountByClassification.updates, toolsCount = prop.availablePatchCountByClassification.tools, otherCount = prop.availablePatchCountByClassification.other, OS = prop.osType | project lastTime, id, OS, updateRollupCount, featurePackCount, servicePackCount, definitionCount, securityCount, criticalCount, updatesCount, toolsCount, otherCount"
Elenco dell'installazione dell'aggiornamento del sistema operativo Linux completata
Restituisce un elenco di stato di Linux Server - Esecuzione dell'installazione dell'aggiornamento del sistema operativo per i computer negli ultimi 7 giorni.
PatchAssessmentResources
| where type has 'softwarepatches' and properties has 'version'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), version = tostring(prop.version), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications)
| where lTime > ago(7d)
| project lTime, RunID, machineName, rgName, resourceType, patchName, version, classifications, installationState
| sort by RunID
az graph query -q "PatchAssessmentResources | where type has 'softwarepatches' and properties has 'version' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), version = tostring(prop.version), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications) | where lTime > ago(7d) | project lTime, RunID, machineName, rgName, resourceType, patchName, version, classifications, installationState | sort by RunID"
Elenco delle macchine virtuali e degli stati di disponibilità associati in base agli ID risorsa
Restituisce l'elenco più recente di macchine virtuali (tipo ) aggregate in base Microsoft.Compute/virtualMachines
allo stato di disponibilità. La query fornisce anche l'ID risorsa associato in base a properties.targetResourceId
, per semplificare il debug e la mitigazione. Gli stati di disponibilità possono essere uno dei quattro valori disponibili, non disponibili, degradati e sconosciuti. Per altre informazioni sul significato di ognuno degli stati di disponibilità, vedere Panoramica di Azure Integrità risorse.
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"
Elenco di macchine virtuali per stato di disponibilità e stato di alimentazione con ID risorsa e gruppi di risorse
Restituisce l'elenco delle macchine virtuali (tipo Microsoft.Compute/virtualMachines
) aggregate sullo stato di alimentazione e sulla disponibilità per fornire uno stato di integrità coeso per le macchine virtuali. La query fornisce anche dettagli sul gruppo di risorse e sull'ID risorsa associato a ogni voce per una visibilità dettagliata sulle risorse.
Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code)
| join kind=leftouter (
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines'
| project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState))
on $left.Id == $right.targetResourceId
| project-away targetResourceId
| where PowerState != 'PowerState/deallocated'
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code) | join kind=leftouter ( HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines' | project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on \$left.Id == \$right.targetResourceId | project-away targetResourceId | where PowerState != 'PowerState/deallocated'"
Elenco di macchine virtuali che non sono disponibili per ID risorsa
Restituisce l'elenco più recente di macchine virtuali (tipo Microsoft.Compute/virtualMachines
) aggregate dallo stato di disponibilità. L'elenco popolato evidenzia solo le macchine virtuali in cui lo stato di disponibilità non è "Disponibile" per assicurarsi di essere consapevoli di tutti gli stati relativi alle macchine virtuali in uso. Quando tutte le macchine virtuali sono disponibili, è possibile aspettarsi di non ricevere risultati.
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| where tostring(properties.availabilityState) != 'Available'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.availabilityState) != 'Available' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"
Elenco dell'installazione dell'aggiornamento del sistema operativo Windows Server completata
Restituisce un elenco di stato di Windows Server : l'installazione dell'aggiornamento del sistema operativo viene eseguita per i computer negli ultimi 7 giorni.
PatchAssessmentResources
| where type has 'softwarepatches' and properties !has 'version'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), kbId = tostring(prop.kbId), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications)
| where lTime > ago(7d)
| project lTime, RunID, machineName, rgName, resourceType, patchName, kbId, classifications, installationState
| sort by RunID
az graph query -q "PatchAssessmentResources | where type has 'softwarepatches' and properties !has 'version' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), kbId = tostring(prop.kbId), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications) | where lTime > ago(7d) | project lTime, RunID, machineName, rgName, resourceType, patchName, kbId, classifications, installationState | sort by RunID"
Visualizzare le macchine virtuali con relative interfacce di rete e IP pubblici
Questa query usa due comandi leftouterjoin
per unire le macchine virtuali create con il modello di distribuzione Resource Manager, le interfacce di rete correlate e qualsiasi indirizzo IP pubblico correlato a tali interfacce di rete.
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"
Mostrare tutte le macchine virtuali ordinate per nome in ordine decrescente
Per elencare solo le macchine virtuali (che sono di tipo Microsoft.Compute/virtualMachines
), è possibile cercare le corrispondenze della proprietà type nei risultati. Analogamente alla query precedente, desc
cambia order by
in decrescente. Nella ricerca di corrispondenze per tipo, =~
induce Resource Graph a non distinguere fra maiuscole e minuscole.
Resources
| project name, location, type
| where type =~ 'Microsoft.Compute/virtualMachines'
| order by name desc
az graph query -q "Resources | project name, location, type | where type =~ 'Microsoft.Compute/virtualMachines' | order by name desc"
Mostrare le prime cinque macchine virtuali per nome e tipo di sistema operativo
Questa query usa top
per recuperare solo cinque record corrispondenti ordinati in base al nome. Il tipo della risorsa di Azure è Microsoft.Compute/virtualMachines
. project
indica ad Azure Resource Graph quali proprietà includere.
Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| project name, properties.storageProfile.osDisk.osType
| top 5 by name desc
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | project name, properties.storageProfile.osDisk.osType | top 5 by name desc"
Riepilogare la macchina virtuale in base alla proprietà estesa stati di alimentazione
Questa query usa le proprietà estese nelle macchine virtuali per riepilogare in base agli stati di alimentazione.
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)"
Macchine virtuali individuate da un'espressione regolare
Questa query cerca le macchine virtuali che corrispondono a un'espressione regolare (nota come regex). matches regex @ permette di definire l'espressione regolare usata per cercare le corrispondenze, ovvero ^Contoso(.*)[0-9]+$
. Tale definizione di espressione regolare è spiegata come:
^
- La corrispondenza deve cominciare all'inizio della stringa.Contoso
- Stringa con distinzione tra maiuscole e minuscole.(.*)
- Una corrispondenza di espressione secondaria:.
- Trova la corrispondenza di qualsiasi carattere, ad eccezione del carattere nuova riga.*
- Trova la corrispondenza dell'elemento precedente zero o più volte.
[0-9]
- Corrispondenza del gruppo di caratteri per i numeri da 0 a 9.+
- Trova la corrispondenza dell'elemento precedente una o più volte.$
- La corrispondenza dell'elemento precedente deve essere presente alla fine della stringa.
Dopo aver cercato le corrispondenze in base al nome, la query proietta il nome e applica l'ordinamento in base al nome in modo crescente.
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"
Generale
Contare le risorse di Azure
Questa query restituisce il numero di risorse di Azure esistenti nelle sottoscrizioni a cui l'utente ha accesso. È anche una query valida da usare per verificare che nella shell preferita siano installati i componenti di Azure Resource Graph appropriati e funzionino correttamente.
Resources
| summarize count()
az graph query -q "Resources | summarize count()"
Elencare le risorse interessate durante il trasferimento di una sottoscrizione di Azure
Restituisce alcune delle risorse di Azure interessate quando si trasferisce una sottoscrizione in una directory di Azure Active Directory (Azure AD) diversa. È necessario ricreare alcune delle risorse esistenti prima del trasferimento della sottoscrizione.
Resources
| where type in (
'microsoft.managedidentity/userassignedidentities',
'microsoft.keyvault/vaults',
'microsoft.sql/servers/databases',
'microsoft.datalakestore/accounts',
'microsoft.containerservice/managedclusters')
or identity has 'SystemAssigned'
or (type =~ 'microsoft.storage/storageaccounts' and properties['isHnsEnabled'] == true)
| summarize count() by type
az graph query -q "Resources | where type in ( 'microsoft.managedidentity/userassignedidentities', 'microsoft.keyvault/vaults', 'microsoft.sql/servers/databases', 'microsoft.datalakestore/accounts', 'microsoft.containerservice/managedclusters') or identity has 'SystemAssigned' or (type =~ 'microsoft.storage/storageaccounts' and properties['isHnsEnabled'] == true) | summarize count() by type"
Elencare le risorse ordinate per nome
Questa query restituisce qualsiasi tipo di risorsa, ma solo le proprietà name, type e location. Usa order by
per ordinare le proprietà in base alla proprietà name in ordine crescente (asc
).
Resources
| project name, type, location
| order by name asc
az graph query -q "Resources | project name, type, location | order by name asc"
Rimuovere colonne dai risultati
La query seguente usa summarize
per contare le risorse in base a sottoscrizione, join
per aggiungere i dettagli della sottoscrizione della tabella ResourceContainers, quindi project-away
per rimuovere alcune colonne.
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"
Mostrare i tipi di risorse e le versioni dell'API
Resource Graph usa principalmente la versione non di anteprima più recente dell'API di un provider di risorse per ottenere mediante l'operazione GET
le proprietà delle risorse durante un aggiornamento. In alcuni casi, la versione dell'API usata è stata sottoposta a override per fornire le proprietà più recenti o più usate nei risultati. La query seguente illustra in dettaglio la versione dell'API usata per la raccolta delle proprietà per ogni tipo di risorsa:
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"
IoT Defender
Conteggia tutti i sensori per tipo
Questa query riepiloga tutti i sensori in base al tipo (OT, EIoT).
iotsecurityresources
| where type == 'microsoft.iotsecurity/sensors'
| summarize count() by tostring(properties.sensorType)
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/sensors' | summarize count() by tostring(properties.sensorType)"
Contare il numero di dispositivi IoT presenti nella rete, in base al sistema operativo
Questa query riepiloga tutti i dispositivi IoT in base alla piattaforma del sistema operativo.
iotsecurityresources
| where type == 'microsoft.iotsecurity/locations/devicegroups/devices'
| summarize count() by tostring(properties.operatingSystem.platform)
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/locations/devicegroups/devices' | summarize count() by tostring(properties.operatingSystem.platform)"
Ottenere tutte le raccomandazioni di gravità elevata
Questa query fornisce un elenco di tutte le raccomandazioni di gravità elevata dell'utente.
iotsecurityresources
| where type == 'microsoft.iotsecurity/locations/devicegroups/recommendations'
| where properties.severity == 'High'
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/locations/devicegroups/recommendations' | where properties.severity == 'High'"
Elencare i siti con un valore di tag specifico
Questa query fornisce un elenco di tutti i siti con un valore di tag specifico.
iotsecurityresources
| where type == 'microsoft.iotsecurity/sites'
| where properties.tags['key'] =~ 'value1'
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/sites' | where properties.tags['key'] =~ 'value1'"
Gruppi di gestione
Numero di sottoscrizioni per gruppo di gestione
Riepiloga il numero di sottoscrizioni in ogni gruppo di gestione.
ResourceContainers
| where type =~ 'microsoft.management/managementgroups'
| project mgname = name
| join kind=leftouter (resourcecontainers | where type=~ 'microsoft.resources/subscriptions'
| extend mgParent = properties.managementGroupAncestorsChain | project id, mgname = tostring(mgParent[0].name)) on mgname
| summarize count() by mgname
az graph query -q "ResourceContainers | where type =~ 'microsoft.management/managementgroups' | project mgname = name | join kind=leftouter (resourcecontainers | where type=~ 'microsoft.resources/subscriptions' | extend mgParent = properties.managementGroupAncestorsChain | project id, mgname = tostring(mgParent[0].name)) on mgname | summarize count() by mgname"
Elencare tutti i predecessori del gruppo di gestione per un gruppo di gestione specificato
Fornisce i dettagli della gerarchia del gruppo di gestione per il gruppo di gestione specificato nell'ambito della query. In questo esempio il gruppo di gestione è denominato Application.
ResourceContainers
| where type =~ 'microsoft.management/managementgroups'
| extend mgParent = properties.details.managementGroupAncestorsChain
| mv-expand with_itemindex=MGHierarchy mgParent
| project name, properties.displayName, mgParent, MGHierarchy, mgParent.name
az graph query -q "ResourceContainers | where type =~ 'microsoft.management/managementgroups' | extend mgParent = properties.details.managementGroupAncestorsChain | mv-expand with_itemindex=MGHierarchy mgParent | project name, properties.displayName, mgParent, MGHierarchy, mgParent.name" --management-groups Application
Elencare tutti i predecessori del gruppo di gestione per una sottoscrizione specificata
Fornisce i dettagli della gerarchia del gruppo di gestione per la sottoscrizione specificata nell'ambito della query. In questo esempio il GUID della sottoscrizione è 111111111-1111-1111-1111-11111111111.
ResourceContainers
| where type =~ 'microsoft.resources/subscriptions'
| extend mgParent = properties.managementGroupAncestorsChain
| mv-expand with_itemindex=MGHierarchy mgParent
| project subscriptionId, name, mgParent, MGHierarchy, mgParent.name
az graph query -q "ResourceContainers | where type =~ 'microsoft.resources/subscriptions' | extend mgParent = properties.managementGroupAncestorsChain | mv-expand with_itemindex=MGHierarchy mgParent | project subscriptionId, name, mgParent, MGHierarchy, mgParent.name" --subscriptions 11111111-1111-1111-1111-111111111111
Elencare tutte le sottoscrizioni in un gruppo di gestione specificato
Fornisce il nome e l'ID sottoscrizione di tutte le sottoscrizioni nel gruppo di gestione specificato nell'ambito della query. In questo esempio il gruppo di gestione è denominato Application.
ResourceContainers
| where type =~ 'microsoft.resources/subscriptions'
| project subscriptionId, name
az graph query -q "ResourceContainers | where type =~ 'microsoft.resources/subscriptions' | project subscriptionId, name" --management-groups Application
Punteggio di sicurezza per gruppo di gestione
Restituisce il punteggio di sicurezza per gruppo di gestione.
SecurityResources
| where type == 'microsoft.security/securescores'
| project subscriptionId,
subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)),
weight = tolong(iff(properties.weight == 0, 1, properties.weight))
| join kind=leftouter (
ResourceContainers
| where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled'
| project subscriptionId, mgChain=properties.managementGroupAncestorsChain )
on subscriptionId
| mv-expand mg=mgChain
| summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name)
| extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2))
| project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore
| order by mgName asc
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores' | project subscriptionId, subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)), weight = tolong(iff(properties.weight == 0, 1, properties.weight)) | join kind=leftouter ( ResourceContainers | where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled' | project subscriptionId, mgChain=properties.managementGroupAncestorsChain ) on subscriptionId | mv-expand mg=mgChain | summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name) | extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2)) | project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore | order by mgName asc"
Microsoft Defender
Visualizzare tutti i Microsoft Defender attivi per gli avvisi cloud
Restituisce un elenco di tutti gli avvisi attivi nel Microsoft Defender per il tenant cloud.
securityresources
| where type =~ 'microsoft.security/locations/alerts'
| where properties.Status in ('Active')
| where properties.Severity in ('Low', 'Medium', 'High')
| project alert_type = tostring(properties.AlertType), SystemAlertId = tostring(properties.SystemAlertId), ResourceIdentifiers = todynamic(properties.ResourceIdentifiers)
az graph query -q "securityresources | where type =~ 'microsoft.security/locations/alerts' | where properties.Status in ('Active') | where properties.Severity in ('Low', 'Medium', 'High') | project alert_type = tostring(properties AlertType), SystemAlertId = tostring(properties.SystemAlertId), ResourceIdentifiers = todynamic(properties ResourceIdentifiers)"
Controlla il punteggio di sicurezza per sottoscrizione
Restituisce un punteggio di sicurezza per ogni sottoscrizione.
SecurityResources
| where type == 'microsoft.security/securescores/securescorecontrols'
| extend controlName=properties.displayName,
controlId=properties.definition.name,
notApplicableResourceCount=properties.notApplicableResourceCount,
unhealthyResourceCount=properties.unhealthyResourceCount,
healthyResourceCount=properties.healthyResourceCount,
percentageScore=properties.score.percentage,
currentScore=properties.score.current,
maxScore=properties.definition.properties.maxScore,
weight=properties.weight,
controlType=properties.definition.properties.source.sourceType,
controlRecommendationIds=properties.definition.properties.assessmentDefinitions
| project tenantId, subscriptionId, controlName, controlId, unhealthyResourceCount, healthyResourceCount, notApplicableResourceCount, percentageScore, currentScore, maxScore, weight, controlType, controlRecommendationIds
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores/securescorecontrols' | extend controlName=properties.displayName, controlId=properties.definition.name, notApplicableResourceCount=properties.notApplicableResourceCount, unhealthyResourceCount=properties.unhealthyResourceCount, healthyResourceCount=properties.healthyResourceCount, percentageScore=properties.score.percentage, currentScore=properties.score.current, maxScore=properties.definition.properties.maxScore, weight=properties.weight, controlType=properties.definition.properties.source.sourceType, controlRecommendationIds=properties.definition.properties.assessmentDefinitions | project tenantId, subscriptionId, controlName, controlId, unhealthyResourceCount, healthyResourceCount, notApplicableResourceCount, percentageScore, currentScore, maxScore, weight, controlType, controlRecommendationIds"
Contare le risorse integre, non integre e non applicabili per ogni raccomandazione
Restituisce il numero di risorse integre, non integre e non applicabili per ogni raccomandazione. Usare summarize
e count
per definire come raggruppare e aggregare i valori per proprietà.
SecurityResources
| where type == 'microsoft.security/assessments'
| extend resourceId=id,
recommendationId=name,
resourceType=type,
recommendationName=properties.displayName,
source=properties.resourceDetails.Source,
recommendationState=properties.status.code,
description=properties.metadata.description,
assessmentType=properties.metadata.assessmentType,
remediationDescription=properties.metadata.remediationDescription,
policyDefinitionId=properties.metadata.policyDefinitionId,
implementationEffort=properties.metadata.implementationEffort,
recommendationSeverity=properties.metadata.severity,
category=properties.metadata.categories,
userImpact=properties.metadata.userImpact,
threats=properties.metadata.threats,
portalLink=properties.links.azurePortal
| summarize numberOfResources=count(resourceId) by tostring(recommendationName), tostring(recommendationState)
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | extend resourceId=id, recommendationId=name, resourceType=type, recommendationName=properties.displayName, source=properties.resourceDetails.Source, recommendationState=properties.status.code, description=properties.metadata.description, assessmentType=properties.metadata.assessmentType, remediationDescription=properties.metadata.remediationDescription, policyDefinitionId=properties.metadata.policyDefinitionId, implementationEffort=properties.metadata.implementationEffort, recommendationSeverity=properties.metadata.severity, category=properties.metadata.categories, userImpact=properties.metadata.userImpact, threats=properties.metadata.threats, portalLink=properties.links.azurePortal | summarize numberOfResources=count(resourceId) by tostring(recommendationName), tostring(recommendationState)"
Ottenere tutti gli avvisi IoT nell'hub, filtrati per tipo
Restituisce tutti gli avvisi IoT per un hub specifico (sostituire segnaposto {hub_id}
) e il tipo di avviso (sostituire il segnaposto {alert_type}
).
SecurityResources
| where type =~ 'microsoft.security/iotalerts' and id contains '{hub_id}' and properties.alertType contains '{alert_type}'
az graph query -q "SecurityResources | where type =~ 'microsoft.security/iotalerts' and id contains '{hub_id}' and properties.alertType contains '{alert_type}'"
Ottenere informazioni dettagliate sulla riservatezza di una risorsa specifica
Restituisce informazioni dettagliate sulla riservatezza di una risorsa specifica (sostituire il segnaposto {resource_id}).
SecurityResources
| where type == 'microsoft.security/insights/classification'
| where properties.associatedResource contains '$resource_id'
| project SensitivityInsight = properties.insightProperties.purviewCatalogs[0].sensitivity
az graph query -q "SecurityResources | where type == 'microsoft.security/insights/classification' | where properties.associatedResource contains '\$resource_id' | project SensitivityInsight = properties.insightProperties.purviewCatalogs[0].sensitivity"
Ottenere un avviso IoT specifico
Restituisce un avviso IoT specifico da un ID avviso di sistema specificato (sostituire il segnaposto {system_Alert_Id}
).
SecurityResources
| where type =~ 'microsoft.security/iotalerts' and properties.systemAlertId contains '{system_Alert_Id}'
az graph query -q "SecurityResources | where type =~ 'microsoft.security/iotalerts' and properties.systemAlertId contains '{system_Alert_Id}'"
Elencare i risultati della valutazione della vulnerabilità di Registro Container
Restituisce tutte le vulnerabilità rilevate nelle immagini del contenitore. Microsoft Defender per i contenitori deve essere abilitato per visualizzare questi risultati di sicurezza.
SecurityResources
| where type == 'microsoft.security/assessments'
| where properties.displayName contains 'Container registry images should have vulnerability findings resolved'
| summarize by assessmentKey=name //the ID of the assessment
| join kind=inner (
securityresources
| where type == 'microsoft.security/assessments/subassessments'
| extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id)
) on assessmentKey
| project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId
| extend description = properties.description,
displayName = properties.displayName,
resourceId = properties.resourceDetails.id,
resourceSource = properties.resourceDetails.source,
category = properties.category,
severity = properties.status.severity,
code = properties.status.code,
timeGenerated = properties.timeGenerated,
remediation = properties.remediation,
impact = properties.impact,
vulnId = properties.id,
additionalData = properties.additionalData
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | where properties.displayName contains 'Container registry images should have vulnerability findings resolved' | summarize by assessmentKey=name //the ID of the assessment | join kind=inner ( securityresources | where type == 'microsoft.security/assessments/subassessments' | extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id) ) on assessmentKey | project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId | extend description = properties.description, displayName = properties.displayName, resourceId = properties.resourceDetails.id, resourceSource = properties.resourceDetails.source, category = properties.category, severity = properties.status.severity, code = properties.status.code, timeGenerated = properties.timeGenerated, remediation = properties.remediation, impact = properties.impact, vulnId = properties.id, additionalData = properties.additionalData"
Elencare Microsoft Defender raccomandazioni
Restituisce tutte le valutazioni Microsoft Defender, organizzate in modo tabulare con campo per proprietà.
SecurityResources
| where type == 'microsoft.security/assessments'
| extend resourceId=id,
recommendationId=name,
recommendationName=properties.displayName,
source=properties.resourceDetails.Source,
recommendationState=properties.status.code,
description=properties.metadata.description,
assessmentType=properties.metadata.assessmentType,
remediationDescription=properties.metadata.remediationDescription,
policyDefinitionId=properties.metadata.policyDefinitionId,
implementationEffort=properties.metadata.implementationEffort,
recommendationSeverity=properties.metadata.severity,
category=properties.metadata.categories,
userImpact=properties.metadata.userImpact,
threats=properties.metadata.threats,
portalLink=properties.links.azurePortal
| project tenantId, subscriptionId, resourceId, recommendationName, recommendationId, recommendationState, recommendationSeverity, description, remediationDescription, assessmentType, policyDefinitionId, implementationEffort, userImpact, category, threats, source, portalLink
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | extend resourceId=id, recommendationId=name, recommendationName=properties.displayName, source=properties.resourceDetails.Source, recommendationState=properties.status.code, description=properties.metadata.description, assessmentType=properties.metadata.assessmentType, remediationDescription=properties.metadata.remediationDescription, policyDefinitionId=properties.metadata.policyDefinitionId, implementationEffort=properties.metadata.implementationEffort, recommendationSeverity=properties.metadata.severity, category=properties.metadata.categories, userImpact=properties.metadata.userImpact, threats=properties.metadata.threats, portalLink=properties.links.azurePortal | project tenantId, subscriptionId, resourceId, recommendationName, recommendationId, recommendationState, recommendationSeverity, description, remediationDescription, assessmentType, policyDefinitionId, implementationEffort, userImpact, category, threats, source, portalLink"
Elencare i risultati della valutazione della vulnerabilità Qualys
Restituisce tutte le vulnerabilità rilevate nelle macchine virtuali in cui è installato un agente Qualys.
SecurityResources
| where type == 'microsoft.security/assessments'
| where * contains 'vulnerabilities in your virtual machines'
| summarize by assessmentKey=name //the ID of the assessment
| join kind=inner (
securityresources
| where type == 'microsoft.security/assessments/subassessments'
| extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id)
) on assessmentKey
| project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId
| extend description = properties.description,
displayName = properties.displayName,
resourceId = properties.resourceDetails.id,
resourceSource = properties.resourceDetails.source,
category = properties.category,
severity = properties.status.severity,
code = properties.status.code,
timeGenerated = properties.timeGenerated,
remediation = properties.remediation,
impact = properties.impact,
vulnId = properties.id,
additionalData = properties.additionalData
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | where * contains 'vulnerabilities in your virtual machines' | summarize by assessmentKey=name //the ID of the assessment | join kind=inner ( securityresources | where type == 'microsoft.security/assessments/subassessments' | extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id) ) on assessmentKey | project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId | extend description = properties.description, displayName = properties.displayName, resourceId = properties.resourceDetails.id, resourceSource = properties.resourceDetails.source, category = properties.category, severity = properties.status.severity, code = properties.status.code, timeGenerated = properties.timeGenerated, remediation = properties.remediation, impact = properties.impact, vulnId = properties.id, additionalData = properties.additionalData"
Stato di valutazione della conformità alle normative
Restituisce lo stato di valutazione della conformità alle normative in base allo standard e al controllo di conformità.
SecurityResources
| where type == 'microsoft.security/regulatorycompliancestandards/regulatorycompliancecontrols/regulatorycomplianceassessments'
| extend assessmentName=properties.description,
complianceStandard=extract(@'/regulatoryComplianceStandards/(.+)/regulatoryComplianceControls',1,id),
complianceControl=extract(@'/regulatoryComplianceControls/(.+)/regulatoryComplianceAssessments',1,id),
skippedResources=properties.skippedResources,
passedResources=properties.passedResources,
failedResources=properties.failedResources,
state=properties.state
| project tenantId, subscriptionId, id, complianceStandard, complianceControl, assessmentName, state, skippedResources, passedResources, failedResources
az graph query -q "SecurityResources | where type == 'microsoft.security/regulatorycompliancestandards/regulatorycompliancecontrols/regulatorycomplianceassessments' | extend assessmentName=properties.description, complianceStandard=extract(@'/regulatoryComplianceStandards/(.+)/regulatoryComplianceControls',1,id), complianceControl=extract(@'/regulatoryComplianceControls/(.+)/regulatoryComplianceAssessments',1,id), skippedResources=properties.skippedResources, passedResources=properties.passedResources, failedResources=properties.failedResources, state=properties.state | project tenantId, subscriptionId, id, complianceStandard, complianceControl, assessmentName, state, skippedResources, passedResources, failedResources"
Stato di conformità alle normative per standard di conformità
Restituisce lo stato di conformità alle normative per ogni sottoscrizione standard di conformità.
SecurityResources
| where type == 'microsoft.security/regulatorycompliancestandards'
| extend complianceStandard=name,
state=properties.state,
passedControls=properties.passedControls,
failedControls=properties.failedControls,
skippedControls=properties.skippedControls,
unsupportedControls=properties.unsupportedControls
| project tenantId, subscriptionId, complianceStandard, state, passedControls, failedControls, skippedControls, unsupportedControls
az graph query -q "SecurityResources | where type == 'microsoft.security/regulatorycompliancestandards' | extend complianceStandard=name, state=properties.state, passedControls=properties.passedControls, failedControls=properties.failedControls, skippedControls=properties.skippedControls, unsupportedControls=properties.unsupportedControls | project tenantId, subscriptionId, complianceStandard, state, passedControls, failedControls, skippedControls, unsupportedControls"
Punteggio sicuro per gruppo di gestione
Restituisce il punteggio di sicurezza per gruppo di gestione.
SecurityResources
| where type == 'microsoft.security/securescores'
| project subscriptionId,
subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)),
weight = tolong(iff(properties.weight == 0, 1, properties.weight))
| join kind=leftouter (
ResourceContainers
| where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled'
| project subscriptionId, mgChain=properties.managementGroupAncestorsChain )
on subscriptionId
| mv-expand mg=mgChain
| summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name)
| extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2))
| project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore
| order by mgName asc
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores' | project subscriptionId, subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)), weight = tolong(iff(properties.weight == 0, 1, properties.weight)) | join kind=leftouter ( ResourceContainers | where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled' | project subscriptionId, mgChain=properties.managementGroupAncestorsChain ) on subscriptionId | mv-expand mg=mgChain | summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name) | extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2)) | project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore | order by mgName asc"
Punteggio sicuro per sottoscrizione
Restituisce il punteggio di sicurezza per sottoscrizione.
SecurityResources
| where type == 'microsoft.security/securescores'
| extend percentageScore=properties.score.percentage,
currentScore=properties.score.current,
maxScore=properties.score.max,
weight=properties.weight
| project tenantId, subscriptionId, percentageScore, currentScore, maxScore, weight
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores' | extend percentageScore=properties.score.percentage, currentScore=properties.score.current, maxScore=properties.score.max, weight=properties.weight | project tenantId, subscriptionId, percentageScore, currentScore, maxScore, weight"
Mostra il piano tariffario del piano Defender per cloud per sottoscrizione
Restituisce Defender per il piano tariffario del piano cloud per sottoscrizione.
SecurityResources
| where type == 'microsoft.security/pricings'
| project Subscription= subscriptionId, Azure_Defender_plan= name, Status= properties.pricingTier
az graph query -q "SecurityResources | where type == 'microsoft.security/pricings' | project Subscription= subscriptionId, Azure_Defender_plan= name, Status= properties.pricingTier"
Rete
Contare le risorse che hanno indirizzi IP configurati per sottoscrizione
Usando la query di esempio "Elenca tutti gli indirizzi IP pubblici" e aggiungendo summarize
e count()
, è possibile ottenere un elenco per sottoscrizione di risorse con indirizzi IP configurati.
Resources
| where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress)
| summarize count () by subscriptionId
az graph query -q "Resources | where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress) | summarize count () by subscriptionId"
Ottenere reti virtuali e subnet di interfacce di rete
Usare un'espressione parse
regolare per ottenere i nomi della rete virtuale e della subnet dalla proprietà ID risorsa. Anche se parse
consente di ottenere dati da un campo complesso, è ottimale accedere alle proprietà direttamente se esistenti anziché usare 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"
Elencare tutti gli indirizzi IP pubblici
Analogamente alla query "Mostra risorse che contengono archiviazione", trovare tutto ciò che è un tipo con la parola publicIPAddresses. Questa query si espande su tale modello per includere solo i risultati in cui properties.ipAddress, per restituire solo le proprietà.ipAddressisnotempty
e i limit
risultati dei primi 100. Potrebbe essere necessario eseguire l'escape delle virgolette a seconda della shell in uso.
Resources
| where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress)
| project properties.ipAddress
| limit 100
az graph query -q "Resources | where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress) | project properties.ipAddress | limit 100"
Mostrare i gruppi di sicurezza di rete non associati
Questa query restituisce gruppi di sicurezza di rete (NSG) che non sono associati a un'interfaccia di rete o a una subnet.
Resources
| where type =~ 'microsoft.network/networksecuritygroups' and isnull(properties.networkInterfaces) and isnull(properties.subnets)
| project name, resourceGroup
| sort by name asc
az graph query -q "Resources | where type =~ 'microsoft.network/networksecuritygroups' and isnull(properties.networkInterfaces) and isnull(properties.subnets) | project name, resourceGroup | sort by name asc"
Visualizzare le macchine virtuali con indirizzi IP pubblici sku di base
Questa query restituisce un elenco di ID macchina virtuale con indirizzi IP pubblici sku di base collegati.
Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project vmId = tolower(id), vmNics = properties.networkProfile.networkInterfaces
| join (
Resources |
where type =~ 'microsoft.network/networkinterfaces' |
project nicVMId = tolower(tostring(properties.virtualMachine.id)), allVMNicID = tolower(id), nicIPConfigs = properties.ipConfigurations)
on $left.vmId == $right.nicVMId
| join (
Resources
| where type =~ 'microsoft.network/publicipaddresses' and isnotnull(properties.ipConfiguration.id)
| where sku.name == 'Basic' // exclude to find all VMs with Public IPs
| project pipId = id, pipSku = sku.name, pipAssociatedNicId = tolower(tostring(split(properties.ipConfiguration.id, '/ipConfigurations/')[0])))
on $left.allVMNicID == $right.pipAssociatedNicId
| project vmId, pipId, pipSku
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | project vmId = tolower(id), vmNics = properties.networkProfile.networkInterfaces | join (Resources | where type =~ 'microsoft.network/networkinterfaces' | project nicVMId = tolower(tostring(properties.virtualMachine.id)), allVMNicID = tolower(id), nicIPConfigs = properties.ipConfigurations) on \$left.vmId == \$right.nicVMId | join ( Resources | where type =~ 'microsoft.network/publicipaddresses' and isnotnull(properties.ipConfiguration.id) | where sku.name == 'Basic' | project pipId = id, pipSku = sku.name, pipAssociatedNicId = tolower(tostring(split(properties.ipConfiguration.id, '/ipConfigurations/')[0]))) on \$left.allVMNicID == \$right.pipAssociatedNicId | project vmId, pipId, pipSku"
Resource Health
Numero di macchine virtuali in base allo stato di disponibilità e all'ID sottoscrizione
Restituisce il conteggio delle macchine virtuali (tipo Microsoft.Compute/virtualMachines
) aggregate dallo stato di disponibilità in ognuna delle sottoscrizioni.
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)"
Elenco di macchine virtuali e stati di disponibilità associati in base agli ID risorsa
Restituisce l'elenco più recente di macchine virtuali (tipo Microsoft.Compute/virtualMachines
) aggregate in base allo stato di disponibilità. La query fornisce anche l'ID risorsa associato basato su properties.targetResourceId
, per semplificare il debug e la mitigazione. Gli stati di disponibilità possono essere uno di quattro valori: Disponibile, Non disponibile, Danneggiato e Sconosciuto. Per altre informazioni sul significato di ognuno degli stati di disponibilità, vedere Panoramica di Azure Integrità risorse.
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"
Elenco di macchine virtuali per stato di disponibilità e stato di alimentazione con ID risorsa e gruppi di risorse
Restituisce un elenco di macchine virtuali (tipo Microsoft.Compute/virtualMachines
) aggregate sullo stato di alimentazione e sullo stato di disponibilità per fornire uno stato di integrità coeso per le macchine virtuali. La query fornisce anche informazioni dettagliate sul gruppo di risorse e sull'ID risorsa associati a ogni voce per ottenere visibilità dettagliata sulle risorse.
Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code)
| join kind=leftouter (
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines'
| project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState))
on $left.Id == $right.targetResourceId
| project-away targetResourceId
| where PowerState != 'PowerState/deallocated'
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code) | join kind=leftouter ( HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines' | project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on \$left.Id == \$right.targetResourceId | project-away targetResourceId | where PowerState != 'PowerState/deallocated'"
Elenco di macchine virtuali non disponibili per ID risorsa
Restituisce l'elenco più recente di macchine virtuali (tipo Microsoft.Compute/virtualMachines
) aggregate in base allo stato di disponibilità. L'elenco popolato evidenzia solo le macchine virtuali il cui stato di disponibilità non è "Disponibile" per assicurarsi di conoscere tutti gli stati relativi alle macchine virtuali. Quando tutte le macchine virtuali sono disponibili, è possibile prevedere di non ricevere risultati.
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| where tostring(properties.availabilityState) != 'Available'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.availabilityState) != 'Available' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"
Tag
Trovare gli account di archiviazione con un tag specifico senza distinzione tra maiuscole e minuscole nel gruppo di risorse
Analogamente alla query "Trova account di archiviazione con un tag con distinzione tra maiuscole e minuscole nella query del gruppo di risorse", ma quando è necessario cercare un nome di tag senza distinzione tra maiuscole e minuscole e un valore di tag, usare mv-expand
con il parametro bagexpansion . Questa query usa una quota maggiore rispetto alla query originale, quindi usare mv-expand
solo se necessario.
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"
Trovare gli account di archiviazione con un tag specifico con distinzione tra maiuscole e minuscole nel gruppo di risorse
La query seguente usa un elemento internojoin
per connettere gli account di archiviazione ai gruppi di risorse con un nome di tag e un valore di tag con distinzione tra maiuscole e minuscole specificati.
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"
Elencare tutti i nomi di tag
Questa query inizia con il tag e compila un oggetto JSON che elenca tutti i nomi di tag univoci e i tipi corrispondenti.
Resources
| project tags
| summarize buildschema(tags)
az graph query -q "Resources | project tags | summarize buildschema(tags)"
Elencare tutti i tag e i relativi valori
Questa query elenca i tag nei gruppi di gestione, nelle sottoscrizioni e nelle risorse insieme ai relativi valori. La query limita innanzitutto le risorse in cui i tag isnotempty()
, limitano i campi inclusi includendo solo i tag in project
e mvexpand
per extend
ottenere i dati associati dal contenitore delle proprietà. Viene quindi usato union
per combinare i risultati di ResourceContainers agli stessi risultati di Resources, offrendo un'ampia copertura a cui vengono recuperati i tag. Infine, limita i risultati ai distinct
dati associati ed esclude i tag nascosti dal sistema.
ResourceContainers
| where isnotempty(tags)
| project tags
| mvexpand tags
| extend tagKey = tostring(bag_keys(tags)[0])
| extend tagValue = tostring(tags[tagKey])
| union (
resources
| where isnotempty(tags)
| project tags
| mvexpand tags
| extend tagKey = tostring(bag_keys(tags)[0])
| extend tagValue = tostring(tags[tagKey])
)
| distinct tagKey, tagValue
| where tagKey !startswith "hidden-"
az graph query -q "ResourceContainers | where isnotempty(tags) | project tags | mvexpand tags | extend tagKey = tostring(bag_keys(tags)[0]) | extend tagValue = tostring(tags[tagKey]) | union ( resources | where isnotempty(tags) | project tags | mvexpand tags | extend tagKey = tostring(bag_keys(tags)[0]) | extend tagValue = tostring(tags[tagKey]) ) | distinct tagKey, tagValue | where tagKey !startswith "hidden-""
Elencare le risorse con un valore di tag specifico
È possibile limitare i risultati mediante proprietà diverse dal tipo di risorsa di Azure, ad esempio un tag. In questo esempio si applica alle risorse di Azure un filtro basato sul nome di tag Environment con il valore Internal. Per fornire anche i tag della risorsa e i relativi valori, aggiungere la proprietà tags per alla parola chiave project
.
Resources
| where tags.environment=~'internal'
| project name, tags
az graph query -q "Resources | where tags.environment=~'internal' | project name, tags"
Passaggi successivi
- Altre informazioni sul linguaggio di query.
- Altre informazioni su come esplorare le risorse.