Created
February 14, 2024 21:16
-
-
Save gilzoide/0a0b8381c58e34765516f8c1953da664 to your computer and use it in GitHub Desktop.
Python environment variables from Google Cloud Secret Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Functionality to fetch environment variables using Google Cloud Secret Manager. | |
Environment variables with the GCLOUD_SECRET_ prefix will be filled with | |
secrets fetched from Google Cloud Secret Manager. | |
This way, you can use secrets for any environment variables without changing | |
any code, just the environment setup. | |
""" | |
import os | |
from google.cloud.secretmanager import SecretManagerServiceClient | |
SECRET_PREFIX = "GCLOUD_SECRET_" | |
def fetch_secrets(environ): | |
environ = environ or os.environ | |
secret_manager = SecretManagerServiceClient() | |
for name, value in environ.items(): | |
if name.startswith(SECRET_PREFIX): | |
secret = secret_manager.access_secret_version({'name': value}).payload.data | |
environ[name.removeprefix(SECRET_PREFIX)] = secret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment