通过 Python 中的服务帐户访问 Google Cloud Storage 的权限
Permission to Google Cloud Storage via service account in Python
我正在尝试获取服务帐户以在 Google 云存储中创建 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 中的一个存储桶
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。
试试这个来自 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)
这样您就可以在代码中直接指向包含服务帐户密钥的文件。
我正在尝试获取服务帐户以在 Google 云存储中创建 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 中的一个存储桶
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。
试试这个来自 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)
这样您就可以在代码中直接指向包含服务帐户密钥的文件。