0
# Data Types and Models
1
2
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.
3
4
## Core Data Types
5
6
### Secret
7
8
Represents a logical secret that can contain multiple versions. Secrets are containers for secret data with associated metadata, configuration, and access policies.
9
10
```python { .api }
11
class Secret:
12
"""
13
A Secret is a logical secret whose value and versions can be accessed.
14
15
Attributes:
16
name (str): Output only. The resource name of the Secret in the format projects/*/secrets/*.
17
replication (Replication): Optional. Immutable. The replication policy of the secret data.
18
create_time (Timestamp): Output only. The time at which the Secret was created.
19
labels (Mapping[str, str]): The labels assigned to this Secret.
20
topics (Sequence[Topic]): Optional. A list of up to 10 Pub/Sub topics for notifications.
21
expire_time (Timestamp): Optional. Timestamp when the Secret is scheduled to expire.
22
ttl (Duration): Input only. The TTL for the Secret.
23
etag (str): Optional. Etag for optimistic concurrency control.
24
rotation (Rotation): Optional. Rotation policy and next rotation time.
25
version_aliases (Mapping[str, int]): Optional. Mapping from version alias to version number.
26
annotations (Mapping[str, str]): Optional. Custom metadata as key-value pairs.
27
customer_managed_encryption (CustomerManagedEncryption): Optional. Customer-managed encryption config.
28
tags (Mapping[str, str]): Optional. Resource tags for organizing and managing secrets.
29
version_destroy_ttl (Duration): Optional. TTL for destroying secret versions.
30
"""
31
name: str
32
replication: Replication
33
create_time: Timestamp
34
labels: Mapping[str, str]
35
topics: Sequence[Topic]
36
expire_time: Timestamp # oneof expiration
37
ttl: Duration # oneof expiration
38
etag: str
39
rotation: Rotation
40
version_aliases: Mapping[str, int]
41
annotations: Mapping[str, str]
42
customer_managed_encryption: CustomerManagedEncryption
43
tags: Mapping[str, str]
44
version_destroy_ttl: Duration
45
```
46
47
**Usage Example:**
48
49
```python
50
from google.cloud import secretmanager
51
from google.protobuf import duration_pb2
52
53
# Create a secret with basic configuration
54
secret = secretmanager.Secret()
55
56
# Set replication to automatic
57
secret.replication = secretmanager.Replication()
58
secret.replication.automatic = secretmanager.Replication.Automatic()
59
60
# Add labels for organization
61
secret.labels = {
62
'environment': 'production',
63
'team': 'backend',
64
'cost-center': 'engineering'
65
}
66
67
# Set TTL (optional)
68
secret.ttl = duration_pb2.Duration()
69
secret.ttl.seconds = 86400 * 30 # 30 days
70
71
# Add annotations (optional)
72
secret.annotations = {
73
'created-by': 'deployment-script',
74
'purpose': 'api-authentication'
75
}
76
77
# Add tags for resource organization (optional)
78
secret.tags = {
79
'billing': 'engineering-team',
80
'compliance': 'pci-dss'
81
}
82
83
# Set up version aliases (optional)
84
secret.version_aliases = {
85
'production': 1,
86
'staging': 2
87
}
88
89
# Set version destruction TTL (optional)
90
secret.version_destroy_ttl = duration_pb2.Duration()
91
secret.version_destroy_ttl.seconds = 86400 * 7 # 7 days
92
```
93
94
### SecretVersion
95
96
Represents a version of a secret containing the actual secret data and metadata about that specific version.
97
98
```python { .api }
99
class SecretVersion:
100
"""
101
A secret version resource in the Secret Manager API.
102
103
Attributes:
104
name (str): Output only. The resource name of the SecretVersion in format
105
projects/*/secrets/*/versions/*.
106
create_time (Timestamp): Output only. The time at which the SecretVersion was created.
107
destroy_time (Timestamp): Output only. The time this SecretVersion was destroyed.
108
state (State): Output only. The current state of the SecretVersion.
109
etag (str): Output only. Etag for optimistic concurrency control.
110
client_specified_payload_checksum (bool): Output only. True if payload checksum was specified.
111
scheduled_destroy_time (Timestamp): Optional. The time this version is scheduled for destruction.
112
customer_managed_encryption (CustomerManagedEncryptionStatus): Output only. Customer-managed encryption status for this version.
113
"""
114
115
class State(Enum):
116
"""The state of a SecretVersion."""
117
STATE_UNSPECIFIED = 0
118
ENABLED = 1 # Version is active and can be accessed
119
DISABLED = 2 # Version is disabled and cannot be accessed
120
DESTROYED = 3 # Version is destroyed and cannot be recovered
121
122
name: str
123
create_time: Timestamp
124
destroy_time: Timestamp
125
state: State
126
etag: str
127
client_specified_payload_checksum: bool
128
scheduled_destroy_time: Timestamp
129
customer_managed_encryption: CustomerManagedEncryptionStatus
130
```
131
132
**Usage Example:**
133
134
```python
135
# Check version state before accessing
136
if version.state == secretmanager.SecretVersion.State.ENABLED:
137
# Safe to access version data
138
access_request = secretmanager.AccessSecretVersionRequest()
139
access_request.name = version.name
140
response = client.access_secret_version(request=access_request)
141
elif version.state == secretmanager.SecretVersion.State.DISABLED:
142
print("Version is disabled - enable before accessing")
143
elif version.state == secretmanager.SecretVersion.State.DESTROYED:
144
print("Version is permanently destroyed")
145
```
146
147
### SecretPayload
148
149
Contains the actual secret data and optional checksum for data integrity verification.
150
151
```python { .api }
152
class SecretPayload:
153
"""
154
A secret payload resource in the Secret Manager API.
155
156
Attributes:
157
data (bytes): The secret data. Must be no larger than 64KiB.
158
data_crc32c (int): Optional. The CRC32C checksum of the secret data.
159
"""
160
data: bytes
161
data_crc32c: int
162
```
163
164
**Usage Example:**
165
166
```python
167
import crc32c
168
import json
169
170
# Create payload with string data
171
payload = secretmanager.SecretPayload()
172
secret_string = "my-api-key-12345"
173
payload.data = secret_string.encode('utf-8')
174
175
# Add checksum for integrity
176
payload.data_crc32c = crc32c.crc32c(payload.data)
177
178
# Create payload with JSON data
179
config_data = {
180
'api_key': 'secret-key',
181
'endpoint': 'https://api.example.com',
182
'timeout': 30
183
}
184
json_payload = secretmanager.SecretPayload()
185
json_payload.data = json.dumps(config_data).encode('utf-8')
186
json_payload.data_crc32c = crc32c.crc32c(json_payload.data)
187
```
188
189
## Configuration Types
190
191
### Replication
192
193
Defines how secret data is replicated across regions for availability and latency optimization.
194
195
```python { .api }
196
class Replication:
197
"""
198
A policy that defines the replication and encryption configuration of data.
199
200
Attributes (oneof replication):
201
automatic (Automatic): Automatic replication across all regions.
202
user_managed (UserManaged): User-managed replication with specific regions.
203
"""
204
205
class Automatic:
206
"""
207
Automatic replication policy that replicates the Secret to all regions.
208
209
Attributes:
210
customer_managed_encryption (CustomerManagedEncryption): Optional. Encryption config.
211
"""
212
customer_managed_encryption: CustomerManagedEncryption
213
214
class UserManaged:
215
"""
216
User-managed replication policy that replicates the Secret to specific regions.
217
218
Attributes:
219
replicas (Sequence[Replica]): Required. The list of Replicas for this Secret.
220
"""
221
222
class Replica:
223
"""
224
Represents a Replica for a Secret.
225
226
Attributes:
227
location (str): Required. The canonical location name.
228
customer_managed_encryption (CustomerManagedEncryption): Optional. Encryption config.
229
"""
230
location: str
231
customer_managed_encryption: CustomerManagedEncryption
232
233
replicas: Sequence[Replica]
234
235
automatic: Automatic # oneof replication
236
user_managed: UserManaged # oneof replication
237
```
238
239
**Usage Example:**
240
241
```python
242
# Automatic replication
243
replication = secretmanager.Replication()
244
replication.automatic = secretmanager.Replication.Automatic()
245
246
# User-managed replication with specific regions
247
replication = secretmanager.Replication()
248
replication.user_managed = secretmanager.Replication.UserManaged()
249
250
# Add replica for us-central1
251
replica1 = secretmanager.Replication.UserManaged.Replica()
252
replica1.location = "us-central1"
253
replication.user_managed.replicas.append(replica1)
254
255
# Add replica for europe-west1
256
replica2 = secretmanager.Replication.UserManaged.Replica()
257
replica2.location = "europe-west1"
258
replication.user_managed.replicas.append(replica2)
259
```
260
261
### CustomerManagedEncryption
262
263
Configuration for customer-managed encryption keys (CMEK) using Google Cloud KMS.
264
265
```python { .api }
266
class CustomerManagedEncryption:
267
"""
268
Configuration for customer-managed encryption using Cloud KMS.
269
270
Attributes:
271
kms_key_name (str): Required. The resource name of the Cloud KMS key to use for encryption.
272
"""
273
kms_key_name: str
274
```
275
276
**Usage Example:**
277
278
```python
279
# Configure CMEK encryption
280
encryption = secretmanager.CustomerManagedEncryption()
281
encryption.kms_key_name = "projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key"
282
283
# Use with automatic replication
284
replication = secretmanager.Replication()
285
replication.automatic = secretmanager.Replication.Automatic()
286
replication.automatic.customer_managed_encryption = encryption
287
```
288
289
### Rotation
290
291
Configuration for automatic secret rotation with specified timing and policies.
292
293
```python { .api }
294
class Rotation:
295
"""
296
The rotation time and period for a Secret.
297
298
Attributes:
299
next_rotation_time (Timestamp): Optional. Timestamp when the next rotation should occur.
300
rotation_period (Duration): Optional. Input only. The Duration between rotation notifications.
301
"""
302
next_rotation_time: Timestamp
303
rotation_period: Duration
304
```
305
306
**Usage Example:**
307
308
```python
309
from google.protobuf import timestamp_pb2, duration_pb2
310
import datetime
311
312
# Set up rotation policy
313
rotation = secretmanager.Rotation()
314
315
# Rotate every 90 days
316
rotation.rotation_period = duration_pb2.Duration()
317
rotation.rotation_period.seconds = 86400 * 90 # 90 days
318
319
# Set next rotation time
320
next_rotation = datetime.datetime.now() + datetime.timedelta(days=90)
321
rotation.next_rotation_time = timestamp_pb2.Timestamp()
322
rotation.next_rotation_time.FromDatetime(next_rotation)
323
```
324
325
### Topic
326
327
Configuration for Pub/Sub notifications when secret operations occur.
328
329
```python { .api }
330
class Topic:
331
"""
332
A Pub/Sub topic which Secret Manager will publish to when control plane events occur.
333
334
Attributes:
335
name (str): Required. The resource name of the Pub/Sub topic.
336
"""
337
name: str
338
```
339
340
**Usage Example:**
341
342
```python
343
# Configure Pub/Sub notifications
344
topic = secretmanager.Topic()
345
topic.name = "projects/my-project/topics/secret-events"
346
347
# Add to secret configuration
348
secret.topics.append(topic)
349
```
350
351
## Status Types
352
353
### ReplicationStatus
354
355
Status information about secret replication across regions.
356
357
```python { .api }
358
class ReplicationStatus:
359
"""
360
The replication status of a SecretVersion.
361
362
Attributes (oneof replication_status):
363
automatic (Automatic): Automatic replication status.
364
user_managed (UserManaged): User-managed replication status.
365
"""
366
367
class Automatic:
368
"""
369
The replication status of a SecretVersion using automatic replication.
370
371
Attributes:
372
customer_managed_encryption (CustomerManagedEncryptionStatus):
373
Output only. The customer-managed encryption status of the SecretVersion.
374
"""
375
customer_managed_encryption: CustomerManagedEncryptionStatus
376
377
class UserManaged:
378
"""
379
The replication status of a SecretVersion using user-managed replication.
380
381
Attributes:
382
replicas (Sequence[ReplicaStatus]): Output only. The list of replica statuses.
383
"""
384
385
class ReplicaStatus:
386
"""
387
The replication status of a SecretVersion.
388
389
Attributes:
390
location (str): Output only. The canonical location name.
391
customer_managed_encryption (CustomerManagedEncryptionStatus):
392
Output only. The customer-managed encryption status.
393
"""
394
location: str
395
customer_managed_encryption: CustomerManagedEncryptionStatus
396
397
replicas: Sequence[ReplicaStatus]
398
399
automatic: Automatic # oneof replication_status
400
user_managed: UserManaged # oneof replication_status
401
```
402
403
### CustomerManagedEncryptionStatus
404
405
Status of customer-managed encryption for a secret version.
406
407
```python { .api }
408
class CustomerManagedEncryptionStatus:
409
"""
410
Describes the status of customer-managed encryption.
411
412
Attributes:
413
kms_key_version_name (str): Required. The resource name of the Cloud KMS
414
CryptoKey version used to encrypt the secret payload.
415
"""
416
kms_key_version_name: str
417
```
418
419
## Transport and Client Configuration Types
420
421
### Transport Options
422
423
```python { .api }
424
class SecretManagerServiceGrpcTransport:
425
"""Synchronous gRPC transport for Secret Manager."""
426
427
class SecretManagerServiceGrpcAsyncIOTransport:
428
"""Asynchronous gRPC transport for Secret Manager."""
429
430
class SecretManagerServiceRestTransport:
431
"""Synchronous REST transport for Secret Manager."""
432
```
433
434
### Client Options
435
436
```python { .api }
437
class ClientOptions:
438
"""
439
Client configuration options.
440
441
Attributes:
442
api_endpoint (str): The API endpoint.
443
client_cert_source (Callable): A callable for client certificate.
444
client_info (ClientInfo): The client information.
445
scopes (Sequence[str]): OAuth2 scopes for authentication.
446
quota_project_id (str): Project ID for quota attribution.
447
"""
448
api_endpoint: str
449
client_cert_source: Callable
450
client_info: ClientInfo
451
scopes: Sequence[str]
452
quota_project_id: str
453
```
454
455
## Pagination Types
456
457
### ListSecretsPager
458
459
Iterator for paginated secret listing results.
460
461
```python { .api }
462
class ListSecretsPager:
463
"""
464
A pager for iterating through list_secrets requests.
465
466
This class provides an iterator interface for paginated results.
467
"""
468
469
def __iter__(self) -> Iterator[Secret]:
470
"""Iterate over secrets."""
471
...
472
473
def __next__(self) -> Secret:
474
"""Get next secret."""
475
...
476
```
477
478
### ListSecretVersionsPager
479
480
Iterator for paginated secret version listing results.
481
482
```python { .api }
483
class ListSecretVersionsPager:
484
"""
485
A pager for iterating through list_secret_versions requests.
486
487
This class provides an iterator interface for paginated results.
488
"""
489
490
def __iter__(self) -> Iterator[SecretVersion]:
491
"""Iterate over secret versions."""
492
...
493
494
def __next__(self) -> SecretVersion:
495
"""Get next secret version."""
496
...
497
```
498
499
### Async Pagination Classes
500
501
```python { .api }
502
class ListSecretsAsyncPager:
503
"""
504
Async pager for iterating through list_secrets requests.
505
506
This class provides an async iterator interface for paginated results.
507
"""
508
509
def __aiter__(self) -> AsyncIterator[Secret]:
510
"""Async iterate over secrets."""
511
...
512
513
async def __anext__(self) -> Secret:
514
"""Get next secret async."""
515
...
516
517
class ListSecretVersionsAsyncPager:
518
"""
519
Async pager for iterating through list_secret_versions requests.
520
521
This class provides an async iterator interface for paginated results.
522
"""
523
524
def __aiter__(self) -> AsyncIterator[SecretVersion]:
525
"""Async iterate over secret versions."""
526
...
527
528
async def __anext__(self) -> SecretVersion:
529
"""Get next secret version async."""
530
...
531
```
532
533
## Common Data Patterns
534
535
### Working with Timestamps
536
537
```python
538
from google.protobuf import timestamp_pb2
539
import datetime
540
541
# Convert datetime to protobuf timestamp
542
dt = datetime.datetime.now(datetime.timezone.utc)
543
timestamp = timestamp_pb2.Timestamp()
544
timestamp.FromDatetime(dt)
545
546
# Convert protobuf timestamp to datetime
547
dt_from_proto = timestamp.ToDatetime()
548
549
# Working with secret expiration
550
secret.expire_time = timestamp_pb2.Timestamp()
551
expiry_date = datetime.datetime.now() + datetime.timedelta(days=365)
552
secret.expire_time.FromDatetime(expiry_date)
553
```
554
555
### Working with Durations
556
557
```python
558
from google.protobuf import duration_pb2
559
560
# Set TTL to 30 days
561
secret.ttl = duration_pb2.Duration()
562
secret.ttl.seconds = 86400 * 30 # 30 days in seconds
563
564
# Set rotation period to 90 days
565
rotation.rotation_period = duration_pb2.Duration()
566
rotation.rotation_period.seconds = 86400 * 90 # 90 days
567
```
568
569
### Working with Field Masks
570
571
```python
572
from google.protobuf import field_mask_pb2
573
574
# Update only specific fields
575
update_mask = field_mask_pb2.FieldMask()
576
update_mask.paths.extend(['labels', 'annotations'])
577
578
request = secretmanager.UpdateSecretRequest()
579
request.secret = updated_secret
580
request.update_mask = update_mask
581
```
582
583
### Data Integrity Verification
584
585
```python
586
import crc32c
587
588
def verify_payload_integrity(payload):
589
"""Verify payload data integrity using CRC32C."""
590
if payload.data_crc32c:
591
computed_crc = crc32c.crc32c(payload.data)
592
if computed_crc != payload.data_crc32c:
593
raise ValueError("Payload data integrity check failed")
594
return True
595
596
# Usage
597
response = client.access_secret_version(request=access_request)
598
verify_payload_integrity(response.payload)
599
```