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


Общие сведения о языке запросов графика ресурсов Azure

Язык запросов для Azure Resource Graph поддерживает множество операторов и функций. Каждый из них работает так же, как элементы языка запросов Kusto (KQL). Чтобы ознакомиться с языком запросов, используемом в Resource Graph, начните с учебника по KQL.

В этой статье рассматриваются компоненты языка, поддерживаемые Resource Graph:

Таблицы Resource Graph

Resource Graph предоставляет несколько таблиц для хранения данных по типам ресурсов Azure Resource Manager и их свойствам. Таблицы Resource Graph можно использовать с оператором join для получения свойств из связанных типов ресурсов.

Таблицы Graph ресурсов поддерживают join вкусы:

Таблица Resource Graph Может ли join к другим таблицам? Description
AdvisorResources Yes Includes resources related to Microsoft.Advisor.
AlertsManagementResources Yes Includes resources related to Microsoft.AlertsManagement.
AppServiceResources Yes Includes resources related to Microsoft.Web.
AuthorizationResources Yes Includes resources related to Microsoft.Authorization.
AWSResources Yes Includes resources related to Microsoft.AwsConnector.
AzureBusinessContinuityResources Yes Includes resources related to Microsoft.AzureBusinessContinuity.
ChaosResources Yes Includes resources related to Microsoft.Chaos.
CommunityGalleryResources Yes Includes resources related to Microsoft.Compute.
ComputeResources Yes Включает ресурсы, связанные с Microsoft.Compute Масштабируемые наборы виртуальных машин.
DesktopVirtualizationResources Yes Includes resources related to Microsoft.DesktopVirtualization.
DnsResources Yes Includes resources related to Microsoft.Network.
EdgeOrderResources Yes Includes resources related to Microsoft.EdgeOrder.
ElasticsanResources Yes Includes resources related to Microsoft.ElasticSan.
ExtendedLocationResources Yes Includes resources related to Microsoft.ExtendedLocation.
FeatureResources Yes Includes resources related to Microsoft.Features.
GuestConfigurationResources Yes Includes resources related to Microsoft.GuestConfiguration.
HealthResourceChanges Yes Includes resources related to Microsoft.Resources.
HealthResources Yes Includes resources related to Microsoft.ResourceHealth.
InsightsResources Yes Includes resources related to Microsoft.Insights.
IoTSecurityResources Yes Includes resources related to Microsoft.IoTSecurity and Microsoft.IoTFirmwareDefense.
KubernetesConfigurationResources Yes Includes resources related to Microsoft.KubernetesConfiguration.
KustoResources Yes Includes resources related to Microsoft.Kusto.
MaintenanceResources Yes Includes resources related to Microsoft.Maintenance.
ManagedServicesResources Yes Includes resources related to Microsoft.ManagedServices.
MigrateResources Yes Includes resources related to Microsoft.OffAzure.
NetworkResources Yes Includes resources related to Microsoft.Network.
PatchAssessmentResources Yes Includes resources related to Azure Virtual Machines patch assessment Microsoft.Compute and Microsoft.HybridCompute.
PatchInstallationResources Yes Includes resources related to Azure Virtual Machines patch installation Microsoft.Compute and Microsoft.HybridCompute.
PolicyResources Yes Includes resources related to Microsoft.PolicyInsights.
RecoveryServicesResources Yes Includes resources related to Microsoft.DataProtection and Microsoft.RecoveryServices.
ResourceChanges Yes Includes resources related to Microsoft.Resources.
ResourceContainerChanges Yes Includes resources related to Microsoft.Resources.
ResourceContainers Yes Включает типы ресурсов и данные группы управления (Microsoft.Management/managementGroups), подписки (Microsoft.Resources/subscriptions) и группы ресурсов (Microsoft.Resources/subscriptions/resourcegroups).
Resources Yes Таблица по умолчанию, если таблица не определена в запросе. В ней содержится большинство типов ресурсов Resource Manager и их свойств.
SecurityResources Yes Includes resources related to Microsoft.Security.
ServiceFabricResources Yes Includes resources related to Microsoft.ServiceFabric.
ServiceHealthResources Yes Includes resources related to Microsoft.ResourceHealth/events.
SpotResources Yes Includes resources related to Microsoft.Compute.
SupportResources Yes Includes resources related to Microsoft.Support.
TagsResources Yes Includes resources related to Microsoft.Resources/tagnamespaces.

Список таблиц, включающих типы ресурсов, перейдите в таблицу Azure Resource Graph и ссылку на тип ресурса.

Note

Resources — это таблица по умолчанию. При запросе Resources таблицы не требуется указать имя таблицы, если join не используется или union не используется. Но рекомендуется всегда включать начальную таблицу в запрос.

Чтобы узнать, какие типы ресурсов доступны в каждой таблице, используйте обозреватель Resource Graph на портале. В качестве альтернативы можно использовать такой запрос, как <tableName> | distinct type, чтобы получить список имеющихся в среде типов ресурсов, которые поддерживаются данной таблицей Resource Graph.

