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

GCP Artifact Registry上传Python包时遇用户名密码授权失败

GCP Artifact Registry Python仓库上传whl文件身份验证失败问题

问题描述

我在GCP项目中创建了共享Python仓库,尝试用twine上传dist/*.whl文件时,系统要求输入用户名和密码,但无论是输入PyPI账户还是GCP账户信息,都提示未授权。

已完成操作

  • 配置GCP项目:gcloud config set project [my_project]
  • 创建Python格式的Artifact Registry仓库:
    gcloud artifacts repositories create [repo] \
      --repository-format=python \
      --location=europe-west2 \
      --description="Shared Python package repository"
    
  • 设置默认仓库:gcloud config set artifacts/repository [repo]
  • 升级build工具:python3 -m pip install --upgrade build
  • 构建包生成whl文件:python3 -m build
  • 确认仓库地址:执行gcloud artifacts print-settings python --project=[my_project] --repository=[repo] --location=europe-west2验证地址正确
  • 执行上传命令:
    python3 -m twine upload --repository-url https://europe-west2-python.pkg.dev/[my_project]/[repo]/ dist/*
    

已排查项

  • 执行gcloud auth revoke后重新登录,登录状态正常(显示当前账户和项目正确)
  • 已启用Artifact Registry API,仓库可通过gcloud artifacts repositories list正常查看
  • 账户拥有权限:
    • Artifact Registry Administrator
    • Artifact Registry Create-on-Push Writer
    • Artifact Registry Repository Administrator
    • Artifact Registry Writer

解决方案

GCP Artifact Registry不支持直接输入GCP账户的用户名密码验证,需使用OAuth2访问令牌或服务账号密钥,推荐以下方法:

方法一:直接用gcloud访问令牌上传

执行命令时,用户名填oauth2accesstoken,密码用当前gcloud账户的访问令牌:

python3 -m twine upload --repository-url https://europe-west2-python.pkg.dev/[my_project]/[repo]/ dist/* -u oauth2accesstoken -p "$(gcloud auth print-access-token)"

方法二:配置twine凭据文件

创建或修改~/.pypirc文件,添加以下内容:

[distutils]
index-servers =
    gcp-artifact-registry

[gcp-artifact-registry]
repository = https://europe-west2-python.pkg.dev/[my_project]/[repo]/
username = oauth2accesstoken
password = $(gcloud auth print-access-token)

之后执行简化上传命令:

python3 -m twine upload --repository gcp-artifact-registry dist/*

方法三:服务账号密钥(适合CI/CD场景)

  1. 创建带Artifact Registry Writer权限的服务账号,下载JSON密钥文件
  2. 设置环境变量:
    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"
    
  3. 同样用oauth2accesstoken作为用户名执行上传命令即可

注意事项

  • 访问令牌有效期为1小时,长期上传需重新生成
  • 可通过gcloud artifacts repositories get-iam-policy [repo] --location=europe-west2再次验证账户权限绑定情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:12:36