Last active
April 23, 2023 16:28
-
-
Save jaybaker/1a79217c4cbef0c0dd78882ef68776ab to your computer and use it in GitHub Desktop.
Load Google Cloud Secrets from python notebook
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
| """ | |
| This gist is intended to be loaded into a python notebook via wget. | |
| It is used to retrieve a secret from the google cloud. | |
| See https://cloud.google.com/secret-manager/docs/reference/libraries#client-libraries-install-python | |
| Usage: | |
| 1. !wget | |
| 2. !pip install google-cloud-secret-manager | |
| 3. import load_secret | |
| 4. secret = load_secret.get_secret(name, project=project_id) | |
| """ | |
| import json | |
| from google.cloud import secretmanager | |
| def get_secret(name, version='latest', project=None): | |
| """Get a secret value | |
| Args: | |
| name - the name of the secret | |
| version - an optional version | |
| project - the name of the cloud project | |
| Returns: | |
| value - the value of the secret or None | |
| The value will be converted to dict if it is JSON. | |
| Uses Google Secret Manager | |
| https://cloud.google.com/secret-manager | |
| https://googleapis.dev/python/secretmanager/latest/gapic/v1/api.html | |
| supporting a limited and targeted subset of that api. | |
| Authentication: | |
| In cloud environments the principal under use must have | |
| the secretmanager.secretAccessor role. | |
| """ | |
| if project: | |
| client = secretmanager.SecretManagerServiceClient() | |
| request = dict(name=client.secret_version_path(project, name, version)) | |
| response = client.access_secret_version(request=request) | |
| payload = response.payload.data.decode('UTF-8') | |
| try: | |
| # try to treat the value as json | |
| payload = json.loads(payload) | |
| except Exception as e: | |
| pass | |
| return payload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment