初学者 Resource Graph 查询示例Starter Resource Graph query samples

了解使用 Azure 资源图表进行查询的第一步是对查询语言有基本的了解。The first step to understanding queries with Azure Resource Graph is a basic understanding of the Query Language. 如果还不熟悉 Kusto 查询语言 (KQL),建议查看 KQL 的教程,了解如何撰写所需资源的请求。If you aren't already familiar with Kusto Query Language (KQL), it's recommended to review the tutorial for KQL to understand how to compose requests for the resources you're looking for.

我们将逐步介绍以下初学者查询:We'll walk through the following starter queries:

如果没有 Azure 订阅,请在开始前创建一个试用版订阅If you don't have an Azure subscription, create a trial subscription before you begin.

语言支持Language support

Azure CLI(通过扩展)和 Azure PowerShell(通过模块)支持 Azure 资源图表。Azure CLI (through an extension) and Azure PowerShell (through a module) support Azure Resource Graph. 在运行以下任何查询之前,请检查环境是否已准备就绪。Before running any of the following queries, check that your environment is ready. 有关安装和验证所选 shell 环境的步骤,请参阅 Azure CLIAzure PowerShellSee Azure CLI and Azure PowerShell for steps to install and validate your shell environment of choice.

对 Azure 资源进行计数Count Azure resources

此查询返回有权访问的订阅中存在的 Azure 资源的数量。This query returns number of Azure resources that exist in the subscriptions that you have access to. 这是一个良好查询,用于验证所选 shell 是否已安装适当的 Azure 资源图表组件并处于正常工作状态。It's also a good query to validate your shell of choice has the appropriate Azure Resource Graph components installed and in working order.

Resources
| summarize count()
az graph query -q "Resources | summarize count()"

统计 Key Vault 资源Count Key Vault resources

此查询使用 count 而不是 summarize 来计算返回的记录数。This query uses count instead of summarize to count the number of records returned. 只有密钥保管库才包括在计数中。Only key vaults are included in the count.

Resources
| where type =~ 'microsoft.keyvault/vaults'
| count
az graph query -q "Resources | where type =~ 'microsoft.keyvault/vaults' | count"

列出按名称排序的资源List resources sorted by name

此查询返回任意类型的资源,但只返回“名称”、“类型”和“位置”属性。This query returns any type of resource, but only the name, type, and location properties. 它使用 order by以升序 (asc) 按“名称”属性对属性排序。It uses order by to sort the properties by the name property in ascending (asc) order.

Resources
| project name, type, location
| order by name asc
az graph query -q "Resources | project name, type, location | order by name asc"

按降序显示按名称排序的所有虚拟机Show all virtual machines ordered by name in descending order

若要只列出虚拟机(类型为 Microsoft.Compute/virtualMachines),我们可在结果中匹配属性“类型”。To list only virtual machines (which are type Microsoft.Compute/virtualMachines), we can match the property type in the results. 与上一查询类似,descorder by 更改为降序。Similar to the previous query, desc changes the order by to be descending. 类型匹配中的 =~ 告知资源图表不区分大小写。The =~ in the type match tells Resource Graph to be case insensitive.

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"

按名称及其 OS 类型显示前五个虚拟机Show first five virtual machines by name and their OS type

此查询将使用 top 仅检索按名称排序的五条匹配记录。This query will use top to only retrieve five matching records that are ordered by name. Azure 资源的类型为 Microsoft.Compute/virtualMachinesThe type of the Azure resource is Microsoft.Compute/virtualMachines. project 告诉 Azure 资源图表要包含哪些属性。project tells Azure Resource Graph which properties to include.

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"

按 OS 类型对虚拟机进行计数Count virtual machines by OS type

基于前面的查询,我们仍受限于类型 Microsoft.Compute/virtualMachines 的 Azure 资源,但不再限制返回的记录数量。Building on the previous query, we're still limiting by Azure resources of type Microsoft.Compute/virtualMachines, but are no longer limiting the number of records returned. 相反,我们使用 summarizecount() 来定义如何按属性对值进行分组和聚合,在此示例中为 properties.storageProfile.osDisk.osTypeInstead, we used summarize and count() to define how to group and aggregate the values by property, which in this example is properties.storageProfile.osDisk.osType. 有关此字符串在完整对象中的外观示例,请参阅浏览资源 - 虚拟机发现For an example of how this string looks in the full object, see explore resources - virtual machine discovery.

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。A different way to write the same query is to extend a property and give it a temporary name for use within the query, in this case os. os 然后由 summarizecount() 使用,如上例所示。os is then used by summarize and count() as in the previous example.

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)"

备注

请注意,虽然 =~ 允许不区分大小写的匹配,但在查询中使用属性(例如 properties.storageProfile.osDisk.osType)要求大小写正确。Be aware that while =~ allows case insensitive matching, use of properties (such as properties.storageProfile.osDisk.osType) in the query require the case to be correct. 如果属性的大小写不正确,则会返回 null 值或不正确值,但分组或汇总可能不正确。If the property is the incorrect case, a null or incorrect value is returned and the grouping or summarization would be incorrect.

