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

如何通过google-compute-engine Python客户端过滤Google Cloud实例?

Google Cloud Compute 实例按标签过滤实现方案

依赖版本确认

你使用的依赖版本如下,方案兼容该版本范围:

Package                  Version
------------------------ ---------
google-api-core          2.0.1
google-auth              2.0.2
google-cloud-compute     0.5.0
google-compute-engine    2.8.13

方案1:服务端过滤(推荐)

aggregated_list接口原生支持通过filter参数在服务端完成标签过滤,减少无用数据传输,过滤语法规则如下:

  • 匹配包含指定单个标签的实例:filter='tags.items="target-tag"'
  • 匹配同时包含多个标签的实例:filter='tags.items="tag1" AND tags.items="tag2"'
  • 匹配包含任意一个指定标签的实例:filter='tags.items="tag1" OR tags.items="tag2"'
    示例代码:
from google.cloud import compute_v1

def list_instances_by_tag(project_id: str, target_tag: str):
    client = compute_v1.InstancesClient()
    # 传入服务端过滤参数
    request = compute_v1.AggregatedListInstancesRequest(
        project=project_id,
        filter=f'tags.items="{target_tag}"'
    )

    for zone, response in client.aggregated_list(request=request):
        if response.instances:
            for instance in response.instances:
                print(f"匹配实例:{zone} - {instance.name}")

方案2:本地过滤(兜底方案)

如果过滤规则非常复杂,服务端语法无法满足,可以先拉取全量实例数据后本地做过滤,示例代码:

from google.cloud import compute_v1

def list_instances_by_tag_local(project_id: str, target_tags: list):
    client = compute_v1.InstancesClient()
    request = compute_v1.AggregatedListInstancesRequest(project=project_id)
    matched_instances = []

    for zone, response in client.aggregated_list(request=request):
        if response.instances:
            for instance in response.instances:
                # 取实例标签做交集判断
                instance_tags = instance.tags.items if instance.tags else []
                if set(target_tags).issubset(set(instance_tags)):
                    matched_instances.append({
                        "zone": zone,
                        "name": instance.name,
                        "tags": instance_tags
                    })
    return matched_instances

注意事项

  • 服务端过滤的标签值区分大小写
  • 若实例未配置任何标签,tags字段会返回空,过滤时需做判空处理避免报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:18:03