【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot - LuBu0505/My-Code GitHub Wiki

问题描述

需要为中国区微软云(China Azure)中的虚拟机磁盘(VM Disk)创建快照, 官方文档中只有az cli(az snapshot create)脚本,并没有介绍使用Python SDK的办法,需要编写代码来实现快照的创建。

问题解答

Azure Python SDK 的 Snapshot Class文档提供了参数说明,如 location 为创建Snapshot资源的位置(必须填写,如China North 3, China East 2等)。另外,最主要的参数是 creation_data,包含Disk的详细信息。

  • create_option :列举了创建磁盘的可能来源。必填。已知值为:“Empty”、“Attach”、“FromImage”、“Import”、“Copy”、“Restore”、“Upload”、“CopyStart”、“ImportSecure”、“UploadPreparedSecure”和“Import”。本文示例是要从已有的Disk中创建快照用于复制还原,所以选择 Copy 。

  • source_resource_id:此处为源VM Disk的资源ID,如:'/subscriptions/x-x-x-x/resourceGroups/xxxxx/providers/Microsoft.Compute/disks/xxxxxxx'

根据以上内容,示例的Python代码如下:

from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient

# Set your subscription ID and resource group name
subscription_id = ' '
resource_group_name = 'xxx-RG'
snapshot_name = 'xxxx'
source_disk_id = '/subscriptions/x-x-x-x/resourceGroups/xxxxx/providers/Microsoft.Compute/disks/xxxxxxx'

# Create a ComputeManagementClient object
credential = DefaultAzureCredential()

compute_client = ComputeManagementClient(credential, subscription_id,base_url="https://management.chinacloudapi.cn/", credential_scopes=["https://management.chinacloudapi.cn/.default"])


# Define the snapshot parameters
snapshot_params = {
    'location': 'China North 3',
    'creation_data': {
        'create_option': 'Copy',
        'source_resource_id': source_disk_id
    }
}

# Create the snapshot
snapshot = compute_client.snapshots.begin_create_or_update(
    resource_group_name,
    snapshot_name,
    snapshot_params
).result()

print(snapshot)

注释

1:使用Default Azure Credential,在执行代码的环境中配置环境变量:AZURE_TENANT_ID, AZURE_CLIENT_ID 和 AZURE_CLIENT_SECRET

2:在中国区Azure中,需要指定 ComputeManagementClient 对象的 base_url 和 credential_scopes, 它们的值是固定的。如需要在Global Azure中使用,可以不用这两个参数值。

代码执行效果图: image.png

参考资料

DefaultAzureCredential (EnvironmentCredential) Class : https://learn.microsoft.com/en-us/dotnet/api/azure.identity.environmentcredential?view=azure-dotnet

创建虚拟硬盘的快照 : https://docs.azure.cn/zh-cn/virtual-machines/snapshot-copy-managed-disk?tabs=cli

Snapshot Class : https://learn.microsoft.com/zh-cn/python/api/azure-mgmt-compute/azure.mgmt.compute.v2022_03_02.models.snapshot?view=azure-python

CreationData Class : https://learn.microsoft.com/zh-cn/python/api/azure-mgmt-compute/azure.mgmt.compute.v2022_03_02.models.creationdata?view=azure-python

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!