显示包含存储的资源Show resources that contain storage

此示例查询不显式定义要匹配的类型,而是查找 contains 单词“存储”的任何 Azure 资源。Instead of explicitly defining the type to match, this example query will find any Azure resource that contains the word storage.

Resources
| where type contains 'storage' | distinct type
az graph query -q "Resources | where type contains 'storage' | distinct type"

列出所有公共 IP 地址List all public IP addresses

与上一查询类似,查找包含单词“publicIPAddresses”的所有类型。Similar to the previous query, find everything that is a type with the word publicIPAddresses. 此查询扩展了该模式,以仅包括 properties.ipAddress 为 isnotempty 的结果,仅返回 properties.ipAddress,并将结果limit为前 100 名 This query expands on that pattern to only include results where properties.ipAddress isnotempty, to only return the properties.ipAddress, and to limit the results by the top 100. 根据所选 shell,可能需要转义引号。You may need to escape the quotes depending on your chosen shell.

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"

对具有由订阅配置的 IP 地址的资源进行计数Count resources that have IP addresses configured by subscription

使用前面的示例查询并添加 summarizecount(),我们可通过订阅配置了 IP 地址的资源来获取列表。Using the previous example query and adding summarize and count(), we can get a list by subscription of resources with configured IP addresses.

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"

列出具有特定标记值的资源List resources with a specific tag value

我们可通过 Azure 资源类型以外的属性(如标记)来限制结果。We can limit the results by properties other than the Azure resource type, such as a tag. 在此示例中,我们正在筛选 Azure 资源,其标记名为“环境”,其值为 Internal 。In this example, we're filtering for Azure resources with a tag name of Environment that have a value of Internal.

Resources
| where tags.environment=~'internal'
| project name
az graph query -q "Resources | where tags.environment=~'internal' | project name"

如果还要提供资源具有的标记及其值,请将属性“标记”添加到 project 关键字。To also provide what tags the resource has and their values, add the property tags to the project keyword.

Resources
| where tags.environment=~'internal'
| project name, tags
az graph query -q "Resources | where tags.environment=~'internal' | project name, tags"

列出具有特定标记值的所有存储帐户List all storage accounts with specific tag value

组合前面示例的筛选功能,按“类型”属性筛选 Azure 资源类型。Combine the filter functionality of the previous example and filter Azure resource type by type property. 此查询还使用特定的标记名称和值来限制对 Azure 资源特定类型的搜索。This query also limits our search for specific types of Azure resources with a specific tag name and value.

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'"

备注

此示例使用 == 进行匹配,而不是使用 =~ 条件。This example uses == for matching instead of the =~ conditional. == 是区分大小写的匹配项。== is a case sensitive match.

列出所有标记及其值List all tags and their values

此查询会列出管理组、订阅和资源上的标记及其值。This query lists tags on management groups, subscriptions, and resources along with their values. 查询首先仅查找带有 isnotempty() 标记的资源,通过仅包含 projectmvexpandextend 中的标记来限制所包含的字段,从而获取属性包中配对的数据。The query first limits to resources where tags isnotempty(), limits the included fields by only including tags in the project, and mvexpand and extend to get the paired data from the property bag. 然后,它使用 union 将 ResourceContainers 中的结果合并到资源中的相同结果,从而广泛覆盖要提取的标记 。It then uses union to combine the results from ResourceContainers to the same results from Resources, giving broad coverage to which tags are fetched. 最后,它将结果限制为 distinct 配对数据,并排除系统隐藏的标记。Last, it limits the results to distinct paired data and excludes system-hidden tags.

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 notempty(tags) | project tags | mvexpand tags | extend tagKey = tostring(bag_keys(tags)[0]) | extend tagValue = tostring(tags[tagKey]) ) | distinct tagKey, tagValue | where tagKey !startswith "hidden-""

显示未关联的网络安全组Show unassociated network security groups

此查询返回未与网络接口或子网关联的网络安全组 (NSG)。This query returns Network Security Groups (NSGs) that aren't associated to a network interface or subnet.

Resources
| where type =~ "microsoft.network/networksecuritygroups" and isnull(properties.networkInterfaces) and isnull(properties.subnets)
| project name, resourceGroup
| sort by name asc
az graph query -q "Resources | where type =~ 'microsoft.network/networksecuritygroups' and isnull(properties.networkInterfaces) and isnull(properties.subnets) | project name, resourceGroup | sort by name asc"

从 Azure 顾问获取成本节约情况摘要Get cost savings summary from Azure Advisor

此查询汇总了每个 Azure 顾问建议的成本节约情况。This query summarizes the cost savings of each Azure Advisor recommendation.

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"

后续步骤Next steps