问题描述
我为秘密服务经理配置了所需的角色,但是当我尝试通过 python 3.7 代码访问它们时,我收到错误 403 访问被拒绝:
google.api_core.exceptions.PermissionDenied: 403 Permission 'secretmanager.secrets.list' denied for resource 'projects/projectid' (or it may not exist)
如果我使用命令行访问它们,它会起作用:
gcloud secrets list
这是python代码:
# Build the resource name of the parent project.
parent = f"projects/projectid"
# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient()
# List all secrets.
for secret in client.list_secrets(request={"parent": parent}):
print("Found secret: {}".format(secret.name))
解决方法
你的代码对我有用。
BILLING="..."
PROJECT="..."
ACCOUNT="..."
SECRET="test"
gcloud projects create ${PROJECT}
gcloud beta billing projects link ${PROJECT} \
--billing-account=${BILLING}
gcloud services enable secretmanager.googleapis.com \
--project=${PROJECT}
gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}
EMAIL="${ROBOT}@${PROJECT}.iam.gserviceaccount.com"
gcloud iam service-accounts keys create ${PWD}/${ACCOUNT}.json \
--iam-account=${EMAIL}
# See note: the minimum role that includes the perm to list secrets
gcloud projects add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${EMAIL} \
--role=roles/secretmanager.viewer
echo "test" > test
gcloud secrets create ${SECRET} \
--data-file="test" \
--project=${PROJECT}
python3 -m venv venv
source venv/bin/activate
python3 -m pip install google-cloud-secret-manager
# Both required by the app
export PROJECT
export GOOGLE_APPLICATION_CREDENTIALS=${PWD}/${ACCOUNT}.json
python main.py
产量:
Found secret: projects/12345678912/secrets/test
main.py:
from google.cloud import secretmanager
import os
project=os.getenv("PROJECT")
client = secretmanager.SecretManagerServiceClient()
parent = f"projects/{project}"
secrets = client.list_secrets(request={
"parent":parent,})
for secret in secrets:
print("Found secret: {}".format(secret.name))
注意 roles/secretmanager.viewer
是唯一包含列出 secretmanager.secrets.list
(link) 所需权限的预定义角色