此示例演示如何使用 Python 脚本中的 Azure SDK 管理库创建资源组。 (本文后面提供了 等效的 Azure CLI 命令 。如果希望使用 Azure 门户,请参阅 “创建资源组”。
本文中的所有命令在 Linux/macOS bash 和 Windows 命令行界面中的工作方式相同,除非另有说明。
1:设置本地开发环境
如果尚未安装,请设置可以运行此代码的环境。 下面是一些选项:
使用
venv
或所选工具配置 Python 虚拟环境。 若要开始使用虚拟环境,请务必激活它。 若要安装 python,请参阅 “安装 Python”。#!/bin/bash # Create a virtual environment python -m venv .venv # Activate the virtual environment source .venv/Scripts/activate # only required for Windows (Git Bash)
使用 conda 环境。 若要安装 Conda,请参阅 “安装 Miniconda”。
在 Visual Studio Code 或 GitHub Codespaces中使用 开发容器。
2:安装 Azure 库包
在控制台中创建一个 requirements.txt 文件,其中列出了此示例中使用的管理库:
azure-mgmt-resource azure-identity
在激活虚拟环境的控制台中,安装要求:
pip install -r requirements.txt
3. 设置环境变量
在此步骤中,你将设置环境变量,以便在本文中的代码中使用。 代码使用 os.environ
方法来检索值。
#!/bin/bash
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export LOCATION=<Location> # Change to your preferred region
export AZURE_SUBSCRIPTION_ID=$(az account show --query id --output tsv)
4:编写代码以创建资源组
在此步骤中,你将使用以下代码创建名为 provision_blob.py 的 Python 文件。 此 Python 脚本使用 Azure SDK for Python 管理库在 Azure 订阅中创建资源组。
使用以下代码创建名为 provision_rg.py 的 Python 文件。 注释说明了详细信息:
# Import the needed credential and management objects from the libraries.
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
# Acquire a credential object using DevaultAzureCredential.
credential = DefaultAzureCredential()
# Retrieve subscription ID from environment variable.
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
# Retrieve resource group name and ___location from environment variables
RESOURCE_GROUP_NAME = os.environ["AZURE_RESOURCE_GROUP_NAME"]
LOCATION = os.environ["LOCATION"]
# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)
# Provision the resource group.
rg_result = resource_client.resource_groups.create_or_update(RESOURCE_GROUP_NAME,
{ "___location": LOCATION })
print(f"Provisioned resource group {rg_result.name}")
# Within the ResourceManagementClient is an object named resource_groups,
# which is of class ResourceGroupsOperations, which contains methods like
# create_or_update.
#
# The second parameter to create_or_update here is technically a ResourceGroup
# object. You can create the object directly using ResourceGroup(___location=
# LOCATION) or you can express the object as inline JSON as shown here. For
# details, see Inline JSON pattern for object arguments at
# https://learn.microsoft.com/azure/developer/python/sdk
# /azure-sdk-library-usage-patterns#inline-json-pattern-for-object-arguments
print(
f"Provisioned resource group {rg_result.name} in the {rg_result.___location} region"
)
# The return value is another ResourceGroup object with all the details of the
# new group. In this case the call is synchronous: the resource group has been
# provisioned by the time the call returns.
# To update the resource group, repeat the call with different properties, such
# as tags:
rg_result = resource_client.resource_groups.create_or_update(
RESOURCE_GROUP_NAME,
{
"___location": LOCATION,
"tags": {"environment": "test", "department": "tech"},
},
)
print(f"Updated resource group {rg_result.name} with tags")
# Optional lines to delete the resource group. begin_delete is asynchronous.
# poller = resource_client.resource_groups.begin_delete(rg_result.name)
# result = poller.result()
代码中的身份验证
本文稍后会使用 Azure CLI 登录到 Azure,以执行示例代码。 如果帐户有足够的权限在 Azure 订阅中创建资源组和存储资源,则脚本应成功运行,而无需其他配置。
若要在生产环境中使用此代码,请通过设置环境变量来使用服务主体进行身份验证。 此方法支持安全、自动化的访问,而无需依赖于交互式登录。 有关详细指南,请参阅 如何使用 Azure 服务对 Python 应用进行身份验证。
确保为服务主体分配了具有足够权限的角色来创建资源组和存储帐户。 例如,在订阅级别分配参与者角色可提供必要的访问权限。 若要了解有关角色分配的详细信息,请参阅 Azure 中基于角色的访问控制(RBAC)。
代码中使用的类的参考链接
5:运行脚本
如果尚未登录,请使用 Azure CLI 登录到 Azure:
az login
运行以下脚本:
python provision_rg.py
6:验证资源组
可以通过 Azure 门户或 Azure CLI 验证资源组是否存在。
Azure 门户:打开 Azure 门户,选择 资源组,并检查该组是否已列出。 如有必要,请使用 Refresh 命令更新列表。
Azure CLI:使用 az group show 命令:
#!/bin/bash az group show -n $AZURE_RESOURCE_GROUP_NAME
7:清理资源
如果不需要保留在此示例中创建的资源组,请运行 az group delete 命令。 资源组不会在订阅中产生任何持续费用,但资源组中的资源可能会继续产生费用。 清理不经常使用的组是一种很好的做法。
--no-wait
参数允许命令立即返回,而不是等待作完成。
#!/bin/bash
az group delete -n $AZURE_RESOURCE_GROUP_NAME --no-wait
还可以使用 ResourceManagementClient.resource_groups.begin_delete
方法从代码中删除资源组。 本文脚本底部的注释代码演示了用法。
有关参考:等效的 Azure CLI 命令
以下 Azure CLI az group create 命令使用标记创建资源组,就像 Python 脚本一样:
az group create -n PythonAzureExample-rg -l centralus --tags "department=tech" "environment=test"