分享方式:


使用 Python 來管理 Azure 資源群組

了解如何將 Python 與 Azure Resource Manager 搭配使用,以管理您的 Azure 資源群組。

必要條件

  • 已安裝 Python 3.8 或更新版本。 若要安裝最新版,請參閱 Python.org

  • 已在您的虛擬環境中安裝下列適用於 Python 的 Azure 程式庫套件。 若要安裝任何套件, 請使用 pip install {package-name}

    • azure-identity
    • azure-mgmt-resource
    • azure-mgmt-storage

    如果您的虛擬環境中已安裝舊版的這些套件,您可能需要使用 pip install --upgrade {package-name}更新這些套件。

  • 本文中的範例會使用 CLI 型驗證 (AzureCliCredential)。 視您的環境而定,您可能需要先執行 az login ,才能進行驗證。

  • 使用 Azure 訂用帳戶識別碼的環境變數。 若要取得 Azure 訂用帳戶識別碼,請使用:

    az account show --name 'your subscription name' --query id -o tsv
    

    若要設定值,請使用適合您環境的選項。

    setx AZURE_SUBSCRIPTION_ID your-subscription-id
    

    注意

    如果您只需在目前執行中的主控台上存取環境變數,請使用 set 來設定環境變數,而不是 setx

    新增環境變數之後,您可能需要重新啟動任何需要讀取環境變數的執行中程式,包括主控台視窗。 例如,如果您使用 Visual Studio 作為編輯器,請在執行範例前重新啟動 Visual Studio。

什麼是資源群組?

「資源群組」是存放 Azure 解決方案相關資源的容器。 該資源群組可包含解決方案的所有資源,或是只包含您想以群組方式管理的資源。 您決定如何根據組織最有意義的內容,將資源新增至資源群組。 一般而言,將共用相同生命週期的資源新增至相同的資源群組,以便您輕鬆地以群組的形式部署、更新和刪除資源。

資源群組會儲存資源相關中繼資料。 當您指定資源群組的位置時,您便是指定中繼資料的儲存位置。 基於相容性理由,您可能需要確保您的資料存放在特定區域中。

建立資源群組

若要部署至資源群組,請使用 ResourceManagementClient.resource_groups.create_or_update

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

rg_result = resource_client.resource_groups.create_or_update(
    "exampleGroup",
    {
        "location": "westus"
    }
)

print(f"Provisioned resource group with ID: {rg_result.id}")

列出資源群組

若要列出訂用帳戶中的資源群組,請使用 ResourceManagementClient.resource_groups.list

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

rg_list = resource_client.resource_groups.list()

for rg in rg_list:
    print(rg.name)

若要取得一個資源群組,請使用 ResourceManagementClient.resource_groups.get 並提供資源群組的名稱。

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

rg_result = resource_client.resource_groups.get("exampleGroup")

print(f"Retrieved resource group {rg_result.name} in the {rg_result.location} region with resource ID {rg_result.id}")

刪除資源群組

若要刪除資源群組,請使用 ResourceManagementClient.resource_groups.begin_delete

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

rg_result = resource_client.resource_groups.begin_delete("exampleGroup")

如需 Azure Resource Manager 如何決定資源刪除順序的詳細資訊,請參閱 Azure Resource Manager 資源群組刪除

部署資源

您可以使用 Python 類別或部署 Azure Resource Manager 範本 (ARM 範本) 來部署 Azure 資源。

使用 Python 類別部署資源

下列範例會使用 StorageManagementClient.storage_accounts.begin_create 建立儲存體帳戶。 儲存體帳戶的名稱在 Azure 中必須是唯一的。

import os
import random
from azure.identity import AzureCliCredential
from azure.mgmt.storage import StorageManagementClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

random_postfix = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz1234567890', k=13))
storage_account_name = "demostore" + random_postfix

storage_client = StorageManagementClient(credential, subscription_id)

storage_account_result = storage_client.storage_accounts.begin_create(
    "exampleGroup",
    storage_account_name,
    {
        "location": "westus",
        "sku": {
            "name": "Standard_LRS"
        }
    }
)

使用 ARM 範本部署資源

若要部署 ARM 範本,請使用 ResourceManagementClient.deployments.begin_create_or_update。 下列範例需要名稱為 storage.json 的本機範本。

import os
import json
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.resource.resources.models import DeploymentMode

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

resource_client = ResourceManagementClient(credential, subscription_id)

with open("storage.json", "r") as template_file:
    template_body = json.load(template_file)

rg_deployment_result = resource_client.deployments.begin_create_or_update(
    "exampleGroup",
    "exampleDeployment",
    {
        "properties": {
            "template": template_body,
            "parameters": {
                "storagePrefix": {
                    "value": "demostore"
                },
            },
            "mode": DeploymentMode.incremental
        }
    }
)

下列範例顯示您要部署的 ARM 範本 storage.json

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storagePrefix": {
      "type": "string",
      "minLength": 3,
      "maxLength": 11
    }
  },
  "variables": {
    "uniqueStorageName": "[concat(parameters('storagePrefix'), uniqueString(resourceGroup().id))]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2022-09-01",
      "name": "[variables('uniqueStorageName')]",
      "location": "eastus",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2",
      "properties": {
        "supportsHttpsTrafficOnly": true
      }
    }
  ]
}

如需部署 ARM 範本的詳細資訊,請參閱使用 ARM 範本和 Azure CLI 部署資源

鎖定資源群組

鎖定可防止您組織中的其他使用者不小心刪除或修改重要資源。

若要防止資源群組及其資源遭到刪除,請使用 ManagementLockClient.management_locks.create_or_update_at_resource_group_level

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ManagementLockClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

lock_client = ManagementLockClient(credential, subscription_id)

lock_result = lock_client.management_locks.create_or_update_at_resource_group_level(
    "exampleGroup",
    "lockGroup",
    {
        "level": "CanNotDelete"
    }
)

若要取得資源群組的鎖定,請使用 ManagementLockClient.management_locks.list_at_resource_group_level

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ManagementLockClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

lock_client = ManagementLockClient(credential, subscription_id)

lock_result = lock_client.management_locks.get_at_resource_group_level("exampleGroup", "lockGroup")

print(f"Lock {lock_result.name} applies {lock_result.level} lock")

若要刪除資源群組的鎖定,請使用 ManagementLockClient.management_locks.delete_at_resource_group_level

import os
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ManagementLockClient

credential = AzureCliCredential()
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

lock_client = ManagementLockClient(credential, subscription_id)

lock_client.management_locks.delete_at_resource_group_level("exampleGroup", "lockGroup")

如需詳細資訊,請參閱使用 Azure Resource Manager 來鎖定資源

標記資源群組

您可以將標籤套用至資源群組和資源,以便以邏輯方式組織您的資產。 如需詳細資訊,請參閱 使用標記組織您的 Azure 資源

將資源群組匯出至範本

若要協助建立 ARM 範本,您可以從現有的資源匯出範本。 如需詳細資訊,請參閱使用 Azure 入口網站匯出範本

管理對資源群組的存取

Azure 角色型訪問控制 (Azure RBAC) 是您管理 Azure 中資源的存取權的方式。 如需詳細資訊,請參閱使用 Azure CLI 新增或移除 Azure 角色指派

下一步