Google Cloud Secret Manager API client library for Python that stores, manages, and secures access to application secrets
—
Core data structures and types used throughout the Google Cloud Secret Manager API. These proto-based message types provide the data model for secrets, versions, configuration options, and all request/response objects.
Represents a logical secret that can contain multiple versions. Secrets are containers for secret data with associated metadata, configuration, and access policies.
class Secret:
"""
A Secret is a logical secret whose value and versions can be accessed.
Attributes:
name (str): Output only. The resource name of the Secret in the format projects/*/secrets/*.
replication (Replication): Optional. Immutable. The replication policy of the secret data.
create_time (Timestamp): Output only. The time at which the Secret was created.
labels (Mapping[str, str]): The labels assigned to this Secret.
topics (Sequence[Topic]): Optional. A list of up to 10 Pub/Sub topics for notifications.
expire_time (Timestamp): Optional. Timestamp when the Secret is scheduled to expire.
ttl (Duration): Input only. The TTL for the Secret.
etag (str): Optional. Etag for optimistic concurrency control.
rotation (Rotation): Optional. Rotation policy and next rotation time.
version_aliases (Mapping[str, int]): Optional. Mapping from version alias to version number.
annotations (Mapping[str, str]): Optional. Custom metadata as key-value pairs.
customer_managed_encryption (CustomerManagedEncryption): Optional. Customer-managed encryption config.
tags (Mapping[str, str]): Optional. Resource tags for organizing and managing secrets.
version_destroy_ttl (Duration): Optional. TTL for destroying secret versions.
"""
name: str
replication: Replication
create_time: Timestamp
labels: Mapping[str, str]
topics: Sequence[Topic]
expire_time: Timestamp # oneof expiration
ttl: Duration # oneof expiration
etag: str
rotation: Rotation
version_aliases: Mapping[str, int]
annotations: Mapping[str, str]
customer_managed_encryption: CustomerManagedEncryption
tags: Mapping[str, str]
version_destroy_ttl: DurationUsage Example:
from google.cloud import secretmanager
from google.protobuf import duration_pb2
# Create a secret with basic configuration
secret = secretmanager.Secret()
# Set replication to automatic
secret.replication = secretmanager.Replication()
secret.replication.automatic = secretmanager.Replication.Automatic()
# Add labels for organization
secret.labels = {
'environment': 'production',
'team': 'backend',
'cost-center': 'engineering'
}
# Set TTL (optional)
secret.ttl = duration_pb2.Duration()
secret.ttl.seconds = 86400 * 30 # 30 days
# Add annotations (optional)
secret.annotations = {
'created-by': 'deployment-script',
'purpose': 'api-authentication'
}
# Add tags for resource organization (optional)
secret.tags = {
'billing': 'engineering-team',
'compliance': 'pci-dss'
}
# Set up version aliases (optional)
secret.version_aliases = {
'production': 1,
'staging': 2
}
# Set version destruction TTL (optional)
secret.version_destroy_ttl = duration_pb2.Duration()
secret.version_destroy_ttl.seconds = 86400 * 7 # 7 daysRepresents a version of a secret containing the actual secret data and metadata about that specific version.
class SecretVersion:
"""
A secret version resource in the Secret Manager API.
Attributes:
name (str): Output only. The resource name of the SecretVersion in format
projects/*/secrets/*/versions/*.
create_time (Timestamp): Output only. The time at which the SecretVersion was created.
destroy_time (Timestamp): Output only. The time this SecretVersion was destroyed.
state (State): Output only. The current state of the SecretVersion.
etag (str): Output only. Etag for optimistic concurrency control.
client_specified_payload_checksum (bool): Output only. True if payload checksum was specified.
scheduled_destroy_time (Timestamp): Optional. The time this version is scheduled for destruction.
customer_managed_encryption (CustomerManagedEncryptionStatus): Output only. Customer-managed encryption status for this version.
"""
class State(Enum):
"""The state of a SecretVersion."""
STATE_UNSPECIFIED = 0
ENABLED = 1 # Version is active and can be accessed
DISABLED = 2 # Version is disabled and cannot be accessed
DESTROYED = 3 # Version is destroyed and cannot be recovered
name: str
create_time: Timestamp
destroy_time: Timestamp
state: State
etag: str
client_specified_payload_checksum: bool
scheduled_destroy_time: Timestamp
customer_managed_encryption: CustomerManagedEncryptionStatusUsage Example:
# Check version state before accessing
if version.state == secretmanager.SecretVersion.State.ENABLED:
# Safe to access version data
access_request = secretmanager.AccessSecretVersionRequest()
access_request.name = version.name
response = client.access_secret_version(request=access_request)
elif version.state == secretmanager.SecretVersion.State.DISABLED:
print("Version is disabled - enable before accessing")
elif version.state == secretmanager.SecretVersion.State.DESTROYED:
print("Version is permanently destroyed")Contains the actual secret data and optional checksum for data integrity verification.
class SecretPayload:
"""
A secret payload resource in the Secret Manager API.
Attributes:
data (bytes): The secret data. Must be no larger than 64KiB.
data_crc32c (int): Optional. The CRC32C checksum of the secret data.
"""
data: bytes
data_crc32c: intUsage Example:
import crc32c
import json
# Create payload with string data
payload = secretmanager.SecretPayload()
secret_string = "my-api-key-12345"
payload.data = secret_string.encode('utf-8')
# Add checksum for integrity
payload.data_crc32c = crc32c.crc32c(payload.data)
# Create payload with JSON data
config_data = {
'api_key': 'secret-key',
'endpoint': 'https://api.example.com',
'timeout': 30
}
json_payload = secretmanager.SecretPayload()
json_payload.data = json.dumps(config_data).encode('utf-8')
json_payload.data_crc32c = crc32c.crc32c(json_payload.data)Defines how secret data is replicated across regions for availability and latency optimization.
class Replication:
"""
A policy that defines the replication and encryption configuration of data.
Attributes (oneof replication):
automatic (Automatic): Automatic replication across all regions.
user_managed (UserManaged): User-managed replication with specific regions.
"""
class Automatic:
"""
Automatic replication policy that replicates the Secret to all regions.
Attributes:
customer_managed_encryption (CustomerManagedEncryption): Optional. Encryption config.
"""
customer_managed_encryption: CustomerManagedEncryption
class UserManaged:
"""
User-managed replication policy that replicates the Secret to specific regions.
Attributes:
replicas (Sequence[Replica]): Required. The list of Replicas for this Secret.
"""
class Replica:
"""
Represents a Replica for a Secret.
Attributes:
location (str): Required. The canonical location name.
customer_managed_encryption (CustomerManagedEncryption): Optional. Encryption config.
"""
location: str
customer_managed_encryption: CustomerManagedEncryption
replicas: Sequence[Replica]
automatic: Automatic # oneof replication
user_managed: UserManaged # oneof replicationUsage Example:
# Automatic replication
replication = secretmanager.Replication()
replication.automatic = secretmanager.Replication.Automatic()
# User-managed replication with specific regions
replication = secretmanager.Replication()
replication.user_managed = secretmanager.Replication.UserManaged()
# Add replica for us-central1
replica1 = secretmanager.Replication.UserManaged.Replica()
replica1.location = "us-central1"
replication.user_managed.replicas.append(replica1)
# Add replica for europe-west1
replica2 = secretmanager.Replication.UserManaged.Replica()
replica2.location = "europe-west1"
replication.user_managed.replicas.append(replica2)Configuration for customer-managed encryption keys (CMEK) using Google Cloud KMS.
class CustomerManagedEncryption:
"""
Configuration for customer-managed encryption using Cloud KMS.
Attributes:
kms_key_name (str): Required. The resource name of the Cloud KMS key to use for encryption.
"""
kms_key_name: strUsage Example:
# Configure CMEK encryption
encryption = secretmanager.CustomerManagedEncryption()
encryption.kms_key_name = "projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key"
# Use with automatic replication
replication = secretmanager.Replication()
replication.automatic = secretmanager.Replication.Automatic()
replication.automatic.customer_managed_encryption = encryptionConfiguration for automatic secret rotation with specified timing and policies.
class Rotation:
"""
The rotation time and period for a Secret.
Attributes:
next_rotation_time (Timestamp): Optional. Timestamp when the next rotation should occur.
rotation_period (Duration): Optional. Input only. The Duration between rotation notifications.
"""
next_rotation_time: Timestamp
rotation_period: DurationUsage Example:
from google.protobuf import timestamp_pb2, duration_pb2
import datetime
# Set up rotation policy
rotation = secretmanager.Rotation()
# Rotate every 90 days
rotation.rotation_period = duration_pb2.Duration()
rotation.rotation_period.seconds = 86400 * 90 # 90 days
# Set next rotation time
next_rotation = datetime.datetime.now() + datetime.timedelta(days=90)
rotation.next_rotation_time = timestamp_pb2.Timestamp()
rotation.next_rotation_time.FromDatetime(next_rotation)Configuration for Pub/Sub notifications when secret operations occur.
class Topic:
"""
A Pub/Sub topic which Secret Manager will publish to when control plane events occur.
Attributes:
name (str): Required. The resource name of the Pub/Sub topic.
"""
name: strUsage Example:
# Configure Pub/Sub notifications
topic = secretmanager.Topic()
topic.name = "projects/my-project/topics/secret-events"
# Add to secret configuration
secret.topics.append(topic)Status information about secret replication across regions.
class ReplicationStatus:
"""
The replication status of a SecretVersion.
Attributes (oneof replication_status):
automatic (Automatic): Automatic replication status.
user_managed (UserManaged): User-managed replication status.
"""
class Automatic:
"""
The replication status of a SecretVersion using automatic replication.
Attributes:
customer_managed_encryption (CustomerManagedEncryptionStatus):
Output only. The customer-managed encryption status of the SecretVersion.
"""
customer_managed_encryption: CustomerManagedEncryptionStatus
class UserManaged:
"""
The replication status of a SecretVersion using user-managed replication.
Attributes:
replicas (Sequence[ReplicaStatus]): Output only. The list of replica statuses.
"""
class ReplicaStatus:
"""
The replication status of a SecretVersion.
Attributes:
location (str): Output only. The canonical location name.
customer_managed_encryption (CustomerManagedEncryptionStatus):
Output only. The customer-managed encryption status.
"""
location: str
customer_managed_encryption: CustomerManagedEncryptionStatus
replicas: Sequence[ReplicaStatus]
automatic: Automatic # oneof replication_status
user_managed: UserManaged # oneof replication_statusStatus of customer-managed encryption for a secret version.
class CustomerManagedEncryptionStatus:
"""
Describes the status of customer-managed encryption.
Attributes:
kms_key_version_name (str): Required. The resource name of the Cloud KMS
CryptoKey version used to encrypt the secret payload.
"""
kms_key_version_name: strclass SecretManagerServiceGrpcTransport:
"""Synchronous gRPC transport for Secret Manager."""
class SecretManagerServiceGrpcAsyncIOTransport:
"""Asynchronous gRPC transport for Secret Manager."""
class SecretManagerServiceRestTransport:
"""Synchronous REST transport for Secret Manager."""class ClientOptions:
"""
Client configuration options.
Attributes:
api_endpoint (str): The API endpoint.
client_cert_source (Callable): A callable for client certificate.
client_info (ClientInfo): The client information.
scopes (Sequence[str]): OAuth2 scopes for authentication.
quota_project_id (str): Project ID for quota attribution.
"""
api_endpoint: str
client_cert_source: Callable
client_info: ClientInfo
scopes: Sequence[str]
quota_project_id: strIterator for paginated secret listing results.
class ListSecretsPager:
"""
A pager for iterating through list_secrets requests.
This class provides an iterator interface for paginated results.
"""
def __iter__(self) -> Iterator[Secret]:
"""Iterate over secrets."""
...
def __next__(self) -> Secret:
"""Get next secret."""
...Iterator for paginated secret version listing results.
class ListSecretVersionsPager:
"""
A pager for iterating through list_secret_versions requests.
This class provides an iterator interface for paginated results.
"""
def __iter__(self) -> Iterator[SecretVersion]:
"""Iterate over secret versions."""
...
def __next__(self) -> SecretVersion:
"""Get next secret version."""
...class ListSecretsAsyncPager:
"""
Async pager for iterating through list_secrets requests.
This class provides an async iterator interface for paginated results.
"""
def __aiter__(self) -> AsyncIterator[Secret]:
"""Async iterate over secrets."""
...
async def __anext__(self) -> Secret:
"""Get next secret async."""
...
class ListSecretVersionsAsyncPager:
"""
Async pager for iterating through list_secret_versions requests.
This class provides an async iterator interface for paginated results.
"""
def __aiter__(self) -> AsyncIterator[SecretVersion]:
"""Async iterate over secret versions."""
...
async def __anext__(self) -> SecretVersion:
"""Get next secret version async."""
...from google.protobuf import timestamp_pb2
import datetime
# Convert datetime to protobuf timestamp
dt = datetime.datetime.now(datetime.timezone.utc)
timestamp = timestamp_pb2.Timestamp()
timestamp.FromDatetime(dt)
# Convert protobuf timestamp to datetime
dt_from_proto = timestamp.ToDatetime()
# Working with secret expiration
secret.expire_time = timestamp_pb2.Timestamp()
expiry_date = datetime.datetime.now() + datetime.timedelta(days=365)
secret.expire_time.FromDatetime(expiry_date)from google.protobuf import duration_pb2
# Set TTL to 30 days
secret.ttl = duration_pb2.Duration()
secret.ttl.seconds = 86400 * 30 # 30 days in seconds
# Set rotation period to 90 days
rotation.rotation_period = duration_pb2.Duration()
rotation.rotation_period.seconds = 86400 * 90 # 90 daysfrom google.protobuf import field_mask_pb2
# Update only specific fields
update_mask = field_mask_pb2.FieldMask()
update_mask.paths.extend(['labels', 'annotations'])
request = secretmanager.UpdateSecretRequest()
request.secret = updated_secret
request.update_mask = update_maskimport crc32c
def verify_payload_integrity(payload):
"""Verify payload data integrity using CRC32C."""
if payload.data_crc32c:
computed_crc = crc32c.crc32c(payload.data)
if computed_crc != payload.data_crc32c:
raise ValueError("Payload data integrity check failed")
return True
# Usage
response = client.access_secret_version(request=access_request)
verify_payload_integrity(response.payload)Install with Tessl CLI
npx tessl i tessl/pypi-google-cloud-secret-manager