Azure ComputeManagementClient.images.get()用通配符*匹配镜像名报错求助
实现Azure Compute镜像的通配符匹配查询
ComputeManagementClient.images.get()方法仅支持精确镜像名称匹配,Azure API不会将*解析为通配符,因此直接传入带*的名称会触发资源未找到错误。要实现通配符匹配,需要先获取目标资源组下的所有镜像,再在本地进行筛选。
解决方案代码
使用images.list_by_resource_group()获取资源组内所有镜像,结合fnmatch模块处理通配符匹配:
from azure.mgmt.compute import ComputeManagementClient from azure.identity import AzureCliCredential import fnmatch # 初始化客户端 credential = AzureCliCredential() compute_client = ComputeManagementClient(credential, '<subscription_id>') # 配置参数 resource_group_name = 'ab-westeurope-image-rg' pattern = 'ubuntu-latest-*' # 通配符匹配规则 # 获取资源组下所有镜像 all_images = compute_client.images.list_by_resource_group(resource_group_name) # 本地筛选符合通配符规则的镜像 matched_images = [image for image in all_images if fnmatch.fnmatch(image.name, pattern)] # 打印匹配到的镜像详情 if matched_images: print(f"找到 {len(matched_images)} 个匹配的镜像:") for img in matched_images: print(f"镜像名称: {img.name}") print(f"创建时间: {img.time_created}") print(f"ID: {img.id}") print("---") else: print("未找到匹配的镜像")
关键说明
list_by_resource_group():返回指定资源组下的所有自定义镜像(不包含Azure市场镜像)fnmatch.fnmatch():支持标准通配符语法(*匹配任意字符,?匹配单个字符,[]匹配字符范围),完全适配你的镜像名称格式需求- 如果需要更复杂的匹配逻辑,可以替换为正则表达式(比如
re.match())
内容的提问来源于stack exchange,提问作者Vinay Gowda
相关产品推荐
相关产品推荐

