了解 Azure Resource Graph 查询语言Understanding the Azure Resource Graph query language

Azure Resource Graph 查询语言支持多个运算符和函数。The query language for the Azure Resource Graph supports a number of operators and functions. 每个运算符和函数的工作原理和操作方式基于 Kusto 查询语言 (KQL)Each work and operate based on Kusto Query Language (KQL). 若要了解 Resource Graph 使用的查询语言,请从 KQL 教程开始。To learn about the query language used by Resource Graph, start with the tutorial for KQL.

本文介绍 Resource Graph 支持的语言组件:This article covers the language components supported by Resource Graph:

Resource Graph 表Resource Graph tables

Resource Graph 为其存储的有关 Azure 资源管理器资源类型及其属性的数据提供多个表。Resource Graph provides several tables for the data it stores about Azure Resource Manager resource types and their properties. 这些表可以与 joinunion 运算符一起使用,以从相关资源类型获取属性。These tables can be used with join or union operators to get properties from related resource types. 下面是 Resource Graph 中可用表的列表:Here is the list of tables available in Resource Graph:

Resource Graph 表Resource Graph tables 说明Description
资源Resources 如果未在查询中定义,则为默认表。The default table if none defined in the query. 此处显示了大多数资源管理器资源类型和属性。Most Resource Manager resource types and properties are here.
ResourceContainersResourceContainers 包括订阅(预览版 -- Microsoft.Resources/subscriptions)和资源组 (Microsoft.Resources/subscriptions/resourcegroups) 资源类型和数据。Includes subscription (in preview -- Microsoft.Resources/subscriptions) and resource group (Microsoft.Resources/subscriptions/resourcegroups) resource types and data.
AdvisorResourcesAdvisorResources 包括与 Microsoft.Advisor 相关的资源。Includes resources related to Microsoft.Advisor.
AlertsManagementResourcesAlertsManagementResources 包括与 Microsoft.AlertsManagement 相关的资源。Includes resources related to Microsoft.AlertsManagement.
HealthResourcesHealthResources 包括与 Microsoft.ResourceHealth 相关的资源。Includes resources related to Microsoft.ResourceHealth.
MaintenanceResourcesMaintenanceResources 包括与 Microsoft.Maintenance 相关的资源。Includes resources related to Microsoft.Maintenance.
SecurityResourcesSecurityResources 包括与 Microsoft.Security 相关的资源。Includes resources related to Microsoft.Security.

有关包含资源类型的完整列表,请参阅参考:支持的表和资源类型For a complete list including resource types, see Reference: Supported tables and resource types.

备注

Resources 是默认表。Resources is the default table. 查询 Resources 表时,无需提供表名称,除非使用 joinunionWhile querying the Resources table, it isn't required to provide the table name unless join or union are used. 但是,建议的做法是始终在查询中包含初始表。However, the recommended practice is to always include the initial table in the query.

使用门户中的 Resource Graph 资源管理器来发现每个表中有哪些可用的资源类型。Use Resource Graph Explorer in the portal to discover what resource types are available in each table. 或者,使用查询(如 <tableName> | distinct type)来获取环境中存在的给定 Resource Graph 表所支持的资源类型的列表。As an alternative, use a query such as <tableName> | distinct type to get a list of resource types the given Resource Graph table supports that exist in your environment.

以下查询显示了简单的 join 用法。The following query shows a simple join. 查询结果将列混合在一起,并且联接表中的所有重复列名称(在此示例中为 ResourceContainers)将附加 1。The query result blends the columns together and any duplicate column names from the joined table, ResourceContainers in this example, are appended with 1. 由于 ResourceContainers 表具有订阅和资源组的类型,因此任何类型都可用于联接到 resources 表中的资源。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 的更复杂用法。The following query shows a more complex use of join. 查询将联接表限制为订阅资源并具有 project,以仅包括原始字段 SubscriptionId 和重命名为 SubNamename 字段。The query limits the joined table to subscriptions resources and with project to include only the original field subscriptionId and the name field renamed to SubName. 字段重命名避免了 join 将其添加为 name1,因为该字段已存在于 Resources中。The field rename avoids join adding it as name1 since the field already exists in Resources. 原始表使用 where 进行筛选,以下 project 包括两个表中的列。The original table is filtered with where and the following project includes columns from both tables. 查询结果是单个密钥保管库,其中显示密钥保管库的类型、名称以及其所在的订阅的名称。The query result is a single key vault displaying type, the name of the key vault, and the name of the subscription it's in.

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

