使用 Python 管理Azure资源组

了解如何将 Python 与 Azure Resource Manager 配合使用来管理Azure资源组。

先决条件

  • 已安装 Python 3.8 或更高版本。 若要安装最新版本,请参阅 Python.org

  • 以下Azure库包,用于在虚拟环境中安装Python。 若要安装任何包,请使用 pip install {package-name}

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

    如果虚拟环境中已安装这些包的较旧版本,则可能需要使用 pip install --upgrade {package-name} 更新它们。

  • 本文中的示例将使用基于 CLI 的身份验证 (AzureCliCredential)。 根据环境,可能需要先运行 az login 进行身份验证。

  • 具有 "Azure 订阅 ID" 的环境变量。 若要获取Azure订阅 ID,请使用:

    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": "chinanorth"
    }
)

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": "chinanorth",
        "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
        }
    }
)

以下示例显示了你即将部署的名为 storage.json 的 ARM 模板:

{
  "$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": "chinanorth",
      "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 资源管理器锁定资源。

标记资源组

可以将标记应用到资源组和资源,以按照逻辑组织资产。 有关详细信息,请参阅 使用标记来组织Azure资源

将资源组导出到模板

若要协助创建 ARM 模板,可以从现有资源导出模板。 有关详细信息,请参阅 使用 Azure 门户导出模板

管理对资源组的访问

Azure基于角色的访问控制(Azure RBAC)是管理对Azure中资源的访问权限的方式。 有关详细信息,请参阅 使用 Azure CLI 添加或删除 Azure 角色分配

后续步骤