api - python 3.7 无法访问谷歌秘密服务管理器
问题描述
我为秘密服务经理配置了所需的角色,但是当我尝试通过 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
主要.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))
NOTE
roles/secretmanager.viewer
是唯一包含列出所需权限的预定义角色secretmanager.secrets.list
(链接)
推荐阅读
- hazelcast - 如何使用谓词从 Hazelcast IMap 中获取值?
- php - {} 在 php 中包裹我的变量是否会降低 sql 注入风险?
- android - 为什么我不能对 TextView textColor 使用数据绑定?
- azure-functions - 如何从 Azure Functions 调用 Microsoft Graph
- javascript - 配置 Jest 以支持 Typescript (NodeJs)
- swift - 一种方法如何同时被称为乘法?
- mysql - 使用第一个查询的结果作为第二个查询中的变量触发
- android-studio - 在 Android Studo 中添加文本框
- postgresql - Postgres 在文本字段中转义单引号和双引号
- c# - 无法从 .net core Web 应用程序调用 .net core 进程