0
# Secret Models and Data Types
1
2
Comprehensive data models representing secrets, their properties, and metadata with complete type definitions for all secret-related operations. These models provide structured access to secret data and enable type-safe operations.
3
4
## Capabilities
5
6
### KeyVaultSecret
7
8
Complete secret representation including both value and metadata properties.
9
10
```python { .api }
11
class KeyVaultSecret:
12
def __init__(
13
self,
14
properties: SecretProperties,
15
value: Optional[str]
16
):
17
"""
18
Represents a complete Key Vault secret with value and properties.
19
20
Parameters:
21
- properties (SecretProperties): Secret metadata and properties
22
- value (str, optional): The secret's value
23
"""
24
25
@property
26
def name(self) -> Optional[str]:
27
"""The name of the secret."""
28
29
@property
30
def id(self) -> Optional[str]:
31
"""The full identifier URL of the secret."""
32
33
@property
34
def properties(self) -> SecretProperties:
35
"""The secret's properties and metadata."""
36
37
@property
38
def value(self) -> Optional[str]:
39
"""The secret's value (sensitive data)."""
40
41
def __repr__(self) -> str:
42
"""String representation of the secret (excludes value for security)."""
43
```
44
45
### SecretProperties
46
47
Secret metadata without the actual secret value, used for operations that don't require the sensitive data.
48
49
```python { .api }
50
class SecretProperties:
51
def __init__(self, *args, **kwargs):
52
"""
53
Represents secret metadata without the actual value.
54
"""
55
56
@property
57
def id(self) -> Optional[str]:
58
"""The full identifier URL of the secret."""
59
60
@property
61
def name(self) -> Optional[str]:
62
"""The name of the secret."""
63
64
@property
65
def version(self) -> Optional[str]:
66
"""The version identifier of the secret."""
67
68
@property
69
def vault_url(self) -> Optional[str]:
70
"""The URL of the vault containing the secret."""
71
72
@property
73
def content_type(self) -> Optional[str]:
74
"""
75
Content type of the secret value.
76
77
Common types: 'text/plain', 'application/json', 'application/x-pem-file'
78
"""
79
80
@property
81
def enabled(self) -> Optional[bool]:
82
"""Whether the secret is enabled for use."""
83
84
@property
85
def not_before(self) -> Optional[datetime]:
86
"""The datetime before which the secret cannot be used."""
87
88
@property
89
def expires_on(self) -> Optional[datetime]:
90
"""The datetime after which the secret expires."""
91
92
@property
93
def created_on(self) -> Optional[datetime]:
94
"""When the secret was created."""
95
96
@property
97
def updated_on(self) -> Optional[datetime]:
98
"""When the secret was last updated."""
99
100
@property
101
def recovery_level(self) -> Optional[str]:
102
"""
103
Recovery level for soft-deleted secrets.
104
105
Values: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable',
106
'Recoverable+ProtectedSubscription'
107
"""
108
109
@property
110
def recoverable_days(self) -> Optional[int]:
111
"""Number of days a deleted secret can be recovered."""
112
113
@property
114
def key_id(self) -> Optional[str]:
115
"""ID of the key backing the secret (for certificate-backed secrets)."""
116
117
@property
118
def managed(self) -> Optional[bool]:
119
"""Whether the secret's lifetime is managed by Key Vault."""
120
121
@property
122
def tags(self) -> Optional[Dict[str, str]]:
123
"""User-defined metadata tags associated with the secret."""
124
125
def __repr__(self) -> str:
126
"""String representation of the secret properties."""
127
```
128
129
### KeyVaultSecretIdentifier
130
131
Parser and representation for Key Vault secret identifiers/URLs.
132
133
```python { .api }
134
class KeyVaultSecretIdentifier:
135
def __init__(self, source_id: str):
136
"""
137
Parse and represent a Key Vault secret identifier.
138
139
Parameters:
140
- source_id (str): The full secret identifier URL to parse
141
Format: https://{vault}.vault.azure.net/secrets/{name}[/{version}]
142
143
Raises:
144
- ValueError: If the secret ID format is invalid
145
"""
146
147
@property
148
def source_id(self) -> str:
149
"""The original identifier URL that was parsed."""
150
151
@property
152
def vault_url(self) -> str:
153
"""The base URL of the Key Vault (e.g., 'https://vault.vault.azure.net/')."""
154
155
@property
156
def name(self) -> str:
157
"""The name of the secret."""
158
159
@property
160
def version(self) -> Optional[str]:
161
"""
162
The version of the secret, if specified in the identifier.
163
None if the identifier refers to the latest version.
164
"""
165
```
166
167
### DeletedSecret
168
169
Represents a soft-deleted secret with recovery information and deletion metadata.
170
171
```python { .api }
172
class DeletedSecret:
173
def __init__(
174
self,
175
properties: SecretProperties,
176
deleted_date: Optional[datetime] = None,
177
recovery_id: Optional[str] = None,
178
scheduled_purge_date: Optional[datetime] = None
179
):
180
"""
181
Represents a deleted secret with recovery capabilities.
182
183
Parameters:
184
- properties (SecretProperties): The secret's properties
185
- deleted_date (datetime, optional): When the secret was deleted
186
- recovery_id (str, optional): Identifier for recovery operations
187
- scheduled_purge_date (datetime, optional): When the secret will be permanently deleted
188
"""
189
190
@property
191
def id(self) -> Optional[str]:
192
"""The full identifier URL of the deleted secret."""
193
194
@property
195
def name(self) -> Optional[str]:
196
"""The name of the deleted secret."""
197
198
@property
199
def properties(self) -> SecretProperties:
200
"""The secret's properties and metadata."""
201
202
@property
203
def deleted_date(self) -> Optional[datetime]:
204
"""When the secret was deleted."""
205
206
@property
207
def recovery_id(self) -> Optional[str]:
208
"""
209
The identifier used for recovery operations.
210
Used with recover_deleted_secret() operations.
211
"""
212
213
@property
214
def scheduled_purge_date(self) -> Optional[datetime]:
215
"""
216
When the secret is scheduled for permanent deletion.
217
After this date, the secret cannot be recovered.
218
"""
219
220
def __repr__(self) -> str:
221
"""String representation of the deleted secret."""
222
```
223
224
### DeletionRecoveryLevel
225
226
Enumeration of recovery levels for soft-deleted secrets indicating the protection and recovery capabilities.
227
228
```python { .api }
229
class DeletionRecoveryLevel(str, Enum):
230
"""
231
Enumeration of recovery levels for deleted secrets.
232
233
Determines how deleted secrets can be recovered and their protection level.
234
"""
235
PURGEABLE = "Purgeable"
236
RECOVERABLE_PURGEABLE = "Recoverable+Purgeable"
237
RECOVERABLE = "Recoverable"
238
RECOVERABLE_PROTECTED_SUBSCRIPTION = "Recoverable+ProtectedSubscription"
239
CUSTOMIZED_RECOVERABLE_PURGEABLE = "CustomizedRecoverable+Purgeable"
240
CUSTOMIZED_RECOVERABLE = "CustomizedRecoverable"
241
CUSTOMIZED_RECOVERABLE_PROTECTED_SUBSCRIPTION = "CustomizedRecoverable+ProtectedSubscription"
242
```
243
244
### ApiVersion
245
246
Enumeration of supported Key Vault API versions.
247
248
```python { .api }
249
class ApiVersion(str, Enum):
250
"""
251
Supported Azure Key Vault API versions.
252
"""
253
V7_6 = "7.6" # Default version (latest)
254
V7_5 = "7.5"
255
V7_4 = "7.4"
256
V7_3 = "7.3"
257
V7_2 = "7.2"
258
V7_1 = "7.1"
259
V7_0 = "7.0"
260
V2016_10_01 = "2016-10-01" # Legacy version
261
```
262
263
## Usage Examples
264
265
### Working with Secret Identifiers
266
267
```python
268
from azure.keyvault.secrets import KeyVaultSecretIdentifier
269
270
# Parse a complete secret identifier
271
secret_id = "https://vault.vault.azure.net/secrets/my-secret/abc123def456"
272
identifier = KeyVaultSecretIdentifier(secret_id)
273
274
print(f"Vault URL: {identifier.vault_url}") # https://vault.vault.azure.net/
275
print(f"Secret Name: {identifier.name}") # my-secret
276
print(f"Version: {identifier.version}") # abc123def456
277
278
# Parse identifier without version (latest)
279
latest_id = "https://vault.vault.azure.net/secrets/my-secret"
280
latest_identifier = KeyVaultSecretIdentifier(latest_id)
281
print(f"Version: {latest_identifier.version}") # None (refers to latest)
282
```
283
284
### Examining Secret Properties
285
286
```python
287
from azure.keyvault.secrets import SecretClient
288
from azure.identity import DefaultAzureCredential
289
290
client = SecretClient("https://vault.vault.azure.net/", DefaultAzureCredential())
291
292
# Get a secret and examine its properties
293
secret = client.get_secret("my-secret")
294
295
print(f"Secret Name: {secret.name}")
296
print(f"Secret Value: {secret.value}")
297
print(f"Content Type: {secret.properties.content_type}")
298
print(f"Enabled: {secret.properties.enabled}")
299
print(f"Created: {secret.properties.created_on}")
300
print(f"Tags: {secret.properties.tags}")
301
302
# Check expiration
303
if secret.properties.expires_on:
304
from datetime import datetime
305
if secret.properties.expires_on < datetime.now(secret.properties.expires_on.tzinfo):
306
print("Warning: Secret has expired!")
307
```
308
309
### Working with Deleted Secrets
310
311
```python
312
from azure.keyvault.secrets import SecretClient
313
from azure.identity import DefaultAzureCredential
314
315
client = SecretClient("https://vault.vault.azure.net/", DefaultAzureCredential())
316
317
# Delete a secret and examine the deleted secret info
318
poller = client.begin_delete_secret("my-secret")
319
deleted_secret = poller.result()
320
321
print(f"Deleted Secret: {deleted_secret.name}")
322
print(f"Deleted On: {deleted_secret.deleted_date}")
323
print(f"Recovery ID: {deleted_secret.recovery_id}")
324
print(f"Scheduled Purge: {deleted_secret.scheduled_purge_date}")
325
326
# Check if recovery is possible
327
from datetime import datetime, timezone
328
now = datetime.now(timezone.utc)
329
if deleted_secret.scheduled_purge_date and deleted_secret.scheduled_purge_date > now:
330
print("Secret can still be recovered")
331
332
# Recover the secret
333
recover_poller = client.begin_recover_deleted_secret("my-secret")
334
recovered_properties = recover_poller.result()
335
print(f"Recovered: {recovered_properties.name}")
336
else:
337
print("Secret is past recovery period")
338
```
339
340
### Working with Secret Versions
341
342
```python
343
from azure.keyvault.secrets import SecretClient
344
from azure.identity import DefaultAzureCredential
345
346
client = SecretClient("https://vault.vault.azure.net/", DefaultAzureCredential())
347
348
# List all versions of a secret
349
for version_props in client.list_properties_of_secret_versions("my-secret"):
350
print(f"Version: {version_props.version}")
351
print(f"Created: {version_props.created_on}")
352
print(f"Enabled: {version_props.enabled}")
353
354
# Get specific version
355
versioned_secret = client.get_secret("my-secret", version_props.version)
356
print(f"Value for version {version_props.version}: {versioned_secret.value}")
357
```
358
359
### Managing Secret Metadata
360
361
```python
362
from azure.keyvault.secrets import SecretClient
363
from azure.identity import DefaultAzureCredential
364
from datetime import datetime, timedelta
365
366
client = SecretClient("https://vault.vault.azure.net/", DefaultAzureCredential())
367
368
# Set a secret with comprehensive metadata
369
expiration = datetime.utcnow() + timedelta(days=365)
370
not_before = datetime.utcnow()
371
372
secret = client.set_secret(
373
"production-api-key",
374
"super-secret-value",
375
enabled=True,
376
content_type="text/plain",
377
tags={
378
"environment": "production",
379
"service": "api-gateway",
380
"owner": "platform-team",
381
"classification": "confidential"
382
},
383
not_before=not_before,
384
expires_on=expiration
385
)
386
387
# Later, update only the metadata without changing the value
388
updated_props = client.update_secret_properties(
389
"production-api-key",
390
tags={
391
"environment": "production",
392
"service": "api-gateway",
393
"owner": "platform-team",
394
"classification": "confidential",
395
"last-rotated": datetime.utcnow().isoformat()
396
}
397
)
398
399
print(f"Updated tags: {updated_props.tags}")
400
```
401
402
## Required Imports
403
404
```python { .api }
405
from typing import Dict, Optional
406
from datetime import datetime
407
from enum import Enum
408
from azure.keyvault.secrets._generated.models import DeletionRecoveryLevel
409
```