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

如何在CI/CD流水线中结合gcloud与Python部署至Artifact Registry

解决Git CI/CD部署Google Cloud Artifact Registry的环境兼容问题

问题根源

你的两个配置都没解决CI阶段环境隔离的核心问题:

  • 版本1中,login-to-gcp阶段的认证状态无法传递到后续的deploy-package阶段(每个CI任务都是独立容器,环境不共享),且deploy-package用的Python镜像没有gcloud命令。
  • 版本2中,你试图合并两个环境的配置,但最后指定了python:latest镜像,覆盖了google/cloud-sdk,导致容器里还是没有gcloud。

可行解决方案

使用同时包含gcloud和Python环境的容器镜像,推荐基于google/cloud-sdk镜像安装Python,这样一个任务就能完成认证、打包、上传全流程。

修改后的完整CI配置

stages:
    - test
    - deploy

unit-test-job:
    image: python:latest
    variables:
        PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
    cache:
        paths:
            - .cache/pip
            - venv/
    before_script:
        - python3 -V
        - pip3 install virtualenv
        - virtualenv venv
        - source venv/bin/activate
        - pip3 install requests python-dotenv
    script:
        - python3 -m unittest discover

deploy-package:
    stage: deploy
    image: google/cloud-sdk:slim
    tags:
        - script
    only:
        - master
    before_script:
        # 安装Python环境和依赖工具
        - apt-get update && apt-get install -y python3 python3-pip
        - pip3 install build twine keyring keyrings.google-artifactregistry-auth
        # GCP认证
        - echo "$GOOGLE_SERVICE_ACCOUNT_JSON" > deployment_service_account.json
        - gcloud auth activate-service-account --key-file deployment_service_account.json
        # 可选:自动生成PyPI仓库配置,简化twine上传命令
        - gcloud artifacts print-settings python --repository=YOUR_REPO_NAME --location=YOUR_REGION > ~/.pypirc
    script:
        - python3 -m build
        - python3 -m twine upload --repository-url https://xxxxxxxx-python.pkg.dev/devote-staging/xxxxxxxx/ dist/*
    after_script:
        - rm -f deployment_service_account.json

关键说明

  1. 镜像选择:用google/cloud-sdk:slim作为基础镜像,它包含完整的gcloud工具,再通过apt-get安装Python3和pip3,确保环境同时具备两者。
  2. 认证流程:在同一个任务里完成GCP服务账号认证,认证状态直接作用于后续的twine上传(keyrings.google-artifactregistry-auth会自动读取gcloud的认证信息)。
  3. 阶段简化:把之前分散的install、authenticate阶段合并到deploy-package的before_script里,避免跨阶段环境不共享的问题。
  4. 权限检查:确保GOOGLE_SERVICE_ACCOUNT_JSON对应的服务账号拥有Artifact Registry Writer权限,否则会出现上传权限不足的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:15:40