通过Python中的服务帐户访问Google Cloud Storage的权限

Mik*_*ike 6 google-cloud-storage google-cloud-platform google-cloud-python

我正在尝试获取一个服务帐户,以便从 Python 脚本中在 Google Cloud Storage 中创建 blob,但我遇到了凭据问题。

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

"home/user/.config/gcloud/service_admin.json"
Run Code Online (Sandbox Code Playgroud)

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

 roles/viewer, roles/storage.admin,  roles/resourcemanager.projectCreator, roles/billing.user
Run Code Online (Sandbox Code Playgroud)

然后我想访问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')
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会导致:

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
Run Code Online (Sandbox Code Playgroud)

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

export GOOGLE_APPLICATION_CREDENTIALS="home/user/.config/gcloud/service_admin.json"
Run Code Online (Sandbox Code Playgroud)

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

Tas*_*sZG 7

尝试服务器到服务器身份验证文档中的示例:

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)
Run Code Online (Sandbox Code Playgroud)

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