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

Colab中调用Google Compute Engine元数据服务失败求助

解决Google Cloud存储桶操作触发的Metadata服务404错误

错误现象

执行列出存储桶Blobs、上传/下载数据等操作时,触发如下错误:

TransportError: ("Failed to retrieve
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/?recursive=true
from the Google Compute Engine metadata service. Status: 404
Response:
b''", <google.auth.transport.requests._Response object at 0x796af24222f0>)

可复现问题的简单代码:

storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name='my_bucket')
list(bucket.list_blobs())

解决方案

  • 确认运行环境:该错误本质是代码默认尝试访问GCE元数据服务获取认证凭证,但这个服务仅在GCP Compute Engine内部环境可访问。如果是本地开发机或非GCP环境运行代码,必须手动指定认证凭证。
  • 手动指定服务账号密钥:
    1. 在GCP控制台创建具备存储桶操作权限的服务账号,下载其JSON格式密钥文件。
    2. 方案一:在代码中直接指定密钥路径
      from google.cloud import storage
      
      # 替换为你的密钥文件路径
      storage_client = storage.Client.from_service_account_json('/path/to/service-account-key.json')
      bucket = storage_client.bucket(bucket_name='my_bucket')
      list(bucket.list_blobs())
      
    3. 方案二:通过环境变量指定密钥(无需修改代码)
      在终端执行以下命令后再运行代码:
      export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"
      
  • GCE实例环境排查(如果在GCE运行):
    • 确认GCE实例已关联具备存储桶读写权限的服务账号;
    • 在实例内部执行以下命令测试元数据服务是否正常:
      curl http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/?recursive=true -H "Metadata-Flavor: Google"
      
      若返回404,检查实例的元数据服务是否被禁用,或联系GCP支持排查实例配置问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:46:09