从这个开始:
- 用户拥有自己的谷歌用户帐户,这些帐户是通过本地设置的
gcloud 登录
- 应用程序以通常的方式使用 gcp API - 默认情况下它将查找 GOOGLE_APPLICATION_CREDENTIALS、GCE 角色、服务帐户,或使用本地用户 gcloud 配置的凭据
- 当用户在本地运行它时,它将使用自己的用户帐户,当在 gcp 中运行时,它将使用服务帐户
- 用户的帐户还可以模拟该服务
帐户。因此,当在本地运行应用程序时,用户首先执行以下操作
gcloud config set
auth/impersonate_service_account [SA_FULL_EMAIL]
它可以运行
具有与在开发环境中运行的相同的信用 - 无需下载任何密钥
现在可以了。但我也希望能够在容器中本地运行应用程序。使用 docker/docker-compose/minikube/etc 如何才能模拟服务帐户?
容器需要访问gcloud https://www.jhanley.com/google-cloud-where-are-my-credentials-stored/信用,并且在应用程序以某种方式启动之前,它也需要在会话中设置模拟。这不能在代码中完成 - 应用程序应该正常使用 API,而不必做任何不同的事情。
编辑:
当应用程序在开发或生产 GCP 帐户/项目中运行时,它们在具有该特定应用程序的正确范围权限的服务帐户的上下文中运行。开发人员自己的用户帐户对开发环境具有广泛的权限。在本地运行时,使用与应用程序在开发环境中运行相同的服务帐户运行而不是开发人员自己的用户帐户非常有用
实现此目的的正确方法是 Google Cloud 提供的 Secret Manager。
- 在您的 Google Cloud 帐户中激活 Secret Manager API。
- 使用 GC UI 或 sdk 创建秘密数据和相关负载。
- 在您的 settings.py 中使用以下函数和您的项目 ID。
- 授予您的服务帐户访问 Secrets 的权限(如果它还没有访问权限)
- 使用 Secret Manager 访问代码中的有效负载,而无需显式公开有效负载。
def access_secret_version(secret_id):
"""
Access the payload for the given secret version if one exists. The version
can be a version number as a string (e.g. "5") or an alias (e.g. "latest").
"""
project_id = PROJECT_ID
version_id = 1
# Import the Secret Manager client library.
from google.cloud import secretmanager_v1beta1 as secretmanager
# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient()
# Build the resource name of the secret version.
name = client.secret_version_path(project_id, secret_id, version_id)
# Access the secret version.
response = client.access_secret_version(name)
# Print the secret payload.
#
# WARNING: Do not print the secret in a production environment - this
# snippet is showing how to access the secret material.
payload = response.payload.data.decode('UTF-8')
# logging.info('Plaintext: {}'.format(payload))
logging.info('Secret accessed for :' + secret_id)
return payload
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)