You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python为Azure Disk创建或添加标签?

Azure磁盘添加/更新标签的Python SDK实现

修正后的可运行代码

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

# 初始化Compute客户端
credential = DefaultAzureCredential()
subscription_id = "你的订阅ID"
compute_client = ComputeManagementClient(credential, subscription_id)

resource_group_name = "你的资源组名称"
disk_name = "test_disk_rohit"

# 获取目标磁盘的完整配置
disk = compute_client.disks.get(resource_group_name, disk_name)

# 处理标签:初始化空字典(若磁盘无标签),添加/更新目标标签
disk.tags = disk.tags or {}
# 将datetime对象转为字符串,Azure标签值仅支持字符串类型
disk.tags["DetachedTime"] = datetime.now().isoformat()

# 提交磁盘更新请求,等待操作完成
poller = compute_client.disks.begin_create_or_update(
    resource_group_name,
    disk_name,
    disk
)
updated_disk = poller.result()
print(f"标签更新成功,当前磁盘标签:{updated_disk.tags}")

原代码的问题说明

  • 未定义变量:原代码中target_disk未初始化,直接调用会触发NameError。
  • 低效遍历:无需遍历所有磁盘,通过disks.get()传入资源组和磁盘名可直接定位目标磁盘,提升效率。
  • 类型不匹配:Azure标签的值必须是字符串,datetime.now()返回的是datetime对象,需转换为字符串格式。
  • 空标签处理缺失:若磁盘原本无标签,disk.tags为None,直接赋值键会报错,需先初始化为空字典。
  • 参数错误:begin_create_or_update的第一个参数应为资源组名称,原代码中resrc未明确赋值,需传入正确的资源组名称。

内容的提问来源于stack exchange,提问作者Rohit Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:10:24