Поделиться через


Примеры запросов Azure Resource Graph для Azure Arc

Эта страница представляет собой коллекцию примеров запросов Azure Resource Graph для Azure Arc.

Подсказка

Вы можете использовать Microsoft Copilot в Azure (предварительная версия) для создания запросов Azure Resource Graph с помощью естественного языка. Дополнительные сведения см. в статье "Получение сведений о ресурсах с помощью Microsoft Copilot в Azure".

Общие примеры запросов Arc

Получение доступных типов ресурсов для настраиваемых расположений с поддержкой 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"

Примеры запросов серверов с поддержкой Arc

Получение количества и процента серверов с поддержкой Arc по доменам

Этот запрос суммирует domainName свойство на серверах с поддержкой Azure Arc и с помощью вычислений создаёт Pct столбец для процента серверов с поддержкой 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)"

Список всех расширений, установленных на сервере с поддержкой Azure Arc

Во-первых, этот запрос использует project на типе ресурса гибридного компьютера для получения идентификатора в верхнем регистре (toupper()), а также для получения имени компьютера и операционной системы, работающей на компьютере. Получение идентификатора ресурса, указанного прописными буквами, — хороший способ подготовить join для работы с другим свойством. Затем запрос использует join с kind в качестве leftouter для получения расширений путем сопоставления заглавной буквы substring ID расширения. Часть идентификатора перед /extensions/<ExtensionName> имеет тот же формат, что и идентификатор гибридной виртуальной машины, поэтому мы используем это свойство для join. summarize Затем используется с make_list именем расширения виртуальной машины для объединения имени каждого расширения, где идентификатор, OSName и ComputerName совпадают с одним свойством массива. Наконец, мы упорядочим по нижнему регистру OSName с asc. По умолчанию 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"

Список серверов с поддержкой Arc, которые не используют самую последнюю версию агента.

Этот запрос возвращает все серверы с поддержкой Arc, на которых выполняется устаревшая версия агента Connected Machine. Агенты с состоянием Срок действия истек исключаются из результатов. Запрос использует leftouterjoin, чтобы объединить рекомендации, вынесенные в отношении любых агентов подключенных машин, определённых устаревшими, и гибридных компьютеров, чтобы отфильтровать любого агента, который не взаимодействовал с 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"

Примеры запросов Kubernetes с поддержкой Arc

Перечислить все ресурсы 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'"

Перечислите все кластеры Kubernetes под управлением Azure Arc с расширением 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"

Список всех кластеров, содержащих конфигурацию 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"

Перечислите все конфигурации 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"

Следующие шаги