如何使用Python代码列出所有Azure虚拟机镜像
实现全量Azure虚拟机镜像列出的Python脚本
要获取全量Azure VM镜像,必须逐层遍历区域→发布者(publisher)→产品(offer)→SKU→版本,因为Azure没有直接返回全量镜像的API接口。以下是可直接运行的脚本实现:
前置准备
先安装所需依赖包:
pip install azure-mgmt-compute azure-identity
完整脚本
from azure.identity import DefaultAzureCredential from azure.mgmt.compute import ComputeManagementClient from azure.core.exceptions import HttpResponseError, ResourceNotFoundError import time def list_all_vm_images(subscription_id): # 初始化Compute客户端 credential = DefaultAzureCredential() compute_client = ComputeManagementClient(credential, subscription_id) # 获取订阅可用的所有区域 regions = [region.name for region in compute_client.subscriptions.list_locations()] print(f"发现可用区域: {len(regions)} 个") all_images = [] for region in regions: print(f"\n=== 开始遍历区域: {region} ===") try: # 获取该区域下所有发布者 publishers = list(compute_client.virtual_machine_images.list_publishers(region)) print(f"区域{region}下发布者数量: {len(publishers)}") for publisher in publishers: publisher_name = publisher.name try: # 获取该发布者在当前区域的所有产品 offers = list(compute_client.virtual_machine_images.list_offers(region, publisher_name)) for offer in offers: offer_name = offer.name try: # 获取该产品的所有SKU skus = list(compute_client.virtual_machine_images.list_skus(region, publisher_name, offer_name)) for sku in skus: sku_name = sku.name try: # 获取该SKU的所有版本(这里只取最新5个,若要全量可去掉top参数) versions = list(compute_client.virtual_machine_images.list( region, publisher_name, offer_name, sku_name, top=5 )) for version in versions: image_info = { "region": region, "publisher": publisher_name, "offer": offer_name, "sku": sku_name, "version": version.name, "id": version.id } all_images.append(image_info) print(f"已记录镜像: {publisher_name}/{offer_name}/{sku_name}/{version.name}") except HttpResponseError as e: print(f"获取SKU {sku_name}版本失败: {e.message}") time.sleep(1) # 遇到错误暂停1秒,避免触发速率限制 except ResourceNotFoundError: print(f"SKU {sku_name}在区域{region}不存在") except HttpResponseError as e: print(f"获取产品 {offer_name}的SKU失败: {e.message}") time.sleep(1) except HttpResponseError as e: print(f"获取发布者 {publisher_name}的产品失败: {e.message}") time.sleep(1) except HttpResponseError as e: print(f"遍历区域 {region}失败: {e.message}") continue # 将结果写入CSV文件(可选) import csv with open("all_azure_vm_images.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["region", "publisher", "offer", "sku", "version", "id"]) writer.writeheader() writer.writerows(all_images) print(f"\n=== 完成!共获取{len(all_images)}个镜像,已保存到all_azure_vm_images.csv ===") if __name__ == "__main__": # 替换为你的订阅ID SUBSCRIPTION_ID = "your-subscription-id-here" list_all_vm_images(SUBSCRIPTION_ID)
关键说明
- 认证方式:使用
DefaultAzureCredential,支持本地开发(Azure CLI、VS Code)、云环境(Managed Identity)等多种认证场景,无需硬编码密钥。 - 速率限制处理:添加了
time.sleep(1)在错误时暂停,避免触发Azure API的速率限制;若需要更高效的处理,可引入tenacity库实现重试逻辑。 - 版本过滤:脚本中默认只取每个SKU的最新5个版本,若需要全量版本,移除
list()中的top=5参数即可,但会大幅增加运行时间和API调用量。 - 权限要求:执行脚本的账号需要拥有Compute Image User或更高权限(如Contributor),确保能读取镜像元数据。
内容的提问来源于stack exchange,提问作者Sandhya
相关产品推荐
相关产品推荐

