0
# Secret Management
1
2
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.
3
4
## Capabilities
5
6
### Creating Secrets
7
8
Creates a new secret with specified configuration including replication policy, labels, and optional settings like TTL, expiration, and Pub/Sub notifications.
9
10
```python { .api }
11
def create_secret(self, request: CreateSecretRequest = None, **kwargs) -> Secret:
12
"""
13
Creates a new Secret containing no SecretVersions.
14
15
Args:
16
request (CreateSecretRequest): The request object containing parent project,
17
secret_id, and secret configuration.
18
parent (str): Required. The resource name of the project associated with the
19
Secret, in the format projects/* or projects/*/locations/*.
20
secret_id (str): Required. This must be unique within the project.
21
secret (Secret): Required. A Secret with initial empty SecretVersion.
22
23
Returns:
24
Secret: The created Secret.
25
26
Raises:
27
google.api_core.exceptions.AlreadyExists: If secret_id already exists.
28
google.api_core.exceptions.InvalidArgument: If request is malformed.
29
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
30
"""
31
```
32
33
**Usage Example:**
34
35
```python
36
from google.cloud import secretmanager
37
38
client = secretmanager.SecretManagerServiceClient()
39
40
# Create secret with automatic replication
41
secret = secretmanager.Secret()
42
secret.replication = secretmanager.Replication()
43
secret.replication.automatic = secretmanager.Replication.Automatic()
44
45
# Add labels for organization
46
secret.labels = {
47
'environment': 'production',
48
'team': 'backend'
49
}
50
51
# Create request
52
request = secretmanager.CreateSecretRequest()
53
request.parent = "projects/my-project"
54
request.secret_id = "api-key"
55
request.secret = secret
56
57
# Create the secret
58
created_secret = client.create_secret(request=request)
59
print(f"Created secret: {created_secret.name}")
60
```
61
62
### Retrieving Secret Metadata
63
64
Retrieves secret metadata and configuration without accessing the secret data itself. Returns information about replication, labels, creation time, and other metadata.
65
66
```python { .api }
67
def get_secret(self, request: GetSecretRequest = None, **kwargs) -> Secret:
68
"""
69
Gets metadata for a given Secret.
70
71
Args:
72
request (GetSecretRequest): The request object.
73
name (str): Required. The resource name of the Secret, in the format
74
projects/*/secrets/* or projects/*/locations/*/secrets/*.
75
76
Returns:
77
Secret: The Secret metadata.
78
79
Raises:
80
google.api_core.exceptions.NotFound: If the secret does not exist.
81
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
82
"""
83
```
84
85
**Usage Example:**
86
87
```python
88
request = secretmanager.GetSecretRequest()
89
request.name = "projects/my-project/secrets/api-key"
90
91
secret = client.get_secret(request=request)
92
print(f"Secret created: {secret.create_time}")
93
print(f"Labels: {secret.labels}")
94
print(f"Replication policy: {secret.replication}")
95
```
96
97
### Updating Secret Configuration
98
99
Updates secret metadata including labels, expiration settings, and Pub/Sub topic configurations. Cannot modify immutable properties like replication policy.
100
101
```python { .api }
102
def update_secret(self, request: UpdateSecretRequest = None, **kwargs) -> Secret:
103
"""
104
Updates metadata of an existing Secret.
105
106
Args:
107
request (UpdateSecretRequest): The request object.
108
secret (Secret): Required. Secret with updated field values.
109
update_mask (FieldMask): Required. Specifies fields to be updated.
110
111
Returns:
112
Secret: The updated Secret.
113
114
Raises:
115
google.api_core.exceptions.NotFound: If the secret does not exist.
116
google.api_core.exceptions.InvalidArgument: If update_mask is invalid.
117
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
118
"""
119
```
120
121
**Usage Example:**
122
123
```python
124
from google.protobuf import field_mask_pb2
125
126
# Get current secret
127
get_request = secretmanager.GetSecretRequest()
128
get_request.name = "projects/my-project/secrets/api-key"
129
secret = client.get_secret(request=get_request)
130
131
# Update labels
132
secret.labels['updated'] = 'true'
133
secret.labels['version'] = '2.0'
134
135
# Create update request with field mask
136
request = secretmanager.UpdateSecretRequest()
137
request.secret = secret
138
request.update_mask = field_mask_pb2.FieldMask()
139
request.update_mask.paths.append('labels')
140
141
updated_secret = client.update_secret(request=request)
142
print(f"Updated secret: {updated_secret.name}")
143
```
144
145
### Deleting Secrets
146
147
Permanently deletes a secret and all of its versions. This operation cannot be undone and immediately makes the secret and all its data inaccessible.
148
149
```python { .api }
150
def delete_secret(self, request: DeleteSecretRequest = None, **kwargs) -> None:
151
"""
152
Deletes a Secret.
153
154
Args:
155
request (DeleteSecretRequest): The request object.
156
name (str): Required. The resource name of the Secret to delete in the format
157
projects/*/secrets/*.
158
etag (str): Optional. Etag of the Secret for optimistic concurrency control.
159
160
Returns:
161
None
162
163
Raises:
164
google.api_core.exceptions.NotFound: If the secret does not exist.
165
google.api_core.exceptions.FailedPrecondition: If etag doesn't match.
166
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
167
"""
168
```
169
170
**Usage Example:**
171
172
```python
173
request = secretmanager.DeleteSecretRequest()
174
request.name = "projects/my-project/secrets/old-api-key"
175
176
# Optional: Use etag for optimistic concurrency control
177
# request.etag = secret.etag
178
179
client.delete_secret(request=request)
180
print("Secret deleted successfully")
181
```
182
183
### Listing Secrets
184
185
Lists all secrets in a project with optional filtering and pagination. Returns secret metadata without accessing secret data.
186
187
```python { .api }
188
def list_secrets(self, request: ListSecretsRequest = None, **kwargs) -> ListSecretsPager:
189
"""
190
Lists Secrets.
191
192
Args:
193
request (ListSecretsRequest): The request object.
194
parent (str): Required. The resource name of the project associated with the
195
Secrets, in the format projects/* or projects/*/locations/*.
196
page_size (int): Optional. The maximum number of results to return in a single page.
197
page_token (str): Optional. Pagination token.
198
filter (str): Optional. Filter string adhering to the filtering rules.
199
200
Returns:
201
ListSecretsPager: An iterator for paginated results.
202
203
Raises:
204
google.api_core.exceptions.InvalidArgument: If filter is malformed.
205
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
206
"""
207
```
208
209
**Usage Example:**
210
211
```python
212
# List all secrets
213
request = secretmanager.ListSecretsRequest()
214
request.parent = "projects/my-project"
215
216
for secret in client.list_secrets(request=request):
217
print(f"Secret: {secret.name}")
218
print(f" Created: {secret.create_time}")
219
print(f" Labels: {secret.labels}")
220
221
# List with filtering
222
request.filter = 'labels.environment="production"'
223
production_secrets = list(client.list_secrets(request=request))
224
print(f"Found {len(production_secrets)} production secrets")
225
226
# List with pagination
227
request = secretmanager.ListSecretsRequest()
228
request.parent = "projects/my-project"
229
request.page_size = 10
230
231
page_result = client.list_secrets(request=request)
232
first_page = list(page_result)
233
print(f"First page: {len(first_page)} secrets")
234
```
235
236
## Path Helper Methods
237
238
Utility methods for constructing and parsing resource names:
239
240
```python { .api }
241
@staticmethod
242
def secret_path(project: str, secret: str) -> str:
243
"""Returns a fully-qualified secret string."""
244
245
@staticmethod
246
def parse_secret_path(path: str) -> Dict[str, str]:
247
"""Parses a secret path into its component segments."""
248
249
@staticmethod
250
def topic_path(project: str, topic: str) -> str:
251
"""Returns a fully-qualified Pub/Sub topic string."""
252
253
@staticmethod
254
def parse_topic_path(path: str) -> Dict[str, str]:
255
"""Parses a topic path into its component segments."""
256
257
@staticmethod
258
def common_project_path(project: str) -> str:
259
"""Returns a fully-qualified project string."""
260
261
@staticmethod
262
def common_location_path(project: str, location: str) -> str:
263
"""Returns a fully-qualified location string."""
264
265
@staticmethod
266
def parse_common_project_path(path: str) -> Dict[str, str]:
267
"""Parses a project path into its component segments."""
268
269
@staticmethod
270
def parse_common_location_path(path: str) -> Dict[str, str]:
271
"""Parses a location path into its component segments."""
272
```
273
274
**Usage Example:**
275
276
```python
277
# Construct secret path
278
secret_path = client.secret_path("my-project", "api-key")
279
print(secret_path) # "projects/my-project/secrets/api-key"
280
281
# Parse secret path
282
components = client.parse_secret_path(secret_path)
283
print(components) # {'project': 'my-project', 'secret': 'api-key'}
284
285
# Construct topic path for Pub/Sub notifications
286
topic_path = client.topic_path("my-project", "secret-events")
287
print(topic_path) # "projects/my-project/topics/secret-events"
288
289
# Construct location path
290
location_path = client.common_location_path("my-project", "us-central1")
291
print(location_path) # "projects/my-project/locations/us-central1"
292
293
# Parse paths
294
topic_components = client.parse_topic_path(topic_path)
295
print(topic_components) # {'project': 'my-project', 'topic': 'secret-events'}
296
```
297
298
## Request Types
299
300
### CreateSecretRequest
301
302
```python { .api }
303
class CreateSecretRequest:
304
"""
305
Request message for SecretManagerService.CreateSecret.
306
307
Attributes:
308
parent (str): Required. The project resource name.
309
secret_id (str): Required. The secret ID.
310
secret (Secret): Required. A Secret with initial configuration.
311
"""
312
parent: str
313
secret_id: str
314
secret: Secret
315
```
316
317
### GetSecretRequest
318
319
```python { .api }
320
class GetSecretRequest:
321
"""
322
Request message for SecretManagerService.GetSecret.
323
324
Attributes:
325
name (str): Required. The secret resource name.
326
"""
327
name: str
328
```
329
330
### UpdateSecretRequest
331
332
```python { .api }
333
class UpdateSecretRequest:
334
"""
335
Request message for SecretManagerService.UpdateSecret.
336
337
Attributes:
338
secret (Secret): Required. Secret with updated values.
339
update_mask (FieldMask): Required. Fields to update.
340
"""
341
secret: Secret
342
update_mask: field_mask_pb2.FieldMask
343
```
344
345
### DeleteSecretRequest
346
347
```python { .api }
348
class DeleteSecretRequest:
349
"""
350
Request message for SecretManagerService.DeleteSecret.
351
352
Attributes:
353
name (str): Required. The secret resource name.
354
etag (str): Optional. Etag for optimistic concurrency control.
355
"""
356
name: str
357
etag: str
358
```
359
360
### ListSecretsRequest
361
362
```python { .api }
363
class ListSecretsRequest:
364
"""
365
Request message for SecretManagerService.ListSecrets.
366
367
Attributes:
368
parent (str): Required. The project resource name.
369
page_size (int): Optional. Maximum results per page.
370
page_token (str): Optional. Pagination token.
371
filter (str): Optional. Filter expression.
372
"""
373
parent: str
374
page_size: int
375
page_token: str
376
filter: str
377
```
378
379
### ListSecretsResponse
380
381
```python { .api }
382
class ListSecretsResponse:
383
"""
384
Response message for SecretManagerService.ListSecrets.
385
386
Attributes:
387
secrets (Sequence[Secret]): List of secrets.
388
next_page_token (str): Token for next page.
389
"""
390
secrets: Sequence[Secret]
391
next_page_token: str
392
```
393
394
## Location Management
395
396
Utility methods for working with Google Cloud locations when managing secrets across regions.
397
398
### Getting Location Information
399
400
Retrieves information about a specific Google Cloud location.
401
402
```python { .api }
403
def get_location(self, request: GetLocationRequest = None, **kwargs) -> Location:
404
"""
405
Gets information about a location.
406
407
Args:
408
request (GetLocationRequest): The request object.
409
name (str): Required. Resource name for the location.
410
411
Returns:
412
Location: The location information.
413
414
Raises:
415
google.api_core.exceptions.NotFound: If the location does not exist.
416
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
417
"""
418
```
419
420
### Listing Available Locations
421
422
Lists available Google Cloud locations for the service.
423
424
```python { .api }
425
def list_locations(self, request: ListLocationsRequest = None, **kwargs) -> ListLocationsResponse:
426
"""
427
Lists information about the supported locations for this service.
428
429
Args:
430
request (ListLocationsRequest): The request object.
431
name (str): Required. The resource name of the project.
432
filter (str): Optional. A filter for the locations.
433
page_size (int): Optional. Maximum results per page.
434
page_token (str): Optional. Pagination token.
435
436
Returns:
437
ListLocationsResponse: The list of locations.
438
439
Raises:
440
google.api_core.exceptions.PermissionDenied: If insufficient permissions.
441
"""
442
```
443
444
**Usage Example:**
445
446
```python
447
# List available locations
448
request = locations_pb2.ListLocationsRequest()
449
request.name = "projects/my-project"
450
451
locations = client.list_locations(request=request)
452
for location in locations:
453
print(f"Location: {location.name}")
454
print(f" Display name: {location.display_name}")
455
print(f" Location ID: {location.location_id}")
456
```