如何通过Azure API获取Azure RM中VM镜像的操作系统类型
获取Azure镜像操作系统类型的编程方法
没问题,我来帮你搞定这个需求!你可以通过Azure Compute相关的API、CLI或者SDK来获取镜像的操作系统类型,下面是几种实用且可靠的方法:
方法1:直接调用Azure Compute REST API
你可以通过调用Azure Compute的镜像详情API来获取OS类型,具体操作如下:
- 构造API请求URL(替换括号里的参数为你的实际值):
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{sku}/versions/{version}?api-version=2023-07-01 - 认证方式:使用Azure AD令牌作为请求头的
Authorization: Bearer <token>(可以通过服务主体或用户身份获取) - 响应结果里,
properties.storageProfile.osDiskImage.osType字段就是你要的操作系统类型,值为Windows或Linux
如果不确定具体的镜像版本,可以先调用版本列表API获取所有可用版本,再任选一个版本查询OS类型(同一个SKU下的镜像版本OS类型通常一致):
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{sku}/versions?api-version=2023-07-01
方法2:用Azure CLI做编程调用
如果你用脚本语言(比如Bash、Python)开发,可以调用Azure CLI命令来获取,然后解析输出:
- 执行命令(替换参数为你的实际值):
az vm image show --location <你的区域> --publisher <镜像发布者> --offer <镜像Offer> --sku <镜像SKU> --version <镜像版本> --query "osType" -o tsv - 这个命令会直接返回
Windows或Linux,非常适合脚本里直接使用。如果不知道版本,用latest代替具体版本号即可。
方法3:使用Azure SDK(以Python为例)
如果是用编程语言开发,推荐用官方SDK来实现,更优雅也更易维护:
- 先安装SDK包:
pip install azure-mgmt-compute azure-identity - 编写代码示例:
运行这段代码后,就能直接得到from azure.identity import DefaultAzureCredential from azure.mgmt.compute import ComputeManagementClient # 初始化客户端 subscription_id = "你的订阅ID" compute_client = ComputeManagementClient( credential=DefaultAzureCredential(), subscription_id=subscription_id ) # 定义镜像参数 location = "eastus" publisher_name = "Canonical" offer = "0001-com-ubuntu-server-jammy" sku = "22_04-lts" version = "latest" # 获取镜像详情 image = compute_client.virtual_machine_images.get( location=location, publisher_name=publisher_name, offer=offer, sku=sku, version=version ) # 提取OS类型 os_type = image.storage_profile.os_disk_image.os_type print(f"操作系统类型:{os_type}")Linux或Windows的结果。
这些方法我平时做Azure自动化任务的时候经常用,亲测稳定有效!
内容的提问来源于stack exchange,提问作者Arun Kumar G R
相关产品推荐
相关产品推荐

