Google Cloud Secret Manager API client library for Python that stores, manages, and secures access to application secrets
—
Management of secret versions and access to secret data. Secret versions contain the actual secret data and can be in different states (enabled, disabled, destroyed). Each secret can have multiple versions, allowing for secret rotation and rollback capabilities.
Creates a new version of an existing secret with the provided secret data. New versions are automatically enabled and become the latest version.
def add_secret_version(self, request: AddSecretVersionRequest = None, **kwargs) -> SecretVersion:
"""
Creates a new SecretVersion containing secret data and attaches it to an existing Secret.
Args:
request (AddSecretVersionRequest): The request object.
parent (str): Required. The resource name of the Secret to associate with the
SecretVersion in the format projects/*/secrets/*.
payload (SecretPayload): Required. The secret payload containing the secret data.
Returns:
SecretVersion: The created SecretVersion.
Raises:
google.api_core.exceptions.NotFound: If the parent secret does not exist.
google.api_core.exceptions.InvalidArgument: If payload is invalid.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
# Create payload with secret data
payload = secretmanager.SecretPayload()
payload.data = b"new-api-key-v2"
# Add version to existing secret
request = secretmanager.AddSecretVersionRequest()
request.parent = "projects/my-project/secrets/api-key"
request.payload = payload
version = client.add_secret_version(request=request)
print(f"Created version: {version.name}")
print(f"State: {version.state}")Gets metadata for a specific secret version without accessing the secret data. Returns version state, creation time, and other metadata.
def get_secret_version(self, request: GetSecretVersionRequest = None, **kwargs) -> SecretVersion:
"""
Gets metadata for a given SecretVersion.
Args:
request (GetSecretVersionRequest): The request object.
name (str): Required. The resource name of the SecretVersion in the format
projects/*/secrets/*/versions/* or projects/*/secrets/*/versions/latest.
Returns:
SecretVersion: The SecretVersion metadata.
Raises:
google.api_core.exceptions.NotFound: If the secret version does not exist.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
# Get specific version
request = secretmanager.GetSecretVersionRequest()
request.name = "projects/my-project/secrets/api-key/versions/1"
version = client.get_secret_version(request=request)
print(f"Version state: {version.state}")
print(f"Created: {version.create_time}")
# Get latest version
request.name = "projects/my-project/secrets/api-key/versions/latest"
latest_version = client.get_secret_version(request=request)
print(f"Latest version: {latest_version.name}")Retrieves the actual secret data from a secret version. This is the primary method for reading secret values.
def access_secret_version(self, request: AccessSecretVersionRequest = None, **kwargs) -> AccessSecretVersionResponse:
"""
Accesses a SecretVersion containing the secret data.
Args:
request (AccessSecretVersionRequest): The request object.
name (str): Required. The resource name of the SecretVersion in the format
projects/*/secrets/*/versions/* or projects/*/secrets/*/versions/latest.
Returns:
AccessSecretVersionResponse: Response containing the secret payload.
Raises:
google.api_core.exceptions.NotFound: If the secret version does not exist.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
google.api_core.exceptions.FailedPrecondition: If version is disabled or destroyed.
"""Usage Example:
# Access latest version data
request = secretmanager.AccessSecretVersionRequest()
request.name = "projects/my-project/secrets/api-key/versions/latest"
response = client.access_secret_version(request=request)
secret_data = response.payload.data.decode('utf-8')
print(f"Secret value: {secret_data}")
# Access specific version
request.name = "projects/my-project/secrets/api-key/versions/1"
response = client.access_secret_version(request=request)
print(f"Version 1 data: {response.payload.data}")
# Check data integrity with CRC32C
if response.payload.data_crc32c:
import crc32c
computed_crc = crc32c.crc32c(response.payload.data)
if computed_crc != response.payload.data_crc32c:
raise ValueError("Data integrity check failed")Lists all versions of a secret with optional filtering and pagination. Returns version metadata without accessing secret data.
def list_secret_versions(self, request: ListSecretVersionsRequest = None, **kwargs) -> ListSecretVersionsPager:
"""
Lists SecretVersions.
Args:
request (ListSecretVersionsRequest): The request object.
parent (str): Required. The resource name of the Secret associated with the
SecretVersions to list, in the format projects/*/secrets/*.
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:
ListSecretVersionsPager: An iterator for paginated results.
Raises:
google.api_core.exceptions.NotFound: If the parent secret does not exist.
google.api_core.exceptions.InvalidArgument: If filter is malformed.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
# List all versions
request = secretmanager.ListSecretVersionsRequest()
request.parent = "projects/my-project/secrets/api-key"
for version in client.list_secret_versions(request=request):
print(f"Version: {version.name}")
print(f" State: {version.state}")
print(f" Created: {version.create_time}")
# List only enabled versions
request.filter = 'state="ENABLED"'
enabled_versions = list(client.list_secret_versions(request=request))
print(f"Enabled versions: {len(enabled_versions)}")Enables a disabled secret version, making it accessible for reading secret data.
def enable_secret_version(self, request: EnableSecretVersionRequest = None, **kwargs) -> SecretVersion:
"""
Enables a SecretVersion.
Args:
request (EnableSecretVersionRequest): The request object.
name (str): Required. The resource name of the SecretVersion to enable in the
format projects/*/secrets/*/versions/*.
etag (str): Optional. Etag for optimistic concurrency control.
Returns:
SecretVersion: The enabled SecretVersion.
Raises:
google.api_core.exceptions.NotFound: If the secret version does not exist.
google.api_core.exceptions.FailedPrecondition: If version is destroyed.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
request = secretmanager.EnableSecretVersionRequest()
request.name = "projects/my-project/secrets/api-key/versions/1"
version = client.enable_secret_version(request=request)
print(f"Enabled version: {version.name}")
print(f"New state: {version.state}")Disables a secret version, preventing access to its secret data while preserving the version for potential re-enabling.
def disable_secret_version(self, request: DisableSecretVersionRequest = None, **kwargs) -> SecretVersion:
"""
Disables a SecretVersion.
Args:
request (DisableSecretVersionRequest): The request object.
name (str): Required. The resource name of the SecretVersion to disable in the
format projects/*/secrets/*/versions/*.
etag (str): Optional. Etag for optimistic concurrency control.
Returns:
SecretVersion: The disabled SecretVersion.
Raises:
google.api_core.exceptions.NotFound: If the secret version does not exist.
google.api_core.exceptions.FailedPrecondition: If version is destroyed.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
request = secretmanager.DisableSecretVersionRequest()
request.name = "projects/my-project/secrets/api-key/versions/1"
version = client.disable_secret_version(request=request)
print(f"Disabled version: {version.name}")
print(f"New state: {version.state}")Permanently destroys a secret version and its data. This operation cannot be undone and immediately makes the version data inaccessible.
def destroy_secret_version(self, request: DestroySecretVersionRequest = None, **kwargs) -> SecretVersion:
"""
Destroys a SecretVersion.
Args:
request (DestroySecretVersionRequest): The request object.
name (str): Required. The resource name of the SecretVersion to destroy in the
format projects/*/secrets/*/versions/*.
etag (str): Optional. Etag for optimistic concurrency control.
Returns:
SecretVersion: The destroyed SecretVersion.
Raises:
google.api_core.exceptions.NotFound: If the secret version does not exist.
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
"""Usage Example:
request = secretmanager.DestroySecretVersionRequest()
request.name = "projects/my-project/secrets/old-api-key/versions/1"
version = client.destroy_secret_version(request=request)
print(f"Destroyed version: {version.name}")
print(f"State: {version.state}")
print(f"Destroy time: {version.destroy_time}")@staticmethod
def secret_version_path(project: str, secret: str, secret_version: str) -> str:
"""Returns a fully-qualified secret version string."""
@staticmethod
def parse_secret_version_path(path: str) -> Dict[str, str]:
"""Parses a secret version path into its component segments."""Usage Example:
# Construct version path
version_path = client.secret_version_path("my-project", "api-key", "1")
print(version_path) # "projects/my-project/secrets/api-key/versions/1"
# Parse version path
components = client.parse_secret_version_path(version_path)
print(components) # {'project': 'my-project', 'secret': 'api-key', 'secret_version': '1'}class AddSecretVersionRequest:
"""
Request message for SecretManagerService.AddSecretVersion.
Attributes:
parent (str): Required. The secret resource name.
payload (SecretPayload): Required. The secret data.
"""
parent: str
payload: SecretPayloadclass GetSecretVersionRequest:
"""
Request message for SecretManagerService.GetSecretVersion.
Attributes:
name (str): Required. The secret version resource name.
"""
name: strclass AccessSecretVersionRequest:
"""
Request message for SecretManagerService.AccessSecretVersion.
Attributes:
name (str): Required. The secret version resource name.
"""
name: strclass AccessSecretVersionResponse:
"""
Response message for SecretManagerService.AccessSecretVersion.
Attributes:
name (str): The secret version resource name.
payload (SecretPayload): The secret payload.
"""
name: str
payload: SecretPayloadclass ListSecretVersionsRequest:
"""
Request message for SecretManagerService.ListSecretVersions.
Attributes:
parent (str): Required. The secret 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 ListSecretVersionsResponse:
"""
Response message for SecretManagerService.ListSecretVersions.
Attributes:
versions (Sequence[SecretVersion]): List of secret versions.
next_page_token (str): Token for next page.
total_size (int): Total number of versions.
"""
versions: Sequence[SecretVersion]
next_page_token: str
total_size: intclass EnableSecretVersionRequest:
"""
Request message for SecretManagerService.EnableSecretVersion.
Attributes:
name (str): Required. The secret version resource name.
etag (str): Optional. Etag for optimistic concurrency control.
"""
name: str
etag: strclass DisableSecretVersionRequest:
"""
Request message for SecretManagerService.DisableSecretVersion.
Attributes:
name (str): Required. The secret version resource name.
etag (str): Optional. Etag for optimistic concurrency control.
"""
name: str
etag: strclass DestroySecretVersionRequest:
"""
Request message for SecretManagerService.DestroySecretVersion.
Attributes:
name (str): Required. The secret version resource name.
etag (str): Optional. Etag for optimistic concurrency control.
"""
name: str
etag: strInstall with Tessl CLI
npx tessl i tessl/pypi-google-cloud-secret-manager