此範例示範如何使用 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 腳本會使用適用於 Python 的 Azure SDK 管理連結庫,在您的 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,請使用 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"