【问题标题】:Permission to Google Cloud Storage via service account in Python通过 Python 中的服务帐户访问 Google Cloud Storage
【发布时间】:2019-07-25 18:33:20
【问题描述】:

我正在尝试获取服务帐户以在 Google Cloud Storage 中创建 Blob 来自 Python 脚本,但我遇到了凭据问题。

1) 我为我的项目创建服务帐户,然后下载 json 中的密钥文件:

"home/user/.config/gcloud/service_admin.json"

2) 我为服务帐户提供必要的凭据(通过子进程中的 gcloud)

 roles/viewer, roles/storage.admin,  roles/resourcemanager.projectCreator, roles/billing.user

那我想访问GCS中的一个bucket

from google.cloud import storage
import google.auth

credentials, project = google.auth.default()
client = storage.Client('myproject', credentials=credentials)
bucket = client.get_bucket('my_bucket')

不幸的是,这会导致:

google.api_core.exceptions.Forbidden: 403 GET
https://www.googleapis.com/storage/v1/b/my_bucket?projection=noAcl:
s_account@myproject.iam.gserviceaccount.com does not have
storage.buckets.get access to my_bucket

如果我设置环境变量,我的运气会好一些

export GOOGLE_APPLICATION_CREDENTIALS="home/user/.config/gcloud/service_admin.json"

然后重新运行脚本。但是,我希望这一切都在创建帐户并继续在存储桶中创建必要文件的脚本的一个实例中运行。如果我知道我的 json 凭证文件在哪里,我如何访问 my_bucket。

【问题讨论】:

    标签: google-cloud-platform google-cloud-storage google-cloud-python


    【解决方案1】:

    Documentation for Server to Server Authentication 试试这个例子:

    from google.cloud import storage
    
    # Explicitly use service account credentials by specifying the private key file.
    storage_client = storage.Client.from_service_account_json('service_account.json')
    
    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)
    

    这样,您可以直接在代码中指向包含服务帐户密钥的文件。

    【讨论】:

    • 这行得通!实际上我的错误是我指的是在以前的项目中创建的存储桶 [client.lookup_bucket('my_bucket') 现在已删除;因此许可问题]。
    猜你喜欢
    • 2020-07-13
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多