你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

如何使用 Azure CLI 管理 Azure 资源组

Azure 资源组是一个容器,用于保存 Azure 解决方案的相关资源。 资源组可能包含存储、虚拟机、应用、仪表板、服务或你在 Azure 中处理的任何内容。

使用 Azure Command-Line 接口(CLI),可以创建、保留和设置默认的 Azure 资源组。 CLI 还允许在创建资源后清理资源。

Azure 区域标识

Azure 客户可以选择在许多不同的区域中部署资源。 在某些情况下,客户可以通过选择提供相同服务的附近区域来降低成本。 如果某个附近区域被标识,则一条消息会显示要选择用于将来部署的区域。

在以下示例中, az config 该命令用于禁用区域建议消息:

az config set core.display_region_identified=no

有关 Azure 区域的详细信息,请参阅选择适合你的 Azure 区域

创建资源组

若要创建资源组,请使用 az group create 命令:

az group create --name MyResourceGroup --___location eastus

资源组属于单个地域。 若要查看当前订阅中支持的所有位置,请运行 az account list-locations 命令:

az account list-locations

若要查看当前订阅的所有资源组,请使用 az group list 命令:

az group list --output table

小窍门

--output 参数是全局参数,适用于所有命令。 "表格值以友好的格式呈现输出。" 有关详细信息,请参阅 Azure CLI 命令的输出格式

创建资源时,请在资源组中创建它。 以下示例演示了使用 az storage account create 命令创建的存储帐户:

az storage account create --resource-group MyResourceGroup --name storage134 --___location eastus --sku Standard_LRS

若要删除资源组,请运行 az group delete 命令:

az group delete --name MyResourceGroup

删除资源组时,将删除属于该资源组的所有资源。 此操作无法撤消。 如果您尝试本文中的任何命令,请通过删除您创建的资源组来整理您的账户。

设置默认资源组

可以为从本地 Azure CLI 或 Azure Cloud Shell 运行的所有命令设置默认资源组。 Azure CLI 将此配置本地存储在 配置文件 中。 若要查看当前配置,请运行 az config get 命令:

az config get

结果显示默认资源组和其他默认值。 如果首次使用 Azure CLI,结果可能为空。

若要为 Azure CLI 安装设置默认资源组,请运行 az config set 命令:

az config set defaults.group=MyResourceGroup

此命令为指定的键设置一个值,在本例 defaults.group中。 有关可用配置选项,请参阅 Azure CLI 配置

注释

az config set 命令不会验证输入的资源组是否存在。 该命令只是简单地存储键值对。

运行该命令后,以下两个命令将得到相同的结果:

az storage account create --resource-group MyResourceGroup --name storage01  --___location eastus --sku Standard_LRS
az storage account create --name storage01 --___location eastus --sku Standard_LRS

资源组属于订阅。 如果您的组织有多个订阅,则在使用订阅中的资源组之前,您需要先设置好该订阅。 如果资源组的默认值不属于当前订阅,则会出现错误。 有关多个订阅的详细信息,请参阅 “使用多个 Azure 订阅”。

无需重置默认值以使用其他资源组。 请改为指定资源组:

az group create --name OtherResourceGroup --___location eastus
az storage account create --resource-group StorageGroups --name storage03  --___location westus --sku Standard_LRS

默认值仅适用于你。 它不会影响通过 Azure 门户进行的其他用户或更改。

如果使用持久化参数值,如本文所述,这些值优先于 配置文件 中设置的默认值。

设置资源组锁

作为管理员,可能需要锁定资源组,以防止用户删除或修改资源组。 有关详细信息,请参阅锁定资源以防止意外更改

在 Azure CLI 中,使用 az group lock 命令。 例如, az account lock create 命令可以阻止用户删除资源组:

az group lock create --name "Cannot delete resource group" --lock-type CanNotDelete

注释

需要对资源组具有权限才能创建或更改锁。

若要查看资源组上的当前锁,请使用 az group lock list 命令:

az group lock list --output table

清理资源

如果尝试了本文中的任何命令,则可以使用 az group delete 命令删除创建的任何资源:

az group delete --name MyResourceGroup
az group delete --name OtherResourceGroup
az group delete --name StorageGroups

此命令将一次性删除组及其包含的所有资源。

另请参阅