备注

限制具有 projectjoin 结果时,join 用于关联两个表的属性(在上述示例中为 subscriptionId)必须包含在 project 中。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.

Resource Graph 自定义语言元素Resource Graph custom language elements

共享查询语法(预览)Shared query syntax (preview)

作为预览功能,共享查询可在 Resource Graph 查询中直接访问。As a preview feature, a shared query can be accessed directly in a Resource Graph query. 在这种情况下,可以创建标准查询作为共享查询并重复使用它们。This scenario makes it possible to create standard queries as shared queries and reuse them. 若要在 Resource Graph 查询中调用共享查询,请使用 {{shared-query-uri}} 语法。To call a shared query inside a Resource Graph query, use the {{shared-query-uri}} syntax. 共享查询的 URI 是该查询的“设置”页上的共享查询的资源 ID。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 OSIn this example, our shared query URI is /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/SharedQueries/providers/Microsoft.ResourceGraph/queries/Count VMs by OS. 此 URI 指向我们想要在另一个查询中引用的共享查询的订阅、资源组和全名。This URI points to the subscription, resource group, and full name of the shared query we want to reference in another query. 此查询与教程:创建和共享查询中创建的查询相同。This query is the same as the one created in Tutorial: Create and share a query.

备注

无法保存将共享查询作为共享查询引用的查询。You can't save a query that references a shared query as a shared query.

示例 1:仅使用共享查询Example 1: Use only the shared query

此 Resource Graph 查询的结果与存储在共享查询中的查询相同。The results of this Resource Graph query are the same as the query stored in the shared query.

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

示例 2:将共享查询并入更大的查询中Example 2: Include the shared query as part of a larger query

此查询首先使用共享查询,然后使用 limit 进一步限制结果。This query first uses the shared query, and then uses limit to further restrict the results.

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

支持的 KQL 语言元素Supported KQL language elements

Resource Graph 支持所有 KQL 数据类型标量函数标量运算符聚合函数Resource Graph supports all KQL data types, scalar functions, scalar operators, and aggregation functions. Resource Graph 支持特定表格运算符,其中一些运算符具有不同的行为。Specific tabular operators are supported by Resource Graph, some of which have different behaviors.

支持的表格/顶级运算符Supported tabular/top level operators

下面是 Resource Graph 支持的 KQL 表格运算符的列表,以及特定示例:Here is the list of KQL tabular operators supported by Resource Graph with specific samples:

KQLKQL Resource Graph 示例查询Resource Graph sample query 说明Notes
计数count 对密钥保管库进行计数Count key vaults
distinctdistinct 显示特定别名的非重复值Show distinct values for a specific alias
extendextend 按 OS 类型对虚拟机进行计数Count virtual machines by OS type
joinjoin 具有订阅名称的密钥保管库Key vault with subscription name 支持的联接类型:inneruniqueinnerleftouterJoin flavors supported: innerunique, inner, leftouter. 单个查询中的 join 限制为 3。Limit of 3 join in a single query. 不允许使用自定义联接策略,如广播联接。Custom join strategies, such as broadcast join, aren't allowed. 可以在单个表中使用,也可以在 Resources 和 ResourceContainers 表中使用。May be used within a single table or between the Resources and ResourceContainers tables.
limitlimit 列出所有公共 IP 地址List all public IP addresses take 的同义词Synonym of take
mvexpandmvexpand 旧运算符,请改用 mv-expandLegacy operator, use mv-expand instead. RowLimit 最大值为 400。RowLimit max of 400. 默认值为 128。The default is 128.
mv-expandmv-expand 列出具有特定写入位置的 Cosmos DBList Cosmos DB with specific write locations RowLimit 最大值:400RowLimit max of 400
orderorder 列出按名称排序的资源List resources sorted by name sort 的同义词Synonym of sort
projectproject 列出按名称排序的资源List resources sorted by name
project-awayproject-away 删除结果中的列Remove columns from results
sortsort 列出按名称排序的资源List resources sorted by name order 的同义词Synonym of order
summarizesummarize 对 Azure 资源进行计数Count Azure resources 仅已简化首页Simplified first page only
taketake 列出所有公共 IP 地址List all public IP addresses limit 的同义词Synonym of limit
返回页首top 按名称及其 OS 类型显示前五个虚拟机Show first five virtual machines by name and their OS type
unionunion 将两个查询的结果合并为单个结果Combine results from two queries into a single result 允许使用单个表:T | union [kind= inner|outer] [withsource=ColumnName] Table。Single table allowed: T | union [kind= inner|outer] [withsource=ColumnName] Table. 单个查询中的 union 分支限制为 3。Limit of 3 union legs in a single query. 不允许对 union 分支表进行模糊解析。Fuzzy resolution of union leg tables isn't allowed. 可以在单个表中使用,也可以在 Resources 和 ResourceContainers 表中使用。May be used within a single table or between the Resources and ResourceContainers tables.
wherewhere 显示包含存储的资源Show resources that contain storage

