在本快速入门中,你使用 Bicep 创建 Azure Resource Graph 共享查询。 可以将 Resource Graph 查询另存为专用查询或共享查询。 专用查询将保存到个人 Azure 门户配置文件中,不显示给其他人。 共享查询是一个资源管理器对象,可通过权限和基于角色的访问权限与他人共享。 可以通过共享查询以通用且一致的方式执行资源发现操作。
Bicep 是一种特定于域的语言 (DSL),使用声明性语法来部署 Azure 资源。 它提供简明的语法、可靠的类型安全性以及对代码重用的支持。 Bicep 会针对你的 Azure 基础结构即代码解决方案提供最佳创作体验。
- 如果没有 Azure 帐户,请在开始前创建一个试用帐户。
- Azure CLI 或 PowerShell 和 Azure PowerShell。
- Visual Studio Code。
从 Visual Studio Code 终端会话连接到 Azure。 如果具有多个订阅,请运行命令以将上下文设置为你的订阅。 将 <subscriptionID>
替换为你的 Azure 订阅 ID。
az login
# Run these commands if you have multiple subscriptions
az account list --output table
az account set --subscription <subscriptionID>
在本快速入门中,我们创建一个名为“按 OS 进行 VM 计数”的共享查询。 若要使用 Resource Graph 资源管理器在 SDK 或门户中尝试此查询,请参阅示例 - 按 OS 类型对虚拟机进行计数。
本快速入门中使用的 Bicep 文件来自 Azure 快速入门模板。
- 打开 Visual Studio Code 并创建一个新文件。
- 将 Bicep 文件复制粘贴到新文件中。
- 在本地计算机上将该文件保存为 main.bicep。
@description('The name of the shared query.')
param queryName string = 'Count VMs by OS'
@description('The Azure Resource Graph query to be saved to the shared query.')
param queryCode string = 'Resources | where type =~ \'Microsoft.Compute/virtualMachines\' | summarize count() by tostring(properties.storageProfile.osDisk.osType)'
@description('The description of the saved Azure Resource Graph query.')
param queryDescription string = 'This shared query counts all virtual machine resources and summarizes by the OS type.'
resource query 'Microsoft.ResourceGraph/queries@2018-09-01-preview' = {
name: queryName
location: 'global'
properties: {
query: queryCode
description: queryDescription
}
}
Bicep 文件中定义的资源为:Microsoft.ResourceGraph/queries。 若要了解如何创建 Bicep 文件,请转到快速入门:使用 Visual Studio Code 创建 Bicep 文件。
使用 Azure CLI 或 Azure PowerShell 创建资源组并部署 Bicep 文件。 请确保你位于保存 Bicep 文件的目录中。 否则,需要指定文件的路径。
az group create --name demoSharedQuery --location chinaeast2
az deployment group create --resource-group demoSharedQuery --template-file main.bicep
该部署会将消息输出到你的 shell。 部署完成后,shell 将返回到命令提示符。
使用 Azure CLI 或 Azure PowerShell 列出资源组中已部署的资源。
az resource list --resource-group demoSharedQuery
输出会显示共享查询的名称、资源组名称和资源 ID。
可以使用 Azure Resource Graph 资源管理器验证共享查询是否正常工作。 若要更改范围,请使用页面左侧的“范围”菜单。
- 登录到 Azure 门户。
- 在页面顶部的搜索字段中输入 Resource Graph。
- 选择“Resource Graph 资源管理器”。
- 选择“打开查询”。
- 将“类型”更改为“共享查询”。
- 选择“按 OS 对 VM 计数”查询。
- 在“结果”选项卡中选择“运行查询”和“查看输出”。
还可以从资源组运行查询。
- 在 Azure 中,转到资源组 demoSharedQuery。
- 在“概述 ”选项卡中,选择“按 OS 对 VM 计数”查询。
- 选择“结果”选项卡。
不再需要所创建的资源时,请使用 Azure CLI 或 Azure PowerShell 删除资源组。 删除某个资源组后,将删除该资源组及其所有资源。 如果你登录到了 Azure 门户以运行查询,请务必退出登录。
az group delete --name demoSharedQuery
若要退出登录 Azure CLI 会话,请执行以下操作:
az logout
在本快速入门中,你使用 Bicep 创建了一个 Resource Graph 共享查询。 若要详细了解 Resource Graph 语言,请继续阅读查询语言详细信息页。