В приведенном ниже запросе показана простая операция join. The query result blends the columns together and any duplicate column names from the joined table, ResourceContainers in this example, are appended with 1. As ResourceContainers table has types for both subscriptions and resource groups, either type might be used to join to the resource from Resources table.

Resources
| join ResourceContainers on subscriptionId
| limit 1

В приведенном ниже запросе показано более сложное использование join. Во-первых, запрос используется project для получения полей из Resources типа ресурса Хранилища ключей Azure. The next step uses join to merge the results with ResourceContainers where the type is a subscription on a property that is both in the first table's project and the joined table's project. The field rename avoids join adding it as name1 since the property already is projected from Resources. Результатом запроса является хранилище ключей, которое представляет тип, название, местоположение и группу ресурсов хранилища, а также название подписки.

Resources
| where type == 'microsoft.keyvault/vaults'
| project name, type, location, subscriptionId, resourceGroup
| join (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId
| project type, name, location, resourceGroup, SubName
| limit 1

Note

When limiting the join results with project, the property used by join to relate the two tables, subscriptionId in the above example, must be included in project.

Extended properties

As a preview feature, some of the resource types in Resource Graph have more type-related properties available to query beyond the properties provided by Azure Resource Manager. This set of values, known as extended properties, exists on a supported resource type in properties.extended. To show resource types with extended properties, use the following query:

Resources
| where isnotnull(properties.extended)
| distinct type
| order by type asc

Пример: получить количество виртуальных машин по instanceView.powerState.code:

Resources
| where type == 'microsoft.compute/virtualmachines'
| summarize count() by tostring(properties.extended.instanceView.powerState.code)

пользовательские элементы языка Resource Graph

Синтаксис общего запроса (Предварительная версия)

As a preview feature, a shared query can be accessed directly in a Resource Graph query. Этот сценарий позволяет создавать стандартные запросы в виде общих и использовать их повторно. Чтобы вызвать общий запрос в рамках запроса Resource Graph, используйте синтаксис {{shared-query-uri}}. The URI of the shared query is the Resource ID of the shared query on the Settings page for that query. В этом примере наш URI общего запроса — /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/SharedQueries/providers/Microsoft.ResourceGraph/queries/Count VMs by OS. Этот URI указывает на подписку, группу ресурсов и полное имя общего запроса, на который мы хотим ссылаться в другом запросе. Этот запрос совпадает с запросом, который был создан в Руководстве по созданию запроса и предоставлению общего доступа к нему.

Note

Нельзя сохранить запрос, который ссылается на общий запрос в виде общего запроса.

Пример 1. Используйте только общий запрос:

Результаты этого запроса Resource Graph совпадают с результатами запроса, хранящегося в общем запросе.

{{/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/SharedQueries/providers/Microsoft.ResourceGraph/queries/Count VMs by OS}}

Пример 2. Включение общего запроса в состав более крупного запроса:

Сначала этот запрос использует общий запрос, а затем использует limit для ограничения результатов.

{{/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/SharedQueries/providers/Microsoft.ResourceGraph/queries/Count VMs by OS}}
| where properties_storageProfile_osDisk_osType =~ 'Windows'

Поддерживаемые элементы языка KQL

Resource Graph supports a subset of KQL data types, scalar functions, scalar operators, and aggregation functions. Specific tabular operators are supported by Resource Graph, some of which have different behaviors.

Поддерживаемые табличные операторы и операторы верхнего уровня

Ниже приведен список табличных операторов KQL, поддерживаемых Resource Graph с определенными примерами:

KQL Пример запроса Resource Graph Notes
count Число хранилищ ключей
distinct Отображение ресурсов, которые содержат хранилище
extend Подсчет виртуальных машин по типу ОС
join Хранилище ключей с именем подписки Join flavors supported: innerunique, inner, leftouter, and fullouter. Ограничение на три операции с join или union (или их комбинацию) в одном запросе, считающиеся вместе, при этом одна из них может быть перекрестным соединением таблиц. If all cross-table join use is between Resource and ResourceContainers, then three cross-table join are allowed. Пользовательские стратегии соединения, такие как широковещательное соединение, не допускаются. Для каких таблиц можно использовать join, перейдите к таблицам Resource Graph.
limit Вывод списка общедоступных IP-адресов Синоним take. Doesn't work with Skip.
mvexpand Устаревший оператор, используйте вместо него mv-expand. RowLimit max of 2,000. Значение по умолчанию — 128.
mv-expand Вывод списка Azure Cosmos DB с определенными расположениями записи RowLimit max of 2,000. Значение по умолчанию — 128. Не более 3 mv-expand в одном запросе.
order Вывод списка ресурсов, отсортированных по имени Синоним sort
parse Получение виртуальных сетей и подсетей сетевых интерфейсов Доступ к свойствам рекомендуется осуществлять напрямую, если они существуют, а не с помощью parse.
project Вывод списка ресурсов, отсортированных по имени
project-away Удаление столбцов из результатов
sort Вывод списка ресурсов, отсортированных по имени Синоним order
summarize Подсчет ресурсов Azure Только первая упрощенная страница
take Вывод списка общедоступных IP-адресов Синоним limit. Doesn't work with Skip.
top Отображение первых пяти виртуальных машин по имени и типу ОС
union Объединение результатов из двух запросов в один результат Разрешена одна таблица: | union [kind= inner|outer] [withsource=ColumnName] Table. Ограничение на три union ноги в одном запросе. Нечеткое разрешение таблиц разветвлений union не допускается. Might be used within a single table or between the Resources and ResourceContainers tables.
where Отображение ресурсов, которые содержат хранилище

Ограничение по умолчанию — три join и три mv-expand оператора в одном запросе пакета SDK для Resource Graph. Чтобы увеличить эти ограничения для своего клиента, выберите Справка + поддержка.

To support the Open Query portal experience, Azure Resource Graph Explorer has a higher global limit than Resource Graph SDK.

Note

Вы не можете ссылаться на таблицу в виде правой таблицы несколько раз, что превышает ограничение 1. При этом вы получите ошибку с кодом DisallowedMaxNumberOfRemoteTables.

Query scope

The scope of the subscriptions or management groups from which resources are returned by a query defaults to a list of subscriptions based on the context of the authorized user. If a management group or a subscription list isn't defined, the query scope is all resources, and includes Azure Lighthouse delegated resources.

Список подписок или групп управления для запроса может быть определен вручную для изменения области результатов. Например, свойство managementGroups REST API принимает идентификатор группы управления, который отличается от названия группы управления. При managementGroups указании включены ресурсы из первых 10 000 подписок в указанной иерархии групп управления или в ней. managementGroups нельзя использовать в то же время, что и subscriptions.

Пример. Запрос всех ресурсов в иерархии группы управления с My Management Group идентификатором myMG.

  • Универсальный код ресурса (URI) REST API

    POST https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=2021-03-01
    
  • Request Body

    {
      "query": "Resources | summarize count()",
      "managementGroups": ["myMG"]
    }
    

Этот AuthorizationScopeFilter параметр позволяет перечислять Политика Azure назначения и назначения ролей на основе ролей Azure (Azure RBAC) в AuthorizationResources таблице, унаследованной от верхних областей. Параметр AuthorizationScopeFilter принимает следующие значения для PolicyResources таблиц и AuthorizationResources таблиц:

  • AtScopeAndBelow (default if not specified): Returns assignments for the given scope and all child scopes.
  • AtScopeAndAbove: Returns assignments for the given scope and all parent scopes, but not child scopes.
  • AtScopeAboveAndBelow: Returns assignments for the given scope, all parent scopes, and all child scopes.
  • AtScopeExact: Returns assignments only for the given scope; no parent or child scopes are included.

Note

To use the AuthorizationScopeFilter parameter, be sure to use the 2021-06-01-preview or later API version in your requests.

Example: Get all policy assignments at the myMG management group and Tenant Root (parent) scopes.

  • Универсальный код ресурса (URI) REST API

    POST https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=2021-06-01-preview
    
  • Пример текста запроса

    {
      "options": {
        "authorizationScopeFilter": "AtScopeAndAbove"
      },
      "query": "PolicyResources | where type =~ 'Microsoft.Authorization/PolicyAssignments'",
      "managementGroups": ["myMG"]
    }
    

Example: Get all policy assignments at the mySubscriptionId subscription, management group, and Tenant Root scopes.

  • Универсальный код ресурса (URI) REST API

    POST https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=2021-06-01-preview
    
  • Пример текста запроса

    {
      "options": {
        "authorizationScopeFilter": "AtScopeAndAbove"
      },
      "query": "PolicyResources | where type =~ 'Microsoft.Authorization/PolicyAssignments'",
      "subscriptions": ["mySubscriptionId"]
    }
    

Escape characters

Некоторые имена свойств, например включающие в себя . или $, должны заключаться в оболочку или экранироваться в запросе, иначе они будут интерпретироваться неправильно и давать непредвиденные результаты.

  • Точка (.): заключите имя ['propertyname.withaperiod'] свойства с помощью квадратных скобок.

    Example query that wraps the property odata.type:

    where type=~'Microsoft.Insights/alertRules' | project name, properties.condition.['odata.type']
    
  • Знак доллара ($): экранируйте символ в имени свойства. Используемый escape-символ зависит от оболочки, которая запускает Resource Graph.

    • Bash: Use a backslash (\) as the escape character.

      Example query that escapes the property $type in Bash:

      where type=~'Microsoft.Insights/alertRules' | project name, properties.condition.\$type
      
    • cmd: Don't escape the dollar sign ($) character.

    • PowerShell: Use a backtick (`) as the escape character.

      Example query that escapes the property $type in PowerShell:

      where type=~'Microsoft.Insights/alertRules' | project name, properties.condition.`$type
      

Next steps