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

使用google.cloud.artifactregistry_v1beta2 API获取GCP镜像标签遇参数错误

解决GCP Artifact Registry list_tags 400无效参数错误

问题根源

调用list_tags时传入的parent参数不符合API要求:list_tags的parent必须指向Artifact Registry中的Package资源完整路径,而非Repository的路径。你当前直接传递Repository的名称作为parent,导致API返回400无效参数错误。

修复方案

需要先获取指定仓库下的所有Package(每个Docker镜像对应一个Package),再针对每个Package调用list_tags获取其关联的镜像标签。以下是修正后的完整代码:

from google.cloud import artifactregistry_v1beta2

def list_all_repositories(project):
    client = artifactregistry_v1beta2.ArtifactRegistryClient()
    locations = ['northamerica-northeast1']
    repositories = []
    for location in locations:
        parent = f"projects/{project}/locations/{location}"
        repositories_in_location = client.list_repositories(parent=parent)
        repositories.extend(repositories_in_location)
    return repositories

def list_images(repository_name):
    client = artifactregistry_v1beta2.ArtifactRegistryClient()
    # 先获取仓库下的所有Package(每个Docker镜像对应一个Package)
    packages = client.list_packages(parent=repository_name)
    
    all_tags = []
    for pkg in packages:
        # 传入Package完整路径作为list_tags的parent参数
        tags = client.list_tags(parent=pkg.name)
        all_tags.extend(tags)
    
    # 按创建时间倒序排序镜像标签
    sorted_tags = sorted(all_tags, key=lambda tag: tag.create_time, reverse=True)
    
    for tag in sorted_tags:
        print(f"镜像标签: {tag.name.split('/')[-1]}, 创建时间: {tag.create_time}")

# 替换为你的GCP项目ID
PROJECT_ID = "your-project-id"
repositories = list_all_repositories(PROJECT_ID)

for repository in repositories:
    print(f"检查仓库: {repository.name}")
    list_images(repository_name=repository.name)

关键修正点

  • 新增list_packages调用:遍历仓库下的所有Package,这是获取镜像标签的必要前置步骤
  • 修正list_tags的parent参数:传入Package的完整路径而非Repository路径
  • 优化输出:拆分标签名称路径,只显示最终的标签字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:55:03