Google Cloud Secret Manager API client library for Python that stores, manages, and secures access to application secrets
—
Core secret lifecycle operations for creating, retrieving, updating, and deleting secrets in Google Cloud Secret Manager. These operations manage secret metadata, replication policies, and configuration settings.
Creates a new secret with specified configuration including replication policy, labels, and optional settings like TTL, expiration, and Pub/Sub notifications.
def create_secret(self, request: CreateSecretRequest = None, **kwargs) -> Secret:
"""
Creates a new Secret containing no SecretVersions.
Args:
request (CreateSecretRequest): The request object containing parent project,
secret_id, and secret configuration.
parent (str): Required. The resource name of the project associated with the
Secret, in the format projects/* or projects/*/locations/*.
secret_id (str): Required. This must be unique within the project.
secret (Secret): Required. A Secret with initial empty SecretVersion.
Returns:
Secret: The created Secret.
Raises:
google.api_core.exceptions.AlreadyExists: If secret_id already exists.
google.api_core.exceptions.InvalidArgument: If request is malformed.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
# Create secret with automatic replication
secret = secretmanager.Secret()
secret.replication = secretmanager.Replication()
secret.replication.automatic = secretmanager.Replication.Automatic()
# Add labels for organization
secret.labels = {
'environment': 'production',
'team': 'backend'
}
# Create request
request = secretmanager.CreateSecretRequest()
request.parent = "projects/my-project"
request.secret_id = "api-key"
request.secret = secret
# Create the secret
created_secret = client.create_secret(request=request)
print(f"Created secret: {created_secret.name}")Retrieves secret metadata and configuration without accessing the secret data itself. Returns information about replication, labels, creation time, and other metadata.
def get_secret(self, request: GetSecretRequest = None, **kwargs) -> Secret:
"""
Gets metadata for a given Secret.
Args:
request (GetSecretRequest): The request object.
name (str): Required. The resource name of the Secret, in the format
projects/*/secrets/* or projects/*/locations/*/secrets/*.
Returns:
Secret: The Secret metadata.
Raises:
google.api_core.exceptions.NotFound: If the secret does not exist.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
request = secretmanager.GetSecretRequest()
request.name = "projects/my-project/secrets/api-key"
secret = client.get_secret(request=request)
print(f"Secret created: {secret.create_time}")
print(f"Labels: {secret.labels}")
print(f"Replication policy: {secret.replication}")Updates secret metadata including labels, expiration settings, and Pub/Sub topic configurations. Cannot modify immutable properties like replication policy.
def update_secret(self, request: UpdateSecretRequest = None, **kwargs) -> Secret:
"""
Updates metadata of an existing Secret.
Args:
request (UpdateSecretRequest): The request object.
secret (Secret): Required. Secret with updated field values.
update_mask (FieldMask): Required. Specifies fields to be updated.
Returns:
Secret: The updated Secret.
Raises:
google.api_core.exceptions.NotFound: If the secret does not exist.
google.api_core.exceptions.InvalidArgument: If update_mask is invalid.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
from google.protobuf import field_mask_pb2
# Get current secret
get_request = secretmanager.GetSecretRequest()
get_request.name = "projects/my-project/secrets/api-key"
secret = client.get_secret(request=get_request)
# Update labels
secret.labels['updated'] = 'true'
secret.labels['version'] = '2.0'
# Create update request with field mask
request = secretmanager.UpdateSecretRequest()
request.secret = secret
request.update_mask = field_mask_pb2.FieldMask()
request.update_mask.paths.append('labels')
updated_secret = client.update_secret(request=request)
print(f"Updated secret: {updated_secret.name}")Permanently deletes a secret and all of its versions. This operation cannot be undone and immediately makes the secret and all its data inaccessible.
def delete_secret(self, request: DeleteSecretRequest = None, **kwargs) -> None:
"""
Deletes a Secret.
Args:
request (DeleteSecretRequest): The request object.
name (str): Required. The resource name of the Secret to delete in the format
projects/*/secrets/*.
etag (str): Optional. Etag of the Secret for optimistic concurrency control.
Returns:
None
Raises:
google.api_core.exceptions.NotFound: If the secret does not exist.
google.api_core.exceptions.FailedPrecondition: If etag doesn't match.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
request = secretmanager.DeleteSecretRequest()
request.name = "projects/my-project/secrets/old-api-key"
# Optional: Use etag for optimistic concurrency control
# request.etag = secret.etag
client.delete_secret(request=request)
print("Secret deleted successfully")Lists all secrets in a project with optional filtering and pagination. Returns secret metadata without accessing secret data.
def list_secrets(self, request: ListSecretsRequest = None, **kwargs) -> ListSecretsPager:
"""
Lists Secrets.
Args:
request (ListSecretsRequest): The request object.
parent (str): Required. The resource name of the project associated with the
Secrets, in the format projects/* or projects/*/locations/*.
page_size (int): Optional. The maximum number of results to return in a single page.
page_token (str): Optional. Pagination token.
filter (str): Optional. Filter string adhering to the filtering rules.
Returns:
ListSecretsPager: An iterator for paginated results.
Raises:
google.api_core.exceptions.InvalidArgument: If filter is malformed.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
# List all secrets
request = secretmanager.ListSecretsRequest()
request.parent = "projects/my-project"
for secret in client.list_secrets(request=request):
print(f"Secret: {secret.name}")
print(f" Created: {secret.create_time}")
print(f" Labels: {secret.labels}")
# List with filtering
request.filter = 'labels.environment="production"'
production_secrets = list(client.list_secrets(request=request))
print(f"Found {len(production_secrets)} production secrets")
# List with pagination
request = secretmanager.ListSecretsRequest()
request.parent = "projects/my-project"
request.page_size = 10
page_result = client.list_secrets(request=request)
first_page = list(page_result)
print(f"First page: {len(first_page)} secrets")Utility methods for constructing and parsing resource names:
@staticmethod
def secret_path(project: str, secret: str) -> str:
"""Returns a fully-qualified secret string."""
@staticmethod
def parse_secret_path(path: str) -> Dict[str, str]:
"""Parses a secret path into its component segments."""
@staticmethod
def topic_path(project: str, topic: str) -> str:
"""Returns a fully-qualified Pub/Sub topic string."""
@staticmethod
def parse_topic_path(path: str) -> Dict[str, str]:
"""Parses a topic path into its component segments."""
@staticmethod
def common_project_path(project: str) -> str:
"""Returns a fully-qualified project string."""
@staticmethod
def common_location_path(project: str, location: str) -> str:
"""Returns a fully-qualified location string."""
@staticmethod
def parse_common_project_path(path: str) -> Dict[str, str]:
"""Parses a project path into its component segments."""
@staticmethod
def parse_common_location_path(path: str) -> Dict[str, str]:
"""Parses a location path into its component segments."""Usage Example:
# Construct secret path
secret_path = client.secret_path("my-project", "api-key")
print(secret_path) # "projects/my-project/secrets/api-key"
# Parse secret path
components = client.parse_secret_path(secret_path)
print(components) # {'project': 'my-project', 'secret': 'api-key'}
# Construct topic path for Pub/Sub notifications
topic_path = client.topic_path("my-project", "secret-events")
print(topic_path) # "projects/my-project/topics/secret-events"
# Construct location path
location_path = client.common_location_path("my-project", "us-central1")
print(location_path) # "projects/my-project/locations/us-central1"
# Parse paths
topic_components = client.parse_topic_path(topic_path)
print(topic_components) # {'project': 'my-project', 'topic': 'secret-events'}class CreateSecretRequest:
"""
Request message for SecretManagerService.CreateSecret.
Attributes:
parent (str): Required. The project resource name.
secret_id (str): Required. The secret ID.
secret (Secret): Required. A Secret with initial configuration.
"""
parent: str
secret_id: str
secret: Secretclass GetSecretRequest:
"""
Request message for SecretManagerService.GetSecret.
Attributes:
name (str): Required. The secret resource name.
"""
name: strclass UpdateSecretRequest:
"""
Request message for SecretManagerService.UpdateSecret.
Attributes:
secret (Secret): Required. Secret with updated values.
update_mask (FieldMask): Required. Fields to update.
"""
secret: Secret
update_mask: field_mask_pb2.FieldMaskclass DeleteSecretRequest:
"""
Request message for SecretManagerService.DeleteSecret.
Attributes:
name (str): Required. The secret resource name.
etag (str): Optional. Etag for optimistic concurrency control.
"""
name: str
etag: strclass ListSecretsRequest:
"""
Request message for SecretManagerService.ListSecrets.
Attributes:
parent (str): Required. The project resource name.
page_size (int): Optional. Maximum results per page.
page_token (str): Optional. Pagination token.
filter (str): Optional. Filter expression.
"""
parent: str
page_size: int
page_token: str
filter: strclass ListSecretsResponse:
"""
Response message for SecretManagerService.ListSecrets.
Attributes:
secrets (Sequence[Secret]): List of secrets.
next_page_token (str): Token for next page.
"""
secrets: Sequence[Secret]
next_page_token: strUtility methods for working with Google Cloud locations when managing secrets across regions.
Retrieves information about a specific Google Cloud location.
def get_location(self, request: GetLocationRequest = None, **kwargs) -> Location:
"""
Gets information about a location.
Args:
request (GetLocationRequest): The request object.
name (str): Required. Resource name for the location.
Returns:
Location: The location information.
Raises:
google.api_core.exceptions.NotFound: If the location does not exist.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Lists available Google Cloud locations for the service.
def list_locations(self, request: ListLocationsRequest = None, **kwargs) -> ListLocationsResponse:
"""
Lists information about the supported locations for this service.
Args:
request (ListLocationsRequest): The request object.
name (str): Required. The resource name of the project.
filter (str): Optional. A filter for the locations.
page_size (int): Optional. Maximum results per page.
page_token (str): Optional. Pagination token.
Returns:
ListLocationsResponse: The list of locations.
Raises:
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
# List available locations
request = locations_pb2.ListLocationsRequest()
request.name = "projects/my-project"
locations = client.list_locations(request=request)
for location in locations:
print(f"Location: {location.name}")
print(f" Display name: {location.display_name}")
print(f" Location ID: {location.location_id}")Install with Tessl CLI
npx tessl i tessl/pypi-google-cloud-secret-manager