0
# Service Operations
1
2
Core service operations for Azure Recovery Services including name availability checking, service capability queries, identity management, and API operation discovery. These operations provide foundational functionality for service discovery, resource naming validation, and system administration.
3
4
## Capabilities
5
6
### Check Name Availability
7
8
Validates whether a proposed resource name is available for use within the specified location and resource group.
9
10
```python { .api }
11
def check_name_availability(
12
resource_group_name: str,
13
location: str,
14
input: Union[CheckNameAvailabilityParameters, IO[bytes]],
15
**kwargs
16
) -> CheckNameAvailabilityResult:
17
"""
18
API to check for resource name availability. A name is available if no other resource exists
19
with the same SubscriptionId, Resource Name and Type, or if existing resources have been
20
garbage collected and deleted more than 24 hours ago.
21
22
Parameters:
23
- resource_group_name: str - The name of the resource group
24
- location: str - Location of the resource
25
- input: Union[CheckNameAvailabilityParameters, IO[bytes]] - Check name availability input
26
27
Returns:
28
CheckNameAvailabilityResult: Result indicating name availability status
29
"""
30
```
31
32
**Usage Example:**
33
34
```python
35
from azure.mgmt.recoveryservices.models import CheckNameAvailabilityParameters
36
37
# Check if vault name is available
38
name_check = CheckNameAvailabilityParameters(
39
type="Microsoft.RecoveryServices/vaults",
40
name="my-proposed-vault-name"
41
)
42
43
result = client.recovery_services.check_name_availability(
44
resource_group_name="my-rg",
45
location="eastus",
46
input=name_check
47
)
48
49
if result.name_available:
50
print(f"β Name '{name_check.name}' is available")
51
else:
52
print(f"β Name '{name_check.name}' is not available")
53
print(f"Reason: {result.reason}")
54
print(f"Message: {result.message}")
55
```
56
57
### Get Service Capabilities
58
59
Retrieves information about the capabilities and features provided by the Recovery Services resource provider in a specific location.
60
61
```python { .api }
62
def capabilities(
63
location: str,
64
input: Union[ResourceCapabilities, IO[bytes]],
65
**kwargs
66
) -> CapabilitiesResponse:
67
"""
68
API to get details about capabilities provided by Microsoft.RecoveryServices RP.
69
70
Parameters:
71
- location: str - Location of the resource
72
- input: Union[ResourceCapabilities, IO[bytes]] - Resource capabilities input
73
74
Returns:
75
CapabilitiesResponse: Response containing service capabilities information
76
"""
77
```
78
79
**Usage Example:**
80
81
```python
82
from azure.mgmt.recoveryservices.models import ResourceCapabilities
83
84
# Query service capabilities
85
capabilities_request = ResourceCapabilities(
86
type="Microsoft.RecoveryServices/vaults"
87
)
88
89
capabilities = client.recovery_services.capabilities(
90
location="eastus",
91
input=capabilities_request
92
)
93
94
print(f"Capabilities for location: eastus")
95
if capabilities.properties:
96
print(f"DNS Zones: {capabilities.properties.dns_zones}")
97
print(f"DNS Zone Response: {capabilities.properties.dns_zone_response}")
98
```
99
100
### Unregister Identity
101
102
Removes a registered identity (container) from the Recovery Services vault, effectively unregistering it from backup or recovery operations.
103
104
```python { .api }
105
def delete(resource_group_name: str, vault_name: str, identity_name: str, **kwargs) -> None:
106
"""
107
Unregisters the given container from your Recovery Services vault.
108
109
Parameters:
110
- resource_group_name: str - The name of the resource group
111
- vault_name: str - The name of the recovery services vault
112
- identity_name: str - Name of the protection container to unregister
113
114
Returns:
115
None
116
"""
117
```
118
119
**Usage Example:**
120
121
```python
122
# Unregister a protection container
123
try:
124
client.registered_identities.delete(
125
resource_group_name="my-rg",
126
vault_name="my-vault",
127
identity_name="my-container-identity"
128
)
129
print("β Successfully unregistered identity")
130
except Exception as e:
131
print(f"β Failed to unregister identity: {e}")
132
```
133
134
### List Available Operations
135
136
Discovers all available operations provided by the Recovery Services resource provider.
137
138
```python { .api }
139
def list(**kwargs) -> ItemPaged[ClientDiscoveryValueForSingleApi]:
140
"""
141
Returns the list of available operations.
142
143
Returns:
144
ItemPaged[ClientDiscoveryValueForSingleApi]: An iterator of available operations
145
"""
146
```
147
148
**Usage Example:**
149
150
```python
151
# List all available operations
152
operations = client.operations.list()
153
154
print("Available Recovery Services Operations:")
155
print("=" * 50)
156
157
for operation in operations:
158
print(f"Operation: {operation.name}")
159
if operation.display:
160
print(f" Provider: {operation.display.provider}")
161
print(f" Resource: {operation.display.resource}")
162
print(f" Operation: {operation.display.operation}")
163
print(f" Description: {operation.display.description}")
164
print()
165
```
166
167
## Service Operation Types
168
169
### Name Availability Check
170
171
```python { .api }
172
class CheckNameAvailabilityParameters:
173
"""
174
Parameters to check name availability.
175
176
Parameters:
177
- type: Optional[str] - Describes the Resource type: Microsoft.RecoveryServices/vaults
178
- name: Optional[str] - Resource name for which availability needs to be checked
179
"""
180
181
class CheckNameAvailabilityResult:
182
"""
183
Response for check name availability API.
184
185
Parameters:
186
- name_available: Optional[bool] - Gets a boolean value that indicates whether the name is available
187
- reason: Optional[str] - Gets the reason that a resource name could not be used
188
- message: Optional[str] - Gets an error message explaining the Reason value in more detail
189
"""
190
```
191
192
### Service Capabilities
193
194
```python { .api }
195
class ResourceCapabilities:
196
"""
197
Input to get capabilities.
198
199
Parameters:
200
- type: Optional[str] - Describes the Resource type: Microsoft.RecoveryServices/vaults
201
"""
202
203
class CapabilitiesResponse:
204
"""
205
Response for get capabilities API.
206
207
Parameters:
208
- type: Optional[str] - Describes the Resource type: Microsoft.RecoveryServices/vaults
209
- properties: Optional[CapabilitiesResponseProperties] - Properties of the response
210
"""
211
212
class CapabilitiesResponseProperties:
213
"""
214
Class to define the capabilities response properties.
215
216
Parameters:
217
- dns_zones: Optional[List[DNSZone]] - The list of available DNS zones
218
- dns_zone_response: Optional[List[DNSZoneResponse]] - Capabilities information
219
"""
220
```
221
222
### API Operation Discovery
223
224
```python { .api }
225
class ClientDiscoveryValueForSingleApi:
226
"""
227
Available operation details.
228
229
Parameters:
230
- name: Optional[str] - Name of the operation
231
- display: Optional[ClientDiscoveryDisplay] - Display information of the operation
232
- origin: Optional[str] - The intended executor of the operation
233
- properties: Optional[ClientDiscoveryForProperties] - Properties of the operation
234
"""
235
236
class ClientDiscoveryDisplay:
237
"""
238
Localized display information of an operation.
239
240
Parameters:
241
- provider: Optional[str] - Name of the provider for display purposes
242
- resource: Optional[str] - ResourceType for which this operation is performed
243
- operation: Optional[str] - Localized friendly name of the operation
244
- description: Optional[str] - Localized friendly description of the operation
245
"""
246
247
class ClientDiscoveryForProperties:
248
"""
249
Class to define the properties of a client discovery operation.
250
251
Parameters:
252
- service_specification: Optional[ClientDiscoveryForServiceSpecification] - Operation properties
253
"""
254
```
255
256
### DNS Zone Information
257
258
```python { .api }
259
class DNSZone:
260
"""
261
A DNS zone.
262
263
Parameters:
264
- name: Optional[str] - Name of the DNS zone
265
- required_zone_names: Optional[List[str]] - Required DNS zone names
266
"""
267
268
class DNSZoneResponse:
269
"""
270
Response data for DNS zone.
271
272
Parameters:
273
- name: Optional[str] - Name of the DNS zone
274
- required_zone_names: Optional[List[str]] - The DNS zone names required for the operation
275
"""
276
```
277
278
## Usage Patterns
279
280
### Resource Name Validation Workflow
281
282
```python
283
def validate_and_suggest_vault_name(client, resource_group: str, location: str, preferred_name: str, max_attempts: int = 5):
284
"""
285
Validate a preferred vault name and suggest alternatives if not available.
286
"""
287
288
def check_name(name: str) -> CheckNameAvailabilityResult:
289
return client.recovery_services.check_name_availability(
290
resource_group_name=resource_group,
291
location=location,
292
input=CheckNameAvailabilityParameters(
293
type="Microsoft.RecoveryServices/vaults",
294
name=name
295
)
296
)
297
298
# Check preferred name first
299
print(f"π Checking availability of preferred name: '{preferred_name}'")
300
result = check_name(preferred_name)
301
302
if result.name_available:
303
print(f"β '{preferred_name}' is available!")
304
return preferred_name
305
306
print(f"β '{preferred_name}' is not available")
307
print(f" Reason: {result.reason}")
308
print(f" Message: {result.message}")
309
310
# Generate alternative names
311
alternatives = []
312
base_name = preferred_name.rstrip('0123456789-')
313
314
for i in range(1, max_attempts + 1):
315
alternative = f"{base_name}-{i:02d}"
316
alternatives.append(alternative)
317
318
# Check alternatives
319
print(f"\nπ Checking {len(alternatives)} alternative names...")
320
321
for alt_name in alternatives:
322
result = check_name(alt_name)
323
if result.name_available:
324
print(f"β Alternative name available: '{alt_name}'")
325
return alt_name
326
else:
327
print(f"β '{alt_name}' - {result.reason}")
328
329
print(f"\nβ οΈ No available names found after {max_attempts} attempts")
330
return None
331
332
def check_regional_capabilities(client, locations: list):
333
"""
334
Check Recovery Services capabilities across multiple Azure regions.
335
"""
336
337
capabilities_by_region = {}
338
339
print("π Checking Recovery Services capabilities across regions...")
340
print("=" * 60)
341
342
for location in locations:
343
try:
344
capabilities = client.recovery_services.capabilities(
345
location=location,
346
input=ResourceCapabilities(type="Microsoft.RecoveryServices/vaults")
347
)
348
349
capabilities_info = {
350
"location": location,
351
"available": True,
352
"dns_zones": [],
353
"features": []
354
}
355
356
if capabilities.properties:
357
if capabilities.properties.dns_zones:
358
capabilities_info["dns_zones"] = [
359
zone.name for zone in capabilities.properties.dns_zones if zone.name
360
]
361
362
if capabilities.properties.dns_zone_response:
363
capabilities_info["dns_zone_responses"] = [
364
zone.name for zone in capabilities.properties.dns_zone_response if zone.name
365
]
366
367
capabilities_by_region[location] = capabilities_info
368
369
print(f"β {location}:")
370
if capabilities_info["dns_zones"]:
371
print(f" DNS Zones: {', '.join(capabilities_info['dns_zones'])}")
372
else:
373
print(" DNS Zones: Not specified")
374
375
except Exception as e:
376
capabilities_by_region[location] = {
377
"location": location,
378
"available": False,
379
"error": str(e)
380
}
381
print(f"β {location}: Error - {e}")
382
383
return capabilities_by_region
384
```
385
386
### Service Discovery and Documentation
387
388
```python
389
def discover_recovery_services_operations(client):
390
"""
391
Discover and document all available Recovery Services operations.
392
"""
393
394
print("π Discovering Recovery Services API Operations...")
395
print("=" * 60)
396
397
operations = client.operations.list()
398
operations_by_category = {}
399
400
for operation in operations:
401
if not operation.display:
402
continue
403
404
category = operation.display.resource or "General"
405
406
if category not in operations_by_category:
407
operations_by_category[category] = []
408
409
op_info = {
410
"name": operation.name,
411
"operation": operation.display.operation,
412
"description": operation.display.description,
413
"provider": operation.display.provider,
414
"origin": operation.origin
415
}
416
417
operations_by_category[category].append(op_info)
418
419
# Display results organized by category
420
for category, ops in operations_by_category.items():
421
print(f"\nπ {category} Operations:")
422
print("-" * 40)
423
424
for op in ops:
425
print(f" β’ {op['operation']}")
426
print(f" Name: {op['name']}")
427
if op['description']:
428
print(f" Description: {op['description']}")
429
print()
430
431
print(f"π Total operations discovered: {sum(len(ops) for ops in operations_by_category.values())}")
432
print(f"π Categories: {len(operations_by_category)}")
433
434
return operations_by_category
435
436
def validate_service_health(client, resource_group: str, location: str):
437
"""
438
Perform comprehensive service health validation.
439
"""
440
441
print("π₯ Recovery Services Health Check")
442
print("=" * 40)
443
444
health_status = {
445
"overall": "healthy",
446
"checks": [],
447
"warnings": [],
448
"errors": []
449
}
450
451
try:
452
# Test 1: Check if we can list operations
453
print("1οΈβ£ Testing operation discovery...")
454
operations = list(client.operations.list())
455
if operations:
456
health_status["checks"].append("β Operation discovery working")
457
print(f" Found {len(operations)} available operations")
458
else:
459
health_status["warnings"].append("β οΈ No operations discovered")
460
print(" β οΈ No operations found")
461
462
# Test 2: Check name availability API
463
print("\n2οΈβ£ Testing name availability API...")
464
test_name = f"health-check-test-{int(datetime.now().timestamp())}"
465
name_result = client.recovery_services.check_name_availability(
466
resource_group_name=resource_group,
467
location=location,
468
input=CheckNameAvailabilityParameters(
469
type="Microsoft.RecoveryServices/vaults",
470
name=test_name
471
)
472
)
473
474
if name_result.name_available is not None:
475
health_status["checks"].append("β Name availability API working")
476
print(f" Test name '{test_name}' availability: {name_result.name_available}")
477
else:
478
health_status["warnings"].append("β οΈ Name availability API returned no result")
479
print(" β οΈ Name availability check returned no result")
480
481
# Test 3: Check capabilities API
482
print("\n3οΈβ£ Testing capabilities API...")
483
capabilities = client.recovery_services.capabilities(
484
location=location,
485
input=ResourceCapabilities(type="Microsoft.RecoveryServices/vaults")
486
)
487
488
if capabilities:
489
health_status["checks"].append("β Capabilities API working")
490
print(" β Capabilities API responding")
491
492
if capabilities.properties and capabilities.properties.dns_zones:
493
print(f" Found {len(capabilities.properties.dns_zones)} DNS zone configurations")
494
else:
495
health_status["warnings"].append("β οΈ Capabilities API returned no data")
496
print(" β οΈ Capabilities API returned no data")
497
498
except Exception as e:
499
health_status["errors"].append(f"β Service health check failed: {e}")
500
health_status["overall"] = "unhealthy"
501
print(f"\nβ Health check failed: {e}")
502
503
# Determine overall status
504
if health_status["errors"]:
505
health_status["overall"] = "unhealthy"
506
elif health_status["warnings"]:
507
health_status["overall"] = "degraded"
508
509
print(f"\nπ Overall Service Health: {health_status['overall'].upper()}")
510
511
return health_status
512
```
513
514
### Identity Management Helpers
515
516
```python
517
def list_registered_identities_from_vault(vault_properties):
518
"""
519
Extract registered identity information from vault properties.
520
Note: This analyzes vault properties since there's no direct list API for registered identities.
521
"""
522
523
if not vault_properties:
524
print("No vault properties provided")
525
return []
526
527
identities = []
528
529
# Check for managed identity configuration
530
if hasattr(vault_properties, 'identity') and vault_properties.identity:
531
identity_info = {
532
"type": "managed_identity",
533
"identity_type": vault_properties.identity.type,
534
"principal_id": vault_properties.identity.principal_id,
535
"tenant_id": vault_properties.identity.tenant_id
536
}
537
538
if vault_properties.identity.user_assigned_identities:
539
identity_info["user_assigned_identities"] = list(vault_properties.identity.user_assigned_identities.keys())
540
541
identities.append(identity_info)
542
543
print(f"Found {len(identities)} identity configurations:")
544
for identity in identities:
545
print(f" Type: {identity['type']}")
546
if identity.get('identity_type'):
547
print(f" Identity Type: {identity['identity_type']}")
548
if identity.get('principal_id'):
549
print(f" Principal ID: {identity['principal_id']}")
550
if identity.get('user_assigned_identities'):
551
print(f" User Assigned Identities: {len(identity['user_assigned_identities'])}")
552
553
return identities
554
555
def safely_unregister_identity(client, resource_group: str, vault_name: str, identity_name: str, confirm: bool = False):
556
"""
557
Safely unregister an identity with confirmation and error handling.
558
"""
559
560
if not confirm:
561
print("β οΈ WARNING: This will unregister the identity from the vault.")
562
print(" This action may affect backup and recovery operations.")
563
print(" Set confirm=True to proceed.")
564
return False
565
566
try:
567
print(f"π Unregistering identity: {identity_name}")
568
569
client.registered_identities.delete(
570
resource_group_name=resource_group,
571
vault_name=vault_name,
572
identity_name=identity_name
573
)
574
575
print(f"β Successfully unregistered identity: {identity_name}")
576
print(" Note: It may take a few minutes for the change to take effect.")
577
578
return True
579
580
except Exception as e:
581
print(f"β Failed to unregister identity: {e}")
582
583
# Provide helpful error guidance
584
if "NotFound" in str(e):
585
print(" The identity may not exist or may already be unregistered.")
586
elif "Forbidden" in str(e):
587
print(" Check that you have sufficient permissions to manage vault identities.")
588
elif "Conflict" in str(e):
589
print(" The identity may be in use. Ensure no active backup/recovery operations depend on it.")
590
591
return False
592
```