Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
Внимание
Примеры запросов и содержимое этой статьи восстановлены на общедоступном динамическом сайте ARG. Примеры, оставленные на этом сайте, больше не обновляются или не поддерживаются. Обозреватель Azure Resource Graph на портале включает поддерживаемые категории и таблицы, а вкладка «Начало работы» содержит примерные запросы и расширенные запросы, которые можно открыть и выполнить в обозревателе ARG.
Эта страница содержит коллекцию примеров запросов Azure Resource Graph, сгруппированных по таблице. Чтобы перейти к определенной таблице, используйте ссылки в верхней части страницы. Или нажмите CTRL-F, чтобы использовать функцию поиска в браузере. Список таблиц и связанные сведения доступны в разделе Таблицы Resource Graph.
Ресурсы Советника
Получите сводку по экономии затрат от Советника Azure
Этот запрос позволяет получить сводку по сокращению затрат для каждой рекомендации Помощника по Azure.
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"
Список серверов с поддержкой Arc, которые не используют самую новую версию агента
Этот запрос возвращает все серверы с поддержкой Arc, на которых выполняется устаревшая версия агента Connected Machine. Агенты с состоянием Срок действия истек исключаются из результатов. В запросе используется leftouterjoin
для объединения рекомендаций Advisor, касающихся агентов Connected Machine, выявленных как устаревшие, и гибридных компьютеров, чтобы отфильтровать агентов, которые не обменивались данными с Azure в течение определенного периода времени.
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"
AppServiceResources
Список версий TLS для службы приложений Azure
Укажите минимальную версию протокола TLS для службы приложений Azure в отношении входящих запросов к веб-приложению.
AppServiceResources
| where type =~ 'microsoft.web/sites/config'
| project id, name, properties.MinTlsVersion
az graph query -q "AppServiceResources | where type =~ 'microsoft.web/sites/config' | project id, name, properties.MinTlsVersion"
РесурсыАвторизации
Устранение неполадок с ограничениями Azure RBAC
Таблицу authorizationresources
можно использовать для устранения неполадок управления доступом на основе ролей Azure (Azure RBAC) при превышении ограничений. Для получения дополнительной информации перейдите к Устранение неполадок, связанных с ограничениями Azure RBAC.
Получение назначений ролей с помощью ключевых свойств
Предоставляет пример назначений ролей и некоторые соответствующие свойства ресурсов.
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"
Получение определений ролей с помощью ключевых свойств
Предоставляет пример определений ролей и некоторые соответствующие свойства ресурсов.
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"
Получение определений ролей с действиями
Отображает пример определений ролей с расширенным списком Действий и Недействий для каждого списка разрешений в определении роли.
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"
Получите определения ролей с перечислением разрешений
Отображает сводку по каждому уникальному Actions
notActions
определению роли.
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"
Получите классических администраторов с ключевыми свойствами
Предоставляет пример классических администраторов и некоторые соответствующие свойства ресурсов.
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"
ComputeResources
Единообразная оркестрация масштабируемого набора виртуальных машин
Получите виртуальные машины в режиме унифицированной оркестрации набора масштабируемых виртуальных машин, классифицированные по состоянию питания. Эта таблица содержит представление модели и powerState
свойства представления экземпляра для части виртуальных машин в универсальном режиме масштабируемого набора виртуальных машин.
Представление модели и powerState
свойства представления экземпляра для части гибкого режима масштабируемого набора виртуальных машин можно запрашивать через Resources
таблицу.
ComputeResources
| where type =~ 'microsoft.compute/virtualmachinescalesets/virtualmachines'
| extend powerState = properties.extended.instanceView.powerState.code
| project name, powerState, id
az graph query -q "ComputeResources | where type =~ 'microsoft.compute/virtualmachinescalesets/virtualmachines' | extend powerState = properties.extended.instanceView.powerState.code | project name, powerState, id"
РасширенныеРесурсыМестоположения
Получите доступные типы ресурсов для настраиваемых расположений, поддерживающих Azure Arc
Выводит список доступных типов ресурсов для настраиваемых расположений с поддержкой Azure Arc.
ExtendedLocationResources
| where type == 'microsoft.extendedlocation/customlocations/enabledresourcetypes'
az graph query -q "ExtendedLocationResources | where type == 'microsoft.extendedlocation/customlocations/enabledresourcetypes'"
Список пользовательских расположений, поддерживающих Azure Arc и включающих VMware или SCVMM
Выводит список всех настраиваемых расположений с поддержкой Azure Arc, которые поддерживают тип ресурса VMware или SCVMM.
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"
Ресурсы конфигурации гостя
Число компьютеров в области применения политик гостевой конфигурации
Отображает число виртуальных машин Azure и серверов, подключенных к Arc, в рамках назначения гостевой конфигурации Политики 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"
Число несоответствующих назначений гостевой конфигурации
Отображает число несоответствующих компьютеров для каждой причины назначения гостевой конфигурации. Ограничивает количество результатов до первых 100 для улучшения производительности.
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"
Поиск всех причин, по которым компьютер не соответствует требованиям для назначений гостевой конфигурации
Отображает все причины назначений гостевой конфигурации для определенного компьютера. Удалите первое предложение where
, чтобы также включить проверки, по итогам которых компьютер соответствует требованиям.
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"
Вывод списка компьютеров и сведений об ожидании ими перезагрузки
Выводит список компьютеров со сведениями о том, ожидают ли они перезагрузки.
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"
Вывод списка незапущенных компьютеров и сведений о соответствии нормативным требованиям по результатам последней проверки
Предоставляет список компьютеров, которые не включены, с назначениями их конфигураций и последним зарегистрированным статусом соответствия.
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"
Запрос деталей отчетов о заданиях гостевой конфигурации
Отображает отчет со сведениями о причине назначения гостевой конфигурации. В следующем примере запрос возвращает только результаты, в которых гостевое назначение имеет имя installed_application_linux
, а выходные данные содержат строку Chrome
, то есть выводит все компьютеры Linux, на которых установлен пакет, имя которого содержит слово 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"
Ресурсы здравоохранения
Количество виртуальных машин по состоянию доступности и идентификатору подписки
Возвращает сведения о количестве виртуальных машин (тип Microsoft.Compute/virtualMachines
), агрегированных по состоянию доступности для каждой из ваших подписок.
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)"
Список виртуальных машин с указанием состояний доступности по идентификаторам ресурсов
Возвращает актуальный список виртуальных машин (тип Microsoft.Compute/virtualMachines
), агрегированных по состоянию доступности. Запрос также предоставляет связанный идентификатор ресурса на основе properties.targetResourceId
, для упрощения отладки и смягчения последствий. Состояния доступности могут иметь одно из четырех значений: "Доступно", "Недоступно", "Снижено" и "Неизвестно". Дополнительные сведения о том, что означают каждое из состояний доступности, см. в разделе Обзор работоспособности ресурсов Azure.
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)"
Список виртуальных машин по состоянию доступности и состоянию электропитания с указанием идентификаторов и групп ресурсов
Возвращает список виртуальных машин (тип Microsoft.Compute/virtualMachines
), агрегированных по состоянию электропитания и состоянию доступности, чтобы дать целостное представление о работоспособности ваших виртуальных машин. Кроме того, запрос предоставляет сведения о группе ресурсов и идентификаторе ресурса, связанного с каждой записью, для получения подробной информации о ресурсах.
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'"
Список недоступных виртуальных машин по идентификаторам ресурсов
Возвращает актуальный список виртуальных машин (тип Microsoft.Compute/virtualMachines
), агрегированных по состоянию доступности. В заполненном списке выделяются только виртуальные машины, состояние доступности которых отличается от "Доступно", чтобы показать вам проблемные состояния виртуальных машин. Когда все ваши виртуальные машины доступны, вы можете ожидать отсутствие результатов.
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)"
Список ресурсов с состояниями доступности, затронутыми незапланированными событиями работоспособности, инициированными платформой
Возвращает последний список виртуальных машин, затронутых незапланированными нарушениями, которые были вызваны неожиданно платформой Azure. Этот запрос возвращает все затронутые виртуальные машины, агрегированные по свойству идентификатора, а также соответствующее состояние доступности и связанные заметки (properties.reason), суммируя конкретные нарушения.
HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| where properties.category == 'Unplanned' and properties.context != 'Customer Initiated'
| project ResourceId = tolower(tostring(properties.targetResourceId)), Annotation = tostring(properties.reason)
| join (
HealthResources
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on ResourceId
| project ResourceId, AvailabilityState, Annotation
az graph query -q "HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | where properties.category == 'Unplanned' and properties.context != 'Customer Initiated' | project ResourceId = tolower(tostring(properties.targetResourceId)), Annotation = tostring(properties.reason) | join (HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on ResourceId | project ResourceId, AvailabilityState, Annotation"
Список недоступных ресурсов с соответствующими сведениями о заметках
Возвращает список виртуальных машин, которые в настоящее время не находятся в состоянии "Доступно", агрегированном по свойству идентификатора. Запрос также показывает фактическое состояние доступности виртуальных машин, а также их связанные сведения, включая причину их недоступности.
HealthResources
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| where properties.availabilityState != 'Available'
| project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
| join (
HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category)) on ResourceId
| project ResourceId, AvailabilityState, Reason, Context, Category
az graph query -q "HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | where properties.availabilityState != 'Available' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState) | join (HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category)) on ResourceId | project ResourceId, AvailabilityState, Reason, Context, Category"
Количество ресурсов в регионе, на которое повлияло нарушение доступности, а также тип влияния
Возвращает количество виртуальных машин, которые в настоящее время не находятся в состоянии "Доступно", агрегированное по свойству идентификатора. В запросе также отображаются соответствующие сведения о расположении и данные аннотации, включая причину, из-за которой виртуальные машины не находились в доступном состоянии.
HealthResources
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| where properties.availabilityState != 'Available'
| project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location
| join (
HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| project ResourceId = tolower(tostring(properties.targetResourceId)), Context = tostring(properties.context), Category = tostring(properties.category), Location = location) on ResourceId
| summarize NumResources = count(ResourceId) by Location, Context, Category
az graph query -q "HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | where properties.availabilityState != 'Available' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location | join (HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | project ResourceId = tolower(tostring(properties.targetResourceId)), Context = tostring(properties.context), Category = tostring(properties.category), Location = location) on ResourceId | summarize NumResources = count(ResourceId) by Location, Context, Category"
Список ресурсов, затронутых определенным событием в области здравоохранения, а также временем воздействия, сведениями о влиянии, состоянием доступности и регионом
Возвращает список виртуальных машин, затронутых VirtualMachineHostRebootedForRepair
заметкой, агрегированной по свойству идентификатора. Запрос также возвращает соответствующее состояние доступности виртуальных машин, время сбоя и сведения о заметках, включая причину воздействия.
HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| where properties.AnnotationName contains 'VirtualMachineHostRebootedForRepair'
| project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category), Location = location, Timestamp = tostring(properties.occurredTime)
| join (
HealthResources
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId
| project ResourceId, Reason, Context, Category, AvailabilityState, Timestamp
az graph query -q "HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | where properties.AnnotationName contains 'VirtualMachineHostRebootedForRepair' | project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category), Location = location, Timestamp = tostring(properties.occuredTime) | join (HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId | project ResourceId, Reason, Context, Category, AvailabilityState, Timestamp"
Список ресурсов, затронутых запланированными событиями в каждом регионе
Возвращает список виртуальных машин, затронутых запланированным обслуживанием или ремонтом, выполняемым платформой Azure, агрегированным по свойству идентификатора. Запрос также возвращает соответствующее состояние доступности виртуальных машин, время нарушений, местоположение и сведения о примечаниях, включая причину воздействия.
HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| where properties.category contains 'Planned'
| project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Location = location, Timestamp = tostring(properties.occuredTime)
| join (
HealthResources
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId
| project ResourceId, Reason, AvailabilityState, Timestamp, Location
az graph query -q "HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | where properties.category contains 'Planned' | project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Location = location, Timestamp = tostring(properties.occuredTime) | join (HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId | project ResourceId, Reason, AvailabilityState, Timestamp, Location"
Список ресурсов, на которые повлияли незапланированные сбои платформы, включая наличие, режимы энергопотребления и расположение.
Возвращает список виртуальных машин, затронутых запланированным обслуживанием или ремонтом, выполняемым платформой Azure, агрегированным по свойству идентификатора. Запрос также показывает соответствующее состояние доступности виртуальных машин, состояние питания и сведения о расположении.
HealthResources
| where type =~ 'microsoft.resourcehealth/resourceannotations'
| where tostring(properties.context) == 'Platform Initiated' and tostring(properties.category) == 'Planned'
| project ResourceId = tolower(properties.targetResourceId), Location = location
| join (
HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| project ResourceId = tolower(properties.targetResourceId), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId
| join (
Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project ResourceId = tolower(id), PowerState = properties.extended.instanceView.powerState.code, Location = location) on ResourceId
| project ResourceId, AvailabilityState, PowerState, Location
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/resourceannotations' | where tostring(properties.context) == 'Platform Initiated' and tostring(properties.category) == 'Planned' | project ResourceId = tolower(properties.targetResourceId), Location = location | join (HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(properties.targetResourceId), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId | join (Resources | where type =~ 'microsoft.compute/virtualmachines' | project ResourceId = tolower(id), PowerState = properties.extended.instanceView.powerState.code, Location = location) on ResourceId | project ResourceId, AvailabilityState, PowerState, Location"
Текущее состояние виртуальных машин в виртуальном экземпляре для SAP
Этот запрос извлекает текущий статус доступности всех виртуальных машин SAP-системы, используя идентификатор системы (SID) виртуального экземпляра для SAP. Замените mySubscriptionId
на идентификатор подписки и замените myResourceId
на идентификатор ресурса виртуального экземпляра для SAP.
Resources
| where subscriptionId == 'mySubscriptionId'
| where type startswith 'microsoft.workloads/sapvirtualinstances/'
| where id startswith 'myResourceId'
| mv-expand d = properties.vmDetails
| project VmId = tolower(d.virtualMachineId)
| join kind = inner (
HealthResources
| where subscriptionId == 'mySubscriptionId'
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| where properties contains 'Microsoft.Compute/virtualMachines'
| extend VmId = tolower(tostring(properties['targetResourceId']))
| extend AvailabilityState = tostring(properties['availabilityState']))
on $left.VmId == $right.VmId
| project VmId, todatetime(properties['occurredTime']), AvailabilityState
| project-rename ['Virtual Machine ID'] = VmId, UTCTimeStamp = properties_occurredTime, ['Availability State'] = AvailabilityState
az graph query -q "Resources | where subscriptionId == 'mySubscriptionId' | where type startswith 'microsoft.workloads/sapvirtualinstances/' | where id startswith 'myResourceId' | mv-expand d = properties.vmDetails | project VmId = tolower(d.virtualMachineId) | join kind = inner (HealthResources | where subscriptionId == 'mySubscriptionId' | where type == 'microsoft.resourcehealth/availabilitystatuses' | where properties contains 'Microsoft.Compute/virtualMachines' | extend VmId = tolower(tostring(properties['targetResourceId'])) | extend AvailabilityState = tostring(properties['availabilityState'])) on \$left.VmId == \$right.VmId | project VmId, todatetime(properties['occurredTime']), AvailabilityState | project-rename ['Virtual Machine ID'] = VmId, UTCTimeStamp = properties_occurredTime, ['Availability State'] = AvailabilityState"
В настоящее время неработоспособные виртуальные машины и аннотации в виртуальном экземпляре для SAP
Этот запрос извлекает список виртуальных машин в системе SAP, которые являются неработоспособными, а также соответствующие аннотации, указанные идентификатором SID виртуального экземпляра для SAP. Замените mySubscriptionId
на идентификатор подписки, а myResourceId
на идентификатор ресурса вашего виртуального экземпляра для SAP.
HealthResources
| where subscriptionId == 'mySubscriptionId'
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| where properties contains 'Microsoft.Compute/virtualMachines'
| extend VmId = tolower(tostring(properties['targetResourceId']))
| extend AvailabilityState = tostring(properties['availabilityState'])
| where AvailabilityState != 'Available'
| project VmId, todatetime(properties['occurredTime']), AvailabilityState
| join kind = inner (
HealthResources
| where subscriptionId == 'mySubscriptionId'
| where type == 'microsoft.resourcehealth/resourceannotations'
| where properties contains 'Microsoft.Compute/virtualMachines'
| extend VmId = tolower(tostring(properties['targetResourceId']))) on $left.VmId == $right.VmId
| join kind = inner (Resources
| where subscriptionId == 'mySubscriptionId'
| where type startswith 'microsoft.workloads/sapvirtualinstances/'
| where id startswith 'myResourceId'
| mv-expand d = properties.vmDetails
| project VmId = tolower(d.virtualMachineId))
on $left.VmId1 == $right.VmId
| extend AnnotationName = tostring(properties['annotationName']), ImpactType = tostring(properties['impactType']), Context = tostring(properties['context']), Summary = tostring(properties['summary']), Reason = tostring(properties['reason']), OccurredTime = todatetime(properties['occurredTime'])
| project VmId, OccurredTime, AvailabilityState, AnnotationName, ImpactType, Context, Summary, Reason
| project-rename ['Virtual Machine ID'] = VmId, ['Time Since Not Available'] = OccurredTime, ['Availability State'] = AvailabilityState, ['Annotation Name'] = AnnotationName, ['Impact Type'] = ImpactType
az graph query -q "HealthResources | where subscriptionId == 'mySubscriptionId' | where type == 'microsoft.resourcehealth/availabilitystatuses' | where properties contains 'Microsoft.Compute/virtualMachines' | extend VmId = tolower(tostring(properties['targetResourceId'])) | extend AvailabilityState = tostring(properties['availabilityState']) | where AvailabilityState != 'Available' | project VmId, todatetime(properties['occurredTime']), AvailabilityState | join kind = inner (HealthResources | where subscriptionId == 'mySubscriptionId' | where type == 'microsoft.resourcehealth/resourceannotations' | where properties contains 'Microsoft.Compute/virtualMachines' | extend VmId = tolower(tostring(properties['targetResourceId']))) on \$left.VmId == \$right.VmId | join kind = inner (Resources | where subscriptionId == 'mySubscriptionId' | where type startswith 'microsoft.workloads/sapvirtualinstances/' | where id startswith 'myResourceId' | mv-expand d = properties.vmDetails | project VmId = tolower(d.virtualMachineId)) on \$left.VmId1 == \$right.VmId | extend AnnotationName = tostring(properties['annotationName']), ImpactType = tostring(properties['impactType']), Context = tostring(properties['context']), Summary = tostring(properties['summary']), Reason = tostring(properties['reason']), OccurredTime = todatetime(properties['occurredTime']) | project VmId, OccurredTime, AvailabilityState, AnnotationName, ImpactType, Context, Summary, Reason | project-rename ['Virtual Machine ID'] = VmId, ['Time Since Not Available'] = OccurredTime, ['Availability State'] = AvailabilityState, ['Annotation Name'] = AnnotationName, ['Impact Type'] = ImpactType"
Изменения ресурсов здравоохранения
Виртуальные машины Azure, затронутые обслуживанием, инициированным Azure
Возвращает список виртуальных машин, затронутых обычными операциями обслуживания, инициированными Azure за последние 14 дней, а также соответствующей причиной влияния.
HealthResourceChanges
| where properties.targetResourceType =~ 'microsoft.resourcehealth/resourceannotations'
| where properties['changes']['properties.category']['newValue'] =~ 'Planned'
| project Id = tostring(split(tolower(properties.targetResourceId), '/providers/microsoft.resourcehealth/resourceannotations')[0]), Reason = properties['changes']['properties.reason']['newValue']
az graph query -q "HealthResourceChanges | where properties.targetResourceType =~ 'microsoft.resourcehealth/resourceannotations' | where properties['changes']['properties.category']['newValue'] =~ 'Planned' | project Id = tostring(split(tolower(properties.targetResourceId), '/providers/microsoft.resourcehealth/resourceannotations')[0]), Reason = properties['changes']['properties.reason']['newValue']"
Изменения в аннотациях к состоянию здоровья за последние 14 дней
Возвращает список всех изменений в заметках о состоянии здоровья за последние 14 дней. Значения NULL указывают на то, что не было обновления этого конкретного поля, связанного с изменением поля Annotation Name
.
healthresourcechanges
| where type == "microsoft.resources/changes"
| where properties.targetResourceType =~ "microsoft.resourcehealth/resourceannotations"
| extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/resourceAnnotations/current')[0]),
Timestamp = todatetime(properties.changeAttributes.timestamp), AnnotationName = properties['changes']['properties.annotationName']['newValue'], Reason = properties['changes']['properties.reason']['newValue'],
Context = properties['changes']['properties.context']['newValue'], Category = properties['changes']['properties.category']['newValue']
| where isnotempty(AnnotationName)
| project Timestamp, Id, PreviousAnnotation = properties['changes']['properties.annotationName']['previousValue'], AnnotationName, Reason, Context, Category
| order by Timestamp desc
az graph query -q "healthresourcechanges | where type == "microsoft.resources/changes" | where properties.targetResourceType =~ "microsoft.resourcehealth/resourceannotations" | extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/resourceAnnotations/current')[0]), Timestamp = todatetime(properties.changeAttributes.timestamp), AnnotationName = properties['changes']['properties.annotationName']['newValue'], Reason = properties['changes']['properties.reason']['newValue'], Context = properties['changes']['properties.context']['newValue'], Category = properties['changes']['properties.category']['newValue'] | where isnotempty(AnnotationName) | project Timestamp, Id, PreviousAnnotation = properties['changes']['properties.annotationName']['previousValue'], AnnotationName, Reason, Context, Category | order by Timestamp desc"
Изменения состояния доступности виртуальной машины за последние 14 дней
Возвращает список всех изменений состояний доступности виртуальной машины за последние 14 дней.
healthresourcechanges
| where type == "microsoft.resources/changes"
| where properties.targetResourceType =~ "microsoft.resourcehealth/availabilityStatuses"
| extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/availabilityStatuses/current')[0]),
Timestamp = todatetime(properties.changeAttributes.timestamp), PreviousAvailabilityState = properties['changes']['properties.availabilityState']['previousValue'],
LatestAvailabilityState = properties['changes']['properties.availabilityState']['newValue']
| where isnotempty(LatestAvailabilityState)
| project Timestamp, Id, PreviousAvailabilityState, LatestAvailabilityState
| order by Timestamp desc
az graph query -q "healthresourcechanges | where type == "microsoft.resources/changes" | where properties.targetResourceType =~ "microsoft.resourcehealth/availabilityStatuses" | extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/availabilityStatuses/current')[0]), Timestamp = todatetime(properties.changeAttributes.timestamp), PreviousAvailabilityState = properties['changes']['properties.availabilityState']['previousValue'], LatestAvailabilityState = properties['changes']['properties.availabilityState']['newValue'] | where isnotempty(LatestAvailabilityState) | project Timestamp, Id, PreviousAvailabilityState, LatestAvailabilityState | order by Timestamp desc"
Изменения работоспособности виртуальных машин и заметок в виртуальном экземпляре для SAP
Этот запрос извлекает исторические изменения в доступности и работоспособности, а также соответствующие заметки всех виртуальных машин SAP-системы, исходя из SID виртуального экземпляра SAP. Замените mySubscriptionId
на идентификатор подписки и myResourceId
на идентификатор ресурса вашего виртуального экземпляра для SAP.
Resources
| where subscriptionId == 'mySubscriptionId'
| where type startswith 'microsoft.workloads/sapvirtualinstances/'
| where id startswith 'myResourceId'
| mv-expand d = properties.vmDetails
| project VmId = tolower(d.virtualMachineId)
| join kind = leftouter (
HealthResourceChanges
| where subscriptionId == 'mySubscriptionId'
| where id !has '/virtualMachineScaleSets/'
| where id has '/virtualMachines/'
| extend timestamp = todatetime(properties.changeAttributes.timestamp)
| extend VmId = tolower(tostring(split(id, '/providers/Microsoft.ResourceHealth/')[0]))
| where properties has 'properties.availabilityState' or properties has 'properties.annotationName'
| extend HealthChangeType = iff(properties has 'properties.availabilityState', 'Availability', 'Annotation')
| extend ChangeType = tostring(properties.changeType)
| where ChangeType == 'Update' or ChangeType == 'Delete')
on $left.VmId == $right.VmId
| extend Changes = parse_json(tostring(properties.changes))
| extend AvailabilityStateJson = parse_json(tostring(Changes['properties.availabilityState']))
| extend AnnotationNameJson = parse_json(tostring(Changes['properties.annotationName']))
| extend AnnotationSummary = parse_json(tostring(Changes['properties.summary']))
| extend AnnotationReason = parse_json(tostring(Changes['properties.reason']))
| extend AnnotationImpactType = parse_json(tostring(Changes['properties.impactType']))
| extend AnnotationContext = parse_json(tostring(Changes['properties.context']))
| extend AnnotationCategory = parse_json(tostring(Changes['properties.category']))
| extend AvailabilityStatePreviousValue = tostring(AvailabilityStateJson.previousValue)
| extend AvailabilityStateCurrentValue = tostring(AvailabilityStateJson.newValue)
| extend AnnotationNamePreviousValue = tostring(AnnotationNameJson.previousValue)
| extend AnnotationNameCurrentValue = tostring(AnnotationNameJson.newValue)
| extend AnnotationSummaryCurrentValue = tostring(AnnotationSummary.newValue)
| extend AnnotationReasonCurrentValue = tostring(AnnotationReason.newValue)
| extend AnnotationImpactTypeCurrentValue = tostring(AnnotationImpactType.newValue)
| extend AnnotationContextCurrentValue = tostring(AnnotationContext.newValue)
| extend AnnotationCategoryCurrentValue = tostring(AnnotationCategory.newValue)
| project id = VmId, timestamp, ChangeType, AvailabilityStateCurrentValue, AnnotationNameCurrentValue, AnnotationSummaryCurrentValue, AnnotationReasonCurrentValue, AnnotationImpactTypeCurrentValue, AnnotationContextCurrentValue, AnnotationCategoryCurrentValue, Changes
| order by id, timestamp asc
| project-rename ['Virtual Machine ID'] = id, UTCTimeStamp = timestamp, ['Change Type'] = ChangeType, ['Availability State'] = AvailabilityStateCurrentValue, ['Summary'] = AnnotationSummaryCurrentValue, ['Reason'] = AnnotationReasonCurrentValue, ['Impact Type'] = AnnotationImpactTypeCurrentValue, Category = AnnotationCategoryCurrentValue, Context = AnnotationContextCurrentValue
az graph query -q "Resources | where subscriptionId == 'mySubscriptionId' | where type startswith 'microsoft.workloads/sapvirtualinstances/' | where id startswith 'myResourceId' | mv-expand d = properties.vmDetails | project VmId = tolower(d.virtualMachineId) | join kind = leftouter (HealthResourceChanges | where subscriptionId == 'mySubscriptionId' | where id !has '/virtualMachineScaleSets/' | where id has '/virtualMachines/' | extend timestamp = todatetime(properties.changeAttributes.timestamp) | extend VmId = tolower(tostring(split(id, '/providers/Microsoft.ResourceHealth/')[0])) | where properties has 'properties.availabilityState' or properties has 'properties.annotationName' | extend HealthChangeType = iff(properties has 'properties.availabilityState', 'Availability', 'Annotation') | extend ChangeType = tostring(properties.changeType) | where ChangeType == 'Update' or ChangeType == 'Delete') on \$left.VmId == \$right.VmId | extend Changes = parse_json(tostring(properties.changes)) | extend AvailabilityStateJson = parse_json(tostring(Changes['properties.availabilityState'])) | extend AnnotationNameJson = parse_json(tostring(Changes['properties.annotationName'])) | extend AnnotationSummary = parse_json(tostring(Changes['properties.summary'])) | extend AnnotationReason = parse_json(tostring(Changes['properties.reason'])) | extend AnnotationImpactType = parse_json(tostring(Changes['properties.impactType'])) | extend AnnotationContext = parse_json(tostring(Changes['properties.context'])) | extend AnnotationCategory = parse_json(tostring(Changes['properties.category'])) | extend AvailabilityStatePreviousValue = tostring(AvailabilityStateJson.previousValue) | extend AvailabilityStateCurrentValue = tostring(AvailabilityStateJson.newValue) | extend AnnotationNamePreviousValue = tostring(AnnotationNameJson.previousValue) | extend AnnotationNameCurrentValue = tostring(AnnotationNameJson.newValue) | extend AnnotationSummaryCurrentValue = tostring(AnnotationSummary.newValue) | extend AnnotationReasonCurrentValue = tostring(AnnotationReason.newValue) | extend AnnotationImpactTypeCurrentValue = tostring(AnnotationImpactType.newValue) | extend AnnotationContextCurrentValue = tostring(AnnotationContext.newValue) | extend AnnotationCategoryCurrentValue = tostring(AnnotationCategory.newValue) | project id = VmId, timestamp, ChangeType, AvailabilityStateCurrentValue, AnnotationNameCurrentValue, AnnotationSummaryCurrentValue, AnnotationReasonCurrentValue, AnnotationImpactTypeCurrentValue, AnnotationContextCurrentValue, AnnotationCategoryCurrentValue, Changes | order by id, timestamp asc | project-rename ['Virtual Machine ID'] = id, UTCTimeStamp = timestamp, ['Change Type'] = ChangeType, ['Availability State'] = AvailabilityStateCurrentValue, ['Summary'] = AnnotationSummaryCurrentValue, ['Reason'] = AnnotationReasonCurrentValue, ['Impact Type'] = AnnotationImpactTypeCurrentValue, Category = AnnotationCategoryCurrentValue, Context = AnnotationContextCurrentValue"
InsightsResources
Список виртуальных машин с сопоставлениями правил сбора данных
В этом запросе перечислены виртуальные машины с ассоциациями правил сбора данных. Для каждой виртуальной машины перечислены правила сбора данных, связанные с ним.
insightsresources
| where type == 'microsoft.insights/datacollectionruleassociations'
| where id contains 'microsoft.compute/virtualmachines/'
| project id = trim_start('/', tolower(id)), properties
| extend idComponents = split(id, '/')
| extend subscription = tolower(tostring(idComponents[1])), resourceGroup = tolower(tostring(idComponents[3])), vmName = tolower(tostring(idComponents[7]))
| extend dcrId = properties['dataCollectionRuleId']
| where isnotnull(dcrId)
| extend dcrId = tostring(dcrId)
| summarize dcrList = make_list(dcrId), dcrCount = count() by subscription, resourceGroup, vmName
| sort by dcrCount desc
az graph query -q "insightsresources | where type == 'microsoft.insights/datacollectionruleassociations' | where id contains 'microsoft.compute/virtualmachines/' | project id = trim_start('/', tolower(id)), properties | extend idComponents = split(id, '/') | extend subscription = tolower(tostring(idComponents[1])), resourceGroup = tolower(tostring(idComponents[3])), vmName = tolower(tostring(idComponents[7])) | extend dcrId = properties['dataCollectionRuleId'] | where isnotnull(dcrId) | extend dcrId = tostring(dcrId) | summarize dcrList = make_list(dcrId), dcrCount = count() by subscription, resourceGroup, vmName | sort by dcrCount desc"
Defender для Интернета вещей
Получить все новые оповещения за последние 30 дней
Этот запрос предоставляет список всех новых оповещений для пользователя за последние 30 дней.
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'"
IotSecurityResources
Подсчет всех датчиков по типу
По этому запросу суммируются все датчики по типу (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)"
Подсчет количества устройств IoT в сети по операционной системе
Этот запрос суммирует все устройства IoT по платформе операционной системы.
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)"
Получите все рекомендации высокой серьезности
По этому запросу предоставляется список всех рекомендаций высокой важности для пользователя.
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'"
Перечисление сайтов с определенным значением тега
По этому запросу выводится список всех сайтов с определенным значением тега.
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'"
Ресурсы конфигурации Kubernetes
Список всех Azure Arc-совместимых кластеров Kubernetes с расширением Azure Monitor.
Возвращает идентификатор подключенного кластера для каждого кластера Kubernetes с поддержкой Azure Arc, в котором установлено расширение Azure Monitor.
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"
Вывод списка всех кластеров Kubernetes с поддержкой Azure Arc без расширения Azure Monitor
Возвращает идентификатор подключенного кластера для каждого кластера Kubernetes с поддержкой Azure Arc, в котором не установлено расширение Azure Monitor.
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"
Список всех ConnectedClusters и ManagedClusters, содержащих конфигурацию Flux
Возвращает идентификаторы connectedCluster и managedCluster для кластеров, содержащих хотя бы одну flux-конфигурацию.
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"
Список всех конфигураций Flux в состоянии несоответствия
Возвращает идентификаторы fluxConfiguration конфигураций, которые не могут синхронизировать ресурсы в кластере.
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"
OrbitalResources
Список предстоящих контактов
Этот запрос помогает клиентам отслеживать все предстоящие контакты, отсортированные по времени начала резервирования.
OrbitalResources
| where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now()
| sort by todatetime(properties.reservationStartTime)
| extend Contact_Profile = tostring(split(properties.contactProfile.id, "/")[-1])
| extend Spacecraft = tostring(split(id, "/")[-3])
| project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Status=properties.status, Provisioning_Status=properties.provisioningState
az graph query -q "OrbitalResources | where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now() | sort by todatetime(properties.reservationStartTime) | extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1]) | extend Spacecraft = tostring(split(id, '/')[-3]) | project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Status=properties.status, Provisioning_Status=properties.provisioningState"
Список последних "x" дней контактов на указанной наземной станции
Этот запрос помогает клиентам отслеживать все последние x
дни контактов, отсортированных по времени начала резервирования для указанной наземной станции. Функция now(-1d)
указывает количество последних дней.
OrbitalResources
| where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now(-1d) and properties.groundStationName == 'Microsoft_Gavle'
| sort by todatetime(properties.reservationStartTime)
| extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1])
| extend Spacecraft = tostring(split(id, '/')[-3])
| project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState
az graph query -q "OrbitalResources | where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now(-1d) and properties.groundStationName == 'Microsoft_Gavle' | sort by todatetime(properties.reservationStartTime) | extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1]) | extend Spacecraft = tostring(split(id, '/')[-3]) | project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState"
Перечислить контакты за последние "x" дней в указанном профиле контактов.
Этот запрос помогает клиентам отслеживать все последние x
дни контактов, отсортированных по времени начала резервирования для указанного профиля контакта. Функция now(-1d)
указывает количество последних дней.
OrbitalResources
| where type == 'microsoft.orbital/spacecrafts/contacts'
| extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1])
| where todatetime(properties.reservationStartTime) >= now(-1d) and Contact_Profile == 'test-CP'
| sort by todatetime(properties.reservationStartTime)
| extend Spacecraft = tostring(split(id, '/')[-3])
| project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState
az graph query -q "OrbitalResources | where type == 'microsoft.orbital/spacecrafts/contacts' | extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1]) | where todatetime(properties.reservationStartTime) >= now(-1d) and Contact_Profile == 'test-CP' | sort by todatetime(properties.reservationStartTime) | extend Spacecraft = tostring(split(id, '/')[-3]) | project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState"
PatchAssessmentResources
Число установленных обновлений ОС
Возвращает список состояний запусков установки обновлений ОС, выполненных на ваших компьютерах за последние 7 дней.
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"
Перечисление доступных обновлений ОС для всех компьютеров, сгруппированных по категории обновлений
Возвращает список обновлений ОС, ожидающих установки на ваших компьютерах.
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"
Список установленных обновлений ОС Linux
Возвращает список статусов установки обновлений ОС Linux Server, выполненных на ваших компьютерах за последние 7 дней.
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"
Список установленных обновлений ОС Windows Server
Возвращает список состояния запуска установки обновлений ОС Windows Server на ваших компьютерах за последние 7 дней.
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"
PolicyResources
Соответствие по назначению политики
Отображает состояние соответствия, процент соответствия и количество ресурсов для каждого назначения Политики 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"
Соответствие по типу ресурса
Отображает состояние соответствия, процент соответствия и число ресурсов для каждого типа ресурса.
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"
Список всех несоответствующих ресурсов
Выводит список ресурсов всех типов, находящихся в состоянии NonCompliant
.
PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| where properties.complianceState == 'NonCompliant'
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | where properties.complianceState == 'NonCompliant'"
Сводка соответствия ресурсов по штатам
Отображает сведения о количестве ресурсов в каждом состоянии соответствия.
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"
Суммирование соответствия ресурсов по штатам для каждого местоположения
Предоставляет информацию о количестве ресурсов в каждом состоянии соответствия требованиям в каждом расположении.
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"
Исключения политик для каждого назначения
Перечисляет количество исключений для каждого назначения.
PolicyResources
| where type == 'microsoft.authorization/policyexemptions'
| summarize count() by tostring(properties.policyAssignmentId)
--management-groups
Используйте параметр с идентификатором группы управления Azure или идентификатором клиента. В этом примере tenantid
переменная сохраняет идентификатор клиента.
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
Исключения политики, срок действия которого истекает в течение 90 дней
Перечисляет имя и дату окончания срока действия.
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"
Контейнеры ресурсов
Объединение результатов из двух запросов в один результат
Следующий запрос использует union
, чтобы получить результаты из таблицы ResourceContainers и добавить их в результаты из таблицы Resources.
ResourceContainers
| where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type | limit 5
| union (Resources | project name, type | limit 5)
az graph query -q "ResourceContainers | where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type | limit 5 | union (Resources | project name, type | limit 5)"
Количество подписок на группу управления
Суммирует количество подписок в каждой группе управления.
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"
Перечислить всех предков групп управления для указанной группы управления
Предоставляет сведения об иерархии той группы управления, что указана в области запроса. В этом примере группа управления имеет название 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
Список всех предков группы управления для указанной подписки
Предоставляет сведения об иерархии группы управления для подписки, указанной в области запроса. В этом примере GUID подписки — 11111111-1111-1111-1111-111111111111.
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
Список всех подписок для указанной группы управления
Предоставляет имя и идентификатор каждой подписки для группы управления, указанной в области запроса. В этом примере группа управления имеет название 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
Перечислить все теги и их значения
В этом запросе приведены теги для групп управления, подписок и ресурсов, а также их значения. Сначала запрос ограничивается ресурсами, содержащими теги isnotempty()
, затем ограничивается полями, среди которых включаются только теги в project
, и mvexpand
и extend
для получения связанных данных из контейнера свойств. Затем он использует union
для объединения результатов из контейнеров ресурсов с аналогичными результатами из ресурсов, обеспечивая широкое покрытие касательно получаемых тегов. Наконец, он ограничивает результаты только сопоставленными данными distinct
, и исключает теги, скрытые системой.
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-""
Удаление столбцов из результатов
Следующий запрос использует summarize
для подсчета ресурсов по подписке, join
— для их объединения с данными о подписке из таблицы ResourceContainers, а затем project-away
— для удаления некоторых столбцов.
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"
Оценка соблюдения мер безопасности для группы управления
Возвращает оценку безопасности для каждой группы управления.
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"
Ресурсы
Объединение результатов из двух запросов в один результат
Следующий запрос использует union
, чтобы получить результаты из таблицы ResourceContainers и добавить их в результаты из таблицы Resources.
ResourceContainers
| where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type | limit 5
| union (Resources | project name, type | limit 5)
az graph query -q "ResourceContainers | where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type | limit 5 | union (Resources | project name, type | limit 5)"
Подсчет ресурсов Azure
Этот запрос возвращает количество ресурсов Azure в доступных вам подписках. Этот запрос также удобно использовать, чтобы проверить, установлены ли в выбранной оболочке соответствующие компоненты Azure Resource Graph и работают ли они.
Resources
| summarize count()
az graph query -q "Resources | summarize count()"
Подсчет ресурсов хранилища ключей
Для подсчета количества возвращаемых записей в этом запросе используется count
вместо summarize
. В подсчет включаются только хранилища ключей.
Resources
| where type =~ 'microsoft.keyvault/vaults'
| count
az graph query -q "Resources | where type =~ 'microsoft.keyvault/vaults' | count"
Количество виртуальных машин по состоянию электропитания
Возвращает количество виртуальных машин (тип Microsoft.Compute/virtualMachines
), классифицированных в соответствии с их состоянием электропитания. Дополнительные сведения о состояниях электропитания см. в статье Общие сведения о состояниях электропитания.
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)"
Подсчет ресурсов с IP-адресами, настроенными посредством подписки
Используя пример запроса "Вывод списка общедоступных IP-адресов" и добавив summarize
и count()
, мы можем получить список ресурсов с настроенными IP-адресами для подписки.
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"
Подсчет виртуальных машин по типу ОС
Основываясь на предыдущем запросе, мы по-прежнему ограничиваем результаты типом ресурса Azure Microsoft.Compute/virtualMachines
, но больше не ограничиваем количество возвращаемых записей. Вместо этого мы использовали summarize
и count()
, чтобы определить способ группирования и объединения значений по свойству (properties.storageProfile.osDisk.osType
в этом примере). Чтобы получить представление о том, как эта строка выглядит в полном объекте, ознакомьтесь с просмотром ресурсов и обнаружением виртуальных машин.
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)"
Подсчет виртуальных машин по типу ОС с расширением
Запрос "Подсчет виртуальных машин по типу ОС" можно составить другим способом, назначив (extend
) свойство и присвоив ему временное имя для использования в запросе, например os. os затем используется в summarize
и count()
, как показано в примере.
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)"
Поиск учетных записей хранения по указанному тегу без учета регистра в группе ресурсов
Выполняется так же, как и запрос на поиск учетных записей хранения по указанному тегу без учета регистра в группе ресурсов. Однако если вам необходимо найти имя и значение тега без учета регистра, используйте mv-expand
с параметром bagexpansion. Этот запрос использует больше квот, чем исходный запрос, поэтому используйте mv-expand
только при необходимости.
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"
Поиск учетных записей хранения по указанному тегу с учетом регистра в группе ресурсов
В приведенном ниже запросе используется внутреннее соединениеjoin
для связывания учетных записей хранения с группами ресурсов, которые имеют указанный чувствительным к регистру тег и значение тега.
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"
Получение количества и процента серверов с поддержкой Arc по доменам
Этот запрос дает сводку по свойству domainName на серверах с поддержкой Azure Arc и создает столбец bin
, рассчитанный по , для отображения процента серверов с поддержкой Arc по доменам.
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)"
Получение сведений о емкости и производительности масштабируемого набора виртуальных машин
Этот запрос выполняет поиск ресурсов масштабируемого набора виртуальных машин и возвращает разные сведения, включая размер виртуальной машины и емкость масштабируемого набора. В запросе используется функция toint()
для приведения значения емкости в число для сортировки. Наконец, столбцы переименовываются в свойства с пользовательскими именами.
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"
Получите виртуальные сети и подсети сетевых интерфейсов
Используйте регулярное выражение parse
для получения имен виртуальной сети и подсети из свойства "ИД ресурса". Хотя parse
позволяет получать данные из сложного поля, доступ к свойствам, если они существуют, лучше всего осуществлять напрямую, а не с помощью 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"
Хранилища ключей с именем подписки
В следующем запросе показано сложное использование join
с kind в качестве leftouter. Запрос ограничивает объединенную таблицу до ресурсов подписки, а project
включает только исходное поле subscriptionId и поле name, переименованное в SubName. Переименование полей позволяет избежать join
, добавляя его как name1, так как поле уже существует в resources. Исходная таблица фильтруется с where
, а следующая project
включает столбцы из обеих таблиц. Результатом запроса являются все хранилища ключей, отображающие тип, имя хранилища ключей и имя подписки, в которой оно находится.
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"
Вывод списка всех кластеров Kubernetes с поддержкой Azure Arc без расширения Azure Monitor
Возвращает идентификатор подключенного кластера для каждого кластера Kubernetes с поддержкой Azure Arc, в котором не установлено расширение Azure Monitor.
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"
Вывод списка всех ресурсов Kubernetes с поддержкой Azure Arc
Возвращает список всех кластеров Kubernetes с поддержкой Azure Arc и соответствующие метаданные для каждого кластера.
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'"
Список всех ConnectedClusters и ManagedClusters, содержащих конфигурацию Flux
Возвращает идентификаторы connectedCluster и managedCluster для кластеров, которые содержат хотя бы одну конфигурацию 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"
Список всех расширений, установленных на виртуальной машине
Сначала этот запрос применяет extend
к типу ресурса виртуальных машин, чтобы получить идентификатор, указанный прописными буквами (toupper()
), имя и тип операционной системы, а также размер виртуальной машины. Получение идентификатора ресурса, указанного прописными буквами, очень удобно при подготовке к объединению с другим свойством. Затем этот запрос использует join
со значением leftouter для параметра kind, чтобы получить список расширений виртуальной машины, сопоставив substring
(в верхнем регистре) идентификатора расширения. Сегмент идентификатора перед строкой "/extensions/<ExtensionName>" имеет тот же формат, что и идентификатор виртуальных машин, поэтому мы используем это свойство для join
. Затем применяется summarize
в сочетании с make_list
для имени расширения виртуальной машины, чтобы объединить в одно свойство массива все имена расширений, у которых совпадают значения ID, OSName, OSType и VMSize. Наконец, мы преобразуем OSName в нижний регистр с помощью order by
asc. По умолчанию order by
использует порядок по убыванию.
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"
Список всех расширений, установленных на сервере с поддержкой Azure Arc
Во-первых, этот запрос использует project
на типе ресурса гибридного компьютера для получения идентификатора в верхнем регистре (toupper()
), а также для получения имени компьютера и операционной системы, работающей на компьютере. Получение идентификатора ресурса, указанного прописными буквами, — хороший способ подготовить join
для работы с другим свойством. Затем запрос использует join
с параметром kind в виде leftouter, чтобы получить список расширений, сопоставив идентификатор расширения в верхнем регистре с substring
. Часть идентификатора перед /extensions/<ExtensionName>
имеет тот же формат, что и идентификатор гибридной виртуальной машины, поэтому мы используем это свойство для join
. Затем summarize
вместе с make_list
применяется для имени расширения виртуальной машины, чтобы объединить в одно свойство массива все имена расширений, у которых совпадают значения id, OSName и ComputerName. Наконец, мы применяем сортировку по возрастанию (asc) для значений OSName в нижнем регистре. По умолчанию order by
использует порядок по убыванию.
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"
Список всех конфигураций Flux в состоянии несоответствия
Возвращает идентификаторы fluxConfiguration конфигураций, которые не могут синхронизировать ресурсы в кластере.
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"
Перечислить все общедоступные IP-адреса
Аналогично примеру "Отображение ресурсов, которые содержат хранилище", этот запрос ищет все ресурсы, тип которых содержит слово publicIPAddresses. Этот запрос изменяет данный шаблон так, чтобы включать в результаты только случаи, где используется properties.ipAddress, возвращать только поле properties.ipAddress, и сортировать результаты по первым 100 в списке. В зависимости от выбранной оболочки может потребоваться экранировать кавычки.
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"
Перечислить все учетные записи хранения с определенным значением тега
Объедините функции фильтра в предыдущем примере и фильтрацию по типу ресурса Azure с помощью свойства type. Этот запрос также ограничивает поиск определенных типов ресурсов Azure за счет использования конкретного имени и значения тега.
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'"
Перечислить все названия тегов
Этот запрос начинается с тега и строит объект JSON, перечисляющий все уникальные имена тегов и их соответствующие типы.
Resources
| project tags
| summarize buildschema(tags)
az graph query -q "Resources | project tags | summarize buildschema(tags)"
Перечислите все теги и их значения
В этом запросе приведены теги для групп управления, подписок и ресурсов, а также их значения. Сначала запрос ограничивается ресурсами с тегами isnotempty()
. Затем ограничивается включаемые поля, оставляя только теги в project
, и используется mvexpand
и extend
, чтобы получить связанные данные из структуры свойств. Затем он использует union
для объединения результатов из ResourceContainers с теми же результатами из Resources, обеспечивая широкий охват полученных тегов. Наконец, он ограничивает результаты для данных, сопоставленных с distinct
, и исключает скрытые системой теги.
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-""
Список серверов с поддержкой Arc, на которых не установлена последняя версия агента
Этот запрос возвращает все серверы с поддержкой Arc, на которых выполняется устаревшая версия агента Connected Machine. Агенты с состоянием Срок действия истек исключаются из результатов. В запросе используется leftouterjoin
для объединения рекомендаций Совета, создаваемых всеми агентами Connected Machine, которые определены как устаревшие, и машинами Hybrid Computer, чтобы отфильтровать всех агентов, которые не обменивались данными с Azure в течение некоторого времени.
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"
Вывод списка настраиваемых расположений с поддержкой Azure Arc и VMware или SCVMM
Выводит список всех настраиваемых расположений с поддержкой Azure Arc, которые поддерживают тип ресурса VMware или SCVMM.
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"
Список экземпляров Azure Cosmos DB с указанием определенных расположений для записи
Следующий запрос ограничивает ресурсы Azure Cosmos DB, использует mv-expand
для расширения пакета свойств для properties.writeLocations, а затем проецирует конкретные поля и ограничивает результаты до значения properties.writeLocations.locationName, совпадающего с "Восточная часть США" или "Западная часть США".
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"
Список затронутых ресурсов при переносе подписки Azure
Возвращает некоторые ресурсы Azure, которые были затронуты при переносе подписки в другой каталог Azure Active Directory (Azure AD). Вам необходимо будет повторно создать некоторые ресурсы, существовавшие до переноса подписки.
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"
Вывод списка незапущенных компьютеров и сведений о соответствии нормативным требованиям по результатам последней проверки
Предоставляет список машин, которые не включены, вместе с их назначениями конфигурации и последним зарегистрированным состоянием соответствия.
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"
Список виртуальных машин по состоянию доступности и состоянию электропитания с указанием идентификаторов и групп ресурсов
Возвращает список виртуальных машин (тип Microsoft.Compute/virtualMachines
), агрегированных по состоянию электропитания и состоянию доступности, чтобы дать целостное представление о работоспособности ваших виртуальных машин. Кроме того, запрос предоставляет сведения о группе ресурсов и идентификаторе ресурса, связанного с каждой записью, для получения подробной информации о ресурсах.
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'"
Список ресурсов, отсортированных по имени
Этот запрос возвращает любой тип ресурса, но только свойства name, type и location. Он использует выражение order by
, чтобы сортировать свойства по свойству name в порядке возрастания (asc
).
Resources
| project name, type, location
| order by name asc
az graph query -q "Resources | project name, type, location | order by name asc"
Список ресурсов с определённым значением тега
Мы можем ограничить результаты не только по типу ресурса Azure, а, например, по тегу. В этом примере мы фильтруем ресурсы Azure по тегу с именем Environment, у которых значение Internal. Чтобы указать теги ресурсов и их значения, добавьте свойство tags для ключевого слова project
.
Resources
| where tags.environment=~'internal'
| project name, tags
az graph query -q "Resources | where tags.environment=~'internal' | project name, tags"
Вывод списка баз данных SQL и их эластичных пулов
В следующем запросе для объединения ресурсов Базы данных SQL и связанных с ними эластичных пулов (если имеются) используется leftouterjoin
.
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"
Вывод списка виртуальных машин с их сетевым интерфейсом и общедоступным IP-адресом
В этом запросе для объединения виртуальных машин, которые созданы с помощью модели развертывания Resource Manager, связанных с ними сетевых интерфейсов и любых общедоступных IP-адресов, связанных с этими сетевыми интерфейсами, используются две команды leftouterjoin
.
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"
Удаление столбцов из результатов
Следующий запрос использует summarize
для подсчета ресурсов по подписке, join
— для их объединения с данными о подписке из таблицы ResourceContainers, а затем project-away
— для удаления некоторых столбцов.
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"
Отображение всех виртуальных машин, упорядоченных по имени в порядке убывания
Чтобы вывести только список виртуальных машин (относящихся к типу Microsoft.Compute/virtualMachines
), в результатах можно применить сопоставление по свойству type. Аналогично предыдущему запросу, desc
изменяет order by
для сортировки по убыванию.
=~
в сопоставлении типа делает Resource Graph нечувствительным к регистру.
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"
Отображение первых пяти виртуальных машин по имени и типу ОС
Этот запрос использует top
для извлечения только пяти соответствующих записей, упорядоченных по имени. Типом ресурса Azure является Microsoft.Compute/virtualMachines
.
project
указывает Azure Resource Graph, какие свойства следует включить.
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"
Отображение типов ресурсов и версий API
Resource Graph в основном использует самую новую не предварительную версию API поставщика ресурсов для получения (GET
) свойств ресурсов во время обновления. В некоторых случаях используемая версия API была переопределена, чтобы предоставить больше текущих или широко используемых свойств в результатах. Следующий запрос содержит сведения о версии API, используемой для сбора свойств каждого типа ресурсов:
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"
Отображение ресурсов, которые содержит хранилище
Вместо явного определения типа для сопоставления этот пример запроса будет искать все ресурсы Azure, содержащие (contains
) слово storage.
Resources
| where type contains 'storage' | distinct type
az graph query -q "Resources | where type contains 'storage' | distinct type"
Отображение несвязанных групп безопасности сети
Этот запрос возвращает группы безопасности сети (NSG), которые не связаны с сетевым интерфейсом или подсетью.
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"
Суммирование виртуальных машин по расширенному свойству состояния питания
Этот запрос использует расширенные свойства на виртуальных машинах для суммирования по состоянию питания.
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)"
Виртуальные машины, сопоставленные по регулярному выражению
Этот запрос выполняет поиск виртуальных машин, которые соответствуют регулярному выражению (известному как регекс).
matches regex @ позволяет определить регулярное выражение для сопоставления, которое равно ^Contoso(.*)[0-9]+$
. Это определение регулярного выражения объясняется следующим образом:
-
^
— Сопоставление должно начаться в начале строки. -
Contoso
— строка, чувствительная к регистру. -
(.*)
— совпадение подэкспрессии:-
.
— Сопоставляется с любым единичным символом (кроме новой строки). -
*
— Соответствует предыдущему элементу ноль или более раз.
-
-
[0-9]
— Совпадение для группы символов, представляющих числа от 0 до 9. -
+
— Сопоставляется с предыдущим элементом один или более раз. -
$
— Сопоставление предыдущего элемента должно осуществляться в конце строки.
После сопоставления по имени запрос отображает имя и сортирует по возрастанию.
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"
Отображение виртуальных машин с общедоступными IP-адресами SKU уровня "Базовый"
Этот запрос возвращает список идентификаторов виртуальных машин с присоединенными общедоступными IP-адресами SKU уровня "Базовый".
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"
Подсчет правил сбора данных Azure Monitor по подписке и группе ресурсов
Этот запрос группирует правила сбора данных Azure Monitor на основании подписки и группы ресурсов.
resources
| where type == 'microsoft.insights/datacollectionrules'
| summarize dcrCount = count() by subscriptionId, resourceGroup, location
| sort by dcrCount desc
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | summarize dcrCount = count() by subscriptionId, resourceGroup, location | sort by dcrCount desc"
Подсчет правил сбора данных Azure Monitor в зависимости от местоположения
Этот запрос группит правила сбора данных Azure Monitor по расположению.
resources
| where type == 'microsoft.insights/datacollectionrules'
| summarize dcrCount=count() by location
| sort by dcrCount desc
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | summarize dcrCount=count() by location | sort by dcrCount desc"
Список правил сбора данных Azure Monitor с рабочей областью Log Analytics в качестве назначения
Получите список рабочих областей Log Analytics, и для каждой области определите правила сбора данных, которые указывают на рабочую область как на одно из мест назначения.
resources
| where type == 'microsoft.insights/datacollectionrules'
| extend destinations = properties['destinations']
| extend logAnalyticsWorkspaces = destinations['logAnalytics']
| where isnotnull(logAnalyticsWorkspaces)
| mv-expand logAnalyticsWorkspace = logAnalyticsWorkspaces
| extend logAnalyticsWorkspaceResourceId = tolower(tostring(logAnalyticsWorkspace['workspaceResourceId']))
| summarize dcrList = make_list(id), dcrCount = count() by logAnalyticsWorkspaceResourceId
| sort by dcrCount desc
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | extend destinations = properties['destinations'] | extend logAnalyticsWorkspaces = destinations['logAnalytics'] | where isnotnull(logAnalyticsWorkspaces) | mv-expand logAnalyticsWorkspace = logAnalyticsWorkspaces | extend logAnalyticsWorkspaceResourceId = tolower(tostring(logAnalyticsWorkspace['workspaceResourceId'])) | summarize dcrList = make_list(id), dcrCount = count() by logAnalyticsWorkspaceResourceId | sort by dcrCount desc"
Перечислите правила сбора данных, использующих метрики Azure Monitor в качестве одного из своих назначений.
В этом запросе перечислены правила сбора данных, использующие метрики Azure Monitor в качестве одного из его назначений.
resources
| where type == 'microsoft.insights/datacollectionrules'
| extend destinations = properties['destinations']
| extend azureMonitorMetrics = destinations['azureMonitorMetrics']
| where isnotnull(azureMonitorMetrics)
| project-away destinations, azureMonitorMetrics
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | extend destinations = properties['destinations'] | extend azureMonitorMetrics = destinations['azureMonitorMetrics'] | where isnotnull(azureMonitorMetrics) | project-away destinations, azureMonitorMetrics"
Оркестрация гибкого масштабируемого набора виртуальных машин
Получение виртуальных машин в режиме гибкой оркестрации масштабируемого набора виртуальных машин, классифицируемых в соответствии с состоянием питания. Эта таблица содержит представление модели и powerState
свойства представления экземпляра для виртуальных машин, входящих в гибкий режим масштабируемого набора виртуальных машин.
Resources
| where type == 'microsoft.compute/virtualmachines'
| extend powerState = tostring(properties.extended.instanceView.powerState.code)
| extend VMSS = tostring(properties.virtualMachineScaleSet.id)
| where isnotempty(VMSS)
| project name, powerState, id
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | extend powerState = tostring(properties.extended.instanceView.powerState.code) | extend VMSS = tostring(properties.virtualMachineScaleSet.id) | where isnotempty(VMSS) | project name, powerState, id"
Ресурсы безопасности
Управляет показателем безопасности по каждой подписке
Возвращает показатель безопасности для каждой подписки.
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"
Подсчет здоровых, нездоровых и неприменимых ресурсов по рекомендации
Возвращает количество работоспособных, неработоспособных и неприменимых ресурсов для каждой рекомендации. Укажите summarize
и count
, чтобы определить способ группирования и объединения значений по свойству.
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)"
Получение всех оповещений Интернета вещей для центра, отфильтрованных по типу
Возвращает все оповещения Интернета вещей для определенного центра (замените заполнитель {hub_id}
) и тип оповещения (замените заполнитель {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}'"
Получение информации о чувствительности определенного ресурса
Возвращает сведения о конфиденциальности определенного ресурса (замените заполнитель {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"
Получить конкретное уведомление IoT
Возвращает конкретное оповещение Интернета вещей по указанному идентификатору системного оповещения (замените заполнитель {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}'"
Перечень результатов оценки уязвимостей реестра контейнеров
Возвращает все уязвимости, обнаруженные в образах контейнеров. Для просмотра этих результатов оценки безопасности необходимо включить Microsoft Defender для контейнеров.
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"
Список рекомендаций Microsoft Defender
Возвращает все оценки Microsoft Defender, упорядоченные в табличном виде с одним полем для каждого свойства.
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"
Представление списка результатов оценок уязвимостей Qualys
Возвращает все уязвимости, обнаруженные на виртуальных машинах, на которых установлен агент 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"
Состояние оценок соответствия нормативным требованиям
Возвращает статус оценок соответствия нормативным требованиям для каждого стандарта и элемента управления.
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"
Состояние соответствия нормативным требованиям для стандарта соответствия
Возвращает статус соблюдения нормативных требований для каждого стандарта соответствия по подписке.
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"
Оценка соблюдения мер безопасности для группы управления
Возвращает оценку соблюдения мер безопасности для группы управления.
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"
Оценка безопасности по подпискам
Возвращает оценку безопасности для подписки.
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"
Показать уровень цен плана Defender для облака по подписке
Возвращает ценовую категорию плана Defender для облака на подписку.
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"
ServiceHealthResources
Влияние активных событий Работоспособности служб на подписки
Предоставляет все активные события работоспособности служб, включая проблемы службы, плановое обслуживание, предупреждения по работоспособности и безопасности, сгруппированные по типам событий, с указанием количества затронутых подписок.
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 = properties.ImpactMitigationTime
| where eventType == 'ServiceIssue' and status == 'Active'
| summarize count(subscriptionId) by name
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 = properties.ImpactMitigationTime | where eventType == 'ServiceIssue' and status == 'Active' | summarize count(subscriptionId) by name"
Все активные события рекомендаций по здоровью
Возвращает все активные события службы здоровья, связанные с рекомендациями по работоспособности, для всех подписок, к которым пользователь имеет доступ.
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 eventType == 'HealthAdvisory' and impactMitigationTime > now()
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 eventType == 'HealthAdvisory' and impactMitigationTime > now()"
Все активные мероприятия планового обслуживания
Возвращает все активные события по состоянию службы в контексте планового обслуживания для всех подписок, к которым имеет доступ пользователь.
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 eventType == 'PlannedMaintenance' and impactMitigationTime > now()
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 eventType == 'PlannedMaintenance' and impactMitigationTime > now()"
Все активные события состояния службы
Возвращает все активные события работоспособности служб для всех подписок, к которым пользователь имеет доступ, включая проблемы службы, плановое обслуживание, уведомления о работоспособности и безопасности.
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 = properties.ImpactMitigationTime
| where (eventType in ('HealthAdvisory', 'SecurityAdvisory', 'PlannedMaintenance') and impactMitigationTime > now()) or (eventType == 'ServiceIssue' and status == 'Active')
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 = properties.ImpactMitigationTime | where (eventType in ('HealthAdvisory', 'SecurityAdvisory', 'PlannedMaintenance') and impactMitigationTime > now()) or (eventType == 'ServiceIssue' and status == 'Active')"
Все активные инциденты с сервисами
Возвращает все активные события Состояния обслуживания, связанные со сбоями служб, для всех подписок, к которым у пользователя есть доступ.
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 = properties.ImpactMitigationTime
| where eventType == 'ServiceIssue' and status == 'Active'
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 = properties.ImpactMitigationTime | where eventType == 'ServiceIssue' and status == 'Active'"
Следующие шаги
- Узнайте больше о языке запросов.
- Узнайте больше о том, как изучать ресурсы.