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

如何通过REST API或Python SDK获取指定标签Azure服务并批量删除?

通过REST API或Python SDK管理带指定标签的Azure服务

一、获取含指定标签的所有服务列表

1. REST API方式

使用Azure Resource Graph的REST API实现跨资源查询,这是最直接的方式:

  • 请求方法:POST
  • 请求URL:https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=2021-03-01
  • 请求体示例(查询标签Environment值为Test的所有资源):
{
    "query": "resources | where tags has 'Environment' and tags.Environment == 'Test'"
}

注意:请求必须携带有效的Azure AD访问令牌,账号需具备Microsoft.ResourceGraph/resources/read权限。

2. Python SDK方式

借助azure-mgmt-resourcegraph包实现查询:

  1. 安装依赖:pip install azure-mgmt-resourcegraph azure-identity
  2. 示例代码:
from azure.identity import DefaultAzureCredential
from azure.mgmt.resourcegraph import ResourceGraphClient
from azure.mgmt.resourcegraph.models import QueryRequest

credential = DefaultAzureCredential()
client = ResourceGraphClient(credential)

# 自定义标签查询语句
query = "resources | where tags has 'Environment' and tags.Environment == 'Test'"
request = QueryRequest(query=query)
response = client.resources(request)

# 遍历输出结果
for resource in response.data:
    print(f"资源ID: {resource['id']}, 名称: {resource['name']}, 类型: {resource['type']}")

二、批量删除带指定标签的服务

1. REST API方式

  1. 先通过上述Resource Graph API获取所有目标资源的id
  2. 对每个资源单独发送DELETE请求:
    • 请求方法:DELETE
    • 请求URL格式:{resource-id}?api-version={对应资源的API版本}
      不同资源类型的API版本不同,比如虚拟机用2023-07-01,存储账户用2023-01-01,可从查询结果的type字段推导,或参考Azure官方文档的对应资源API版本说明。

2. Python SDK方式

在获取资源列表后,根据资源类型调用对应管理客户端执行删除操作,示例以虚拟机为例:

from azure.mgmt.compute import ComputeManagementClient

# 初始化计算资源客户端
compute_client = ComputeManagementClient(credential, "你的订阅ID")

for resource in response.data:
    if resource['type'] == 'Microsoft.Compute/virtualMachines':
        resource_group = resource['id'].split('/')[4]
        vm_name = resource['name']
        # 发起异步删除请求
        compute_client.virtual_machines.begin_delete(resource_group, vm_name)
        print(f"已发起删除虚拟机 {vm_name} 的请求")

其他资源类型(如存储账户、App Service)需使用对应的管理客户端(azure-mgmt-storage、azure-mgmt-web等),调用对应资源的删除方法即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:08:29