Introduction

In previous lessons, we explored the fundamentals of managing sensitive information using Google Cloud's secrets management services. In this lesson, we will dive into advanced features that help you organize, control, and manage the lifecycle of your secrets more effectively. We will cover how to list all secrets, use labels for organization, manage secret versions, and handle secret deletion and destruction. These capabilities are essential for maintaining security and operational efficiency in your cloud environment.

Listing All Secrets

Google Cloud Secret Manager allows you to list all secrets within a project. This is useful for inventory, auditing, and management purposes. You can retrieve a list of all secrets and display their names as follows:

from google.cloud import secretmanager

# Initialize the Secret Manager client
client = secretmanager.SecretManagerServiceClient()

# Replace with your Google Cloud project ID
project_id = "your-project-id"
parent = f"projects/{project_id}"

# List all secrets in the project
for secret in client.list_secrets(request={"parent": parent}):
    print("Secret Name:", secret.name)

Output:

Secret Name: projects/your-project-id/secrets/api-key
Secret Name: projects/your-project-id/secrets/database-password
Secret Name: projects/your-project-id/secrets/my-secret

This code lists all secrets in the specified project, allowing you to see which secrets are currently managed.

Labeling and Unlabeling Secrets

Labels in Google Cloud Secret Manager are key-value pairs that help you organize and categorize your secrets. You can add, update, or remove labels to make it easier to manage secrets across different environments or applications.

To add or update labels on a secret:

from google.cloud import secretmanager
from google.protobuf import field_mask_pb2

client = secretmanager.SecretManagerServiceClient()
secret_name = f"projects/{project_id}/secrets/my-secret"

# Define new labels
labels = {
    "environment": "production",
    "team": "devops"
}

# Update the secret with new labels
secret = {"name": secret_name, "labels": labels}
update_mask = field_mask_pb2.FieldMask(paths=["labels"])
updated_secret = client.update_secret(secret=secret, update_mask=update_mask)
print("Updated Labels:", updated_secret.labels)

Output:

Updated Labels: {'environment': 'production', 'team': 'devops'}

The update_mask parameter is crucial in this operation. It's a field mask that specifies which fields of the secret should be updated during the operation. By setting paths=["labels"], we're telling Google Cloud to only update the labels field and leave all other secret properties (such as replication settings, TTL, etc.) unchanged. This prevents accidental modification of other secret attributes and ensures that only the intended changes are applied.

To remove a label, simply omit it from the labels dictionary and update the secret:

# Remove the 'team' label
labels = {
    "environment": "production"
}

secret = {"name": secret_name, "labels": labels}
update_mask = field_mask_pb2.FieldMask(paths=["labels"])
updated_secret = client.update_secret(secret=secret, update_mask=update_mask)
print("Labels after removal:", updated_secret.labels)

Output:

Labels after removal: {'environment': 'production'}

Using labels helps you filter and manage secrets according to your organizational needs.

Working with Secret Versions

Each secret in Google Cloud Secret Manager can have multiple versions. Versions allow you to rotate secrets and maintain a history of previous values. The latest alias always points to the most recent enabled version.

To list all versions of a secret:

from google.cloud import secretmanager

client = secretmanager.SecretManagerServiceClient()
secret_name = f"projects/{project_id}/secrets/my-secret"

# List all versions of the secret
for version in client.list_secret_versions(request={"parent": secret_name}):
    print("Version Name:", version.name, "State:", version.state.name)

Output:

Version Name: projects/your-project-id/secrets/my-secret/versions/1 State: ENABLED
Version Name: projects/your-project-id/secrets/my-secret/versions/2 State: ENABLED
Version Name: projects/your-project-id/secrets/my-secret/versions/3 State: ENABLED

To access the value of a specific version or the latest version:

# Access the latest version
latest_version_name = f"{secret_name}/versions/latest"
response = client.access_secret_version(request={"name": latest_version_name})
print("Latest Secret Value:", response.payload.data.decode("UTF-8"))

# Access a specific version (e.g., version 1)
version_1_name = f"{secret_name}/versions/1"
response = client.access_secret_version(request={"name": version_1_name})
print("Version 1 Secret Value:", response.payload.data.decode("UTF-8"))

Output:

Latest Secret Value: my-updated-secret-value
Version 1 Secret Value: my-original-secret-value

Managing versions allows you to rotate secrets safely and roll back to previous values if needed.

Secret Deletion and Destruction

In Google Cloud Secret Manager, you can delete an entire secret or destroy individual secret versions. Deleting a secret removes all its versions and metadata, and this action is irreversible. Destroying a secret version permanently removes only that specific version, while the secret and its other versions remain intact.

To delete a secret:

from google.cloud import secretmanager

client = secretmanager.SecretManagerServiceClient()
secret_name = f"projects/{project_id}/secrets/my-secret"

# Delete the secret (cannot be undone)
client.delete_secret(request={"name": secret_name})
print("Secret deleted.")

Output:

Secret deleted.

To destroy a specific secret version:

version_name = f"{secret_name}/versions/1"

# Destroy the secret version (cannot be undone)
client.destroy_secret_version(request={"name": version_name})
print("Secret version destroyed.")

Output:

Secret version destroyed.

Note that once a secret or secret version is deleted or destroyed, it cannot be recovered. Plan carefully before performing these actions.

Summary

In this lesson, we explored advanced features of Google Cloud Secret Manager, including listing secrets, organizing them with labels, managing secret versions, and handling deletion and destruction. Mastering these features enables you to maintain a secure, organized, and efficient approach to managing sensitive information in your cloud environment. Now, it's time to put these concepts into practice with hands-on exercises!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal