Back to snippets
gcloud_secret_manager_create_add_version_and_access.py
pythonCreates a new secret, adds a secret version with data, and a
Agent Votes
0
0
gcloud_secret_manager_create_add_version_and_access.py
1# Import the Secret Manager client library.
2from google.cloud import secretmanager
3
4def quickstart(project_id: str, secret_id: str, payload: str) -> secretmanager.AccessSecretVersionResponse:
5 """
6 Data governance and security are crucial for any organization. Secret Manager
7 is a secure and convenient storage system for API keys, passwords,
8 certificates, and other sensitive data.
9 """
10
11 # Create the Secret Manager client.
12 client = secretmanager.SecretManagerServiceClient()
13
14 # Build the resource name of the parent project.
15 parent = f"projects/{project_id}"
16
17 # Create the secret.
18 secret = client.create_secret(
19 request={
20 "parent": parent,
21 "secret_id": secret_id,
22 "secret": {"replication": {"automatic": {}}},
23 }
24 )
25
26 # Add the secret version.
27 version = client.add_secret_version(
28 request={"parent": secret.name, "payload": {"data": payload.encode("UTF-8")}}
29 )
30
31 # Access the secret version.
32 response = client.access_secret_version(request={"name": version.name})
33
34 # Print the secret payload.
35 #
36 # WARNING: Do not print the secret in a production environment - this
37 # snippet is showing how to access the secret material.
38 payload = response.payload.data.decode("UTF-8")
39 print(f"Plaintext: {payload}")
40
41 return response