查询范围Query scope

查询返回的资源的订阅范围取决于访问 Resource Graph 的方法。The scope of the subscriptions from which resources are returned by a query depend on the method of accessing Resource Graph. Azure CLI 和 Azure PowerShell 会根据授权用户的上下文填充要在请求中加入的订阅列表。Azure CLI and Azure PowerShell populate the list of subscriptions to include in the request based on the context of the authorized user. 可以分别使用 subscriptions 和 Subscription 参数为每个订阅手动定义订阅列表 。The list of subscriptions can be manually defined for each with the subscriptions and Subscription parameters, respectively. 在 REST API 和所有其他 SDK 中,包括资源的订阅列表必须显式定义为请求的一部分。In REST API and all other SDKs, the list of subscriptions to include resources from must be explicitly defined as part of the request.

作为预览版,REST API 版本 2020-04-01-preview 会添加一个属性,将查询范围限定到管理组As a preview, REST API version 2020-04-01-preview adds a property to scope the query to a management group. 此预览 API 也使订阅属性成为可选属性。This preview API also makes the subscription property optional. 如果未定义管理组和订阅列表,则查询范围是经过身份验证的用户可以访问的所有资源。If neither the management group or subscription list are defined, the query scope is all resources the authenticated user can access. 新的 managementGroupId 属性采用管理组 ID,该 ID 不同于管理组的名称。The new managementGroupId property takes the management group ID, which is different from the name of the management group. 指定 managementGroupId 时,将包含在指定管理组层次结构中或其下的前 5000 个订阅的资源。When managementGroupId is specified, resources from the first 5000 subscriptions in or under the specified management group hierarchy are included. managementGroupIdsubscriptions 不能同时使用。managementGroupId can't be used at the same time as subscriptions.

示例:使用 ID“myMG”查询管理组层次结构中名为“我的管理组”的所有资源。Example: Query all resources within the hierarchy of the management group named 'My Management Group' with ID 'myMG'.

  • REST API URIREST API URI

    POST https://management.chinacloudapi.cn/providers/Microsoft.ResourceGraph/resources?api-version=2020-04-01-preview
    
  • 请求正文Request Body

    {
        "query": "Resources | summarize count()",
        "managementGroupId": "myMG"
    }
    

转义字符Escape characters

某些属性名称(例如,包含 .$ 的名称)必须在查询中进行包装或转义,否则属性名称将被错误解释,并且不会提供预期结果。Some property names, such as those that include a . or $, must be wrapped or escaped in the query or the property name is interpreted incorrectly and doesn't provide the expected results.

  • . - 包装属性名称,如下所示:['propertyname.withaperiod']. - Wrap the property name as such: ['propertyname.withaperiod']

    用于包装属性 odata.type 的示例查询:Example query that wraps the property odata.type:

    where type=~'Microsoft.Insights/alertRules' | project name, properties.condition.['odata.type']
    
  • $ - 转义属性名称中的字符。$ - Escape the character in the property name. 使用的转义字符取决于运行 Resource Graph 的 shell。The escape character used depends on the shell Resource Graph is run from.

    • bash - \bash - \

      用于在 bash 中转义属性 $type 的示例查询:Example query that escapes the property $type in bash:

      where type=~'Microsoft.Insights/alertRules' | project name, properties.condition.\$type
      
    • cmd - 不要转义 $ 字符。cmd - Don't escape the $ character.

    • PowerShell - `PowerShell - `

      用于在 PowerShell 中转义属性 $type 的示例查询:Example query that escapes the property $type in PowerShell:

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

后续步骤Next steps