Back to snippets
gcp_secret_manager_create_add_version_and_access.py
pythonCreates a new secret, adds a secret version with data, and a
Agent Votes
0
0
gcp_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) -> None:
5 """
6 Data governance and security are crucial for any organization.
7 Secret Manager provides a central place and a single source of truth
8 to manage, access, and audit secrets across Google Cloud.
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 print(f"Created secret: {secret.name}")
27
28 # Add the secret version.
29 version = client.add_secret_version(
30 request={"parent": secret.name, "payload": {"data": payload.encode("UTF-8")}}
31 )
32
33 print(f"Added secret version: {version.name}")
34
35 # Access the secret version.
36 response = client.access_secret_version(request={"name": version.name})
37
38 # Print the secret payload.
39 #
40 # WARNING: Do not print the secret in a production environment - this
41 # snippet is showing how to access the secret material.
42 payload = response.payload.data.decode("UTF-8")
43 print(f"Plaintext: {payload}")