or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration-stores.mdindex.mdkey-values.mdmodels-and-types.mdoperations.mdprivate-networking.mdreplicas.mdsnapshots.md

replicas.mddocs/

0

# Replica Management Operations

1

2

The `ReplicasOperations` class provides comprehensive management capabilities for Azure App Configuration store replicas. Replicas enable multi-region deployment of your configuration stores, providing improved availability and performance for geographically distributed applications.

3

4

## Operations Class

5

6

```python { .api }

7

class ReplicasOperations:

8

"""

9

Operations for managing App Configuration store replicas.

10

11

Replicas allow you to create read-only copies of your configuration store in different

12

Azure regions, enabling improved performance and availability for distributed applications.

13

Configuration data is automatically synchronized from the primary store to all replicas.

14

"""

15

```

16

17

## Replica Lifecycle Management

18

19

### List Replicas

20

21

```python { .api }

22

def list_by_configuration_store(

23

self,

24

resource_group_name: str,

25

config_store_name: str,

26

skip_token: Optional[str] = None,

27

**kwargs: Any

28

) -> ItemPaged[Replica]:

29

"""

30

Lists all replicas for a specific App Configuration store.

31

32

Args:

33

resource_group_name: The name of the resource group containing the store.

34

config_store_name: The name of the configuration store.

35

skip_token: A skip token to retrieve the next set of results, if any.

36

**kwargs: Additional keyword arguments for the request.

37

38

Returns:

39

ItemPaged[Replica]: A paged collection of replicas for the store.

40

41

Example:

42

>>> replicas = client.replicas.list_by_configuration_store("my-rg", "my-store")

43

>>> for replica in replicas:

44

... print(f"Replica: {replica.name} in {replica.location}")

45

... print(f"Status: {replica.provisioning_state}")

46

... print(f"Endpoint: {replica.endpoint}")

47

"""

48

```

49

50

### Get Replica

51

52

```python { .api }

53

def get(

54

self,

55

resource_group_name: str,

56

config_store_name: str,

57

replica_name: str,

58

**kwargs: Any

59

) -> Replica:

60

"""

61

Gets the properties of a specific replica.

62

63

Args:

64

resource_group_name: The name of the resource group containing the store.

65

config_store_name: The name of the configuration store.

66

replica_name: The name of the replica.

67

**kwargs: Additional keyword arguments for the request.

68

69

Returns:

70

Replica: The replica details and properties.

71

72

Example:

73

>>> replica = client.replicas.get("my-rg", "my-store", "west-us-replica")

74

>>> print(f"Replica location: {replica.location}")

75

>>> print(f"Provisioning state: {replica.provisioning_state}")

76

>>> print(f"Endpoint: {replica.endpoint}")

77

"""

78

```

79

80

### Create Replica

81

82

```python { .api }

83

def begin_create(

84

self,

85

resource_group_name: str,

86

config_store_name: str,

87

replica_name: str,

88

replica_creation_parameters: Replica,

89

**kwargs: Any

90

) -> LROPoller[Replica]:

91

"""

92

Creates a new replica for an App Configuration store.

93

94

Args:

95

resource_group_name: The name of the resource group containing the store.

96

config_store_name: The name of the configuration store.

97

replica_name: The name for the new replica (must be unique within the store).

98

replica_creation_parameters: Parameters for creating the replica.

99

**kwargs: Additional keyword arguments for the request.

100

101

Returns:

102

LROPoller[Replica]: A poller for the long-running create operation.

103

104

Note:

105

Replica creation is asynchronous and may take several minutes to complete.

106

The replica will automatically synchronize configuration data from the primary store.

107

108

Example:

109

>>> from azure.mgmt.appconfiguration.models import Replica

110

>>> replica_params = Replica(location="West US 2")

111

>>> create_poller = client.replicas.begin_create(

112

... "my-rg", "my-store", "westus2-replica", replica_params

113

... )

114

>>> replica = create_poller.result() # Wait for completion

115

>>> print(f"Created replica: {replica.name} at {replica.endpoint}")

116

"""

117

```

118

119

### Delete Replica

120

121

```python { .api }

122

def begin_delete(

123

self,

124

resource_group_name: str,

125

config_store_name: str,

126

replica_name: str,

127

**kwargs: Any

128

) -> LROPoller[None]:

129

"""

130

Deletes a replica from an App Configuration store.

131

132

Args:

133

resource_group_name: The name of the resource group containing the store.

134

config_store_name: The name of the configuration store.

135

replica_name: The name of the replica to delete.

136

**kwargs: Additional keyword arguments for the request.

137

138

Returns:

139

LROPoller[None]: A poller for the long-running delete operation.

140

141

Warning:

142

Deleting a replica is permanent and cannot be undone. Applications using

143

the replica endpoint will need to be reconfigured to use different endpoints.

144

145

Example:

146

>>> delete_poller = client.replicas.begin_delete(

147

... "my-rg", "my-store", "old-replica"

148

... )

149

>>> delete_poller.wait() # Wait for deletion to complete

150

>>> print("Replica deleted successfully")

151

"""

152

```

153

154

## Replica Model

155

156

### Replica Class

157

158

```python { .api }

159

class Replica:

160

"""

161

Represents an App Configuration store replica.

162

163

Attributes:

164

id (str): The resource ID of the replica (read-only).

165

name (str): The name of the replica (read-only).

166

type (str): The resource type (read-only).

167

location (str): The Azure region where the replica is located.

168

endpoint (str): The endpoint URL for the replica (read-only).

169

provisioning_state (ReplicaProvisioningState): The provisioning state (read-only).

170

system_data (SystemData): System metadata for the replica (read-only).

171

"""

172

173

def __init__(

174

self,

175

*,

176

location: str,

177

**kwargs: Any

178

) -> None:

179

"""

180

Initialize a Replica instance.

181

182

Args:

183

location: The Azure region for the replica (e.g., "West US 2", "East Asia").

184

**kwargs: Additional properties.

185

"""

186

```

187

188

### ReplicaProvisioningState Enumeration

189

190

```python { .api }

191

class ReplicaProvisioningState:

192

"""

193

Enumeration of replica provisioning states.

194

195

Values:

196

CREATING: Replica is being created.

197

SUCCEEDED: Replica has been successfully created and is operational.

198

DELETING: Replica is being deleted.

199

FAILED: Replica creation or operation has failed.

200

CANCELED: Replica operation was canceled.

201

"""

202

CREATING = "Creating"

203

SUCCEEDED = "Succeeded"

204

DELETING = "Deleting"

205

FAILED = "Failed"

206

CANCELED = "Canceled"

207

```

208

209

## Practical Usage Examples

210

211

### Basic Replica Management

212

213

```python { .api }

214

from azure.mgmt.appconfiguration import AppConfigurationManagementClient

215

from azure.mgmt.appconfiguration.models import Replica, ReplicaProvisioningState

216

from azure.identity import DefaultAzureCredential

217

218

# Initialize client

219

credential = DefaultAzureCredential()

220

client = AppConfigurationManagementClient(credential, "subscription-id")

221

222

resource_group = "my-resource-group"

223

store_name = "my-config-store"

224

225

# Create replicas in multiple regions for global distribution

226

print("Creating replicas for global distribution...")

227

228

regions = {

229

"westus2-replica": "West US 2",

230

"eastus2-replica": "East US 2",

231

"westeurope-replica": "West Europe",

232

"southeastasia-replica": "Southeast Asia"

233

}

234

235

created_replicas = {}

236

237

for replica_name, location in regions.items():

238

print(f"Creating replica in {location}...")

239

240

replica_params = Replica(location=location)

241

242

try:

243

create_poller = client.replicas.begin_create(

244

resource_group,

245

store_name,

246

replica_name,

247

replica_params

248

)

249

250

# Monitor creation progress

251

print(f" Replica creation started for {location}")

252

replica = create_poller.result()

253

254

created_replicas[replica_name] = replica

255

print(f" ✓ Replica created: {replica.endpoint}")

256

257

except Exception as e:

258

print(f" ✗ Failed to create replica in {location}: {e}")

259

260

print(f"Successfully created {len(created_replicas)} replicas")

261

```

262

263

### Multi-Region Deployment Strategy

264

265

```python { .api }

266

def deploy_global_replica_strategy():

267

"""Deploy replicas using a strategic global distribution approach."""

268

269

# Define regions based on application user distribution

270

deployment_strategy = {

271

"primary": {

272

"region": "East US",

273

"description": "Primary region - no replica needed"

274

},

275

"americas": {

276

"region": "West US 2",

277

"replica_name": "americas-west-replica",

278

"description": "Serves western Americas"

279

},

280

"europe": {

281

"region": "West Europe",

282

"replica_name": "europe-replica",

283

"description": "Serves European users"

284

},

285

"asia": {

286

"region": "Southeast Asia",

287

"replica_name": "asia-replica",

288

"description": "Serves Asian Pacific users"

289

}

290

}

291

292

print("=== Global Replica Deployment Strategy ===")

293

294

# Check current replicas

295

print("\n1. Current replica status:")

296

existing_replicas = client.replicas.list_by_configuration_store(

297

resource_group, store_name

298

)

299

300

existing_names = set()

301

for replica in existing_replicas:

302

existing_names.add(replica.name)

303

print(f" Existing: {replica.name} in {replica.location} ({replica.provisioning_state})")

304

305

# Deploy missing replicas

306

print("\n2. Deploying missing replicas:")

307

deployment_results = {}

308

309

for region_key, config in deployment_strategy.items():

310

if region_key == "primary":

311

continue

312

313

replica_name = config["replica_name"]

314

315

if replica_name in existing_names:

316

print(f" ✓ {replica_name} already exists")

317

continue

318

319

print(f" Creating {replica_name} in {config['region']}...")

320

print(f" Purpose: {config['description']}")

321

322

try:

323

replica_params = Replica(location=config["region"])

324

325

create_poller = client.replicas.begin_create(

326

resource_group,

327

store_name,

328

replica_name,

329

replica_params

330

)

331

332

# Store poller for batch monitoring

333

deployment_results[replica_name] = {

334

"poller": create_poller,

335

"config": config

336

}

337

338

except Exception as e:

339

print(f" ✗ Failed to start creation: {e}")

340

deployment_results[replica_name] = {"error": str(e)}

341

342

# Monitor all deployments

343

print("\n3. Monitoring deployments:")

344

for replica_name, result in deployment_results.items():

345

if "error" in result:

346

print(f" ✗ {replica_name}: {result['error']}")

347

continue

348

349

try:

350

poller = result["poller"]

351

print(f" Waiting for {replica_name}...")

352

353

replica = poller.result() # This will wait for completion

354

355

print(f" ✓ {replica_name} deployed successfully")

356

print(f" Endpoint: {replica.endpoint}")

357

358

except Exception as e:

359

print(f" ✗ {replica_name} deployment failed: {e}")

360

361

# Final status check

362

print("\n4. Final deployment status:")

363

final_replicas = client.replicas.list_by_configuration_store(

364

resource_group, store_name

365

)

366

367

for replica in final_replicas:

368

region_info = next(

369

(f" ({config['description']})"

370

for config in deployment_strategy.values()

371

if config.get("region") == replica.location),

372

""

373

)

374

print(f" {replica.name}: {replica.location}{region_info} - {replica.provisioning_state}")

375

376

# Execute deployment strategy

377

deploy_global_replica_strategy()

378

```

379

380

### Replica Health Monitoring

381

382

```python { .api }

383

def monitor_replica_health():

384

"""Monitor the health and status of all replicas."""

385

386

print("=== Replica Health Monitor ===")

387

388

replicas = client.replicas.list_by_configuration_store(

389

resource_group, store_name

390

)

391

392

replica_list = list(replicas)

393

394

if not replica_list:

395

print("No replicas found for this configuration store")

396

return

397

398

print(f"Monitoring {len(replica_list)} replicas:")

399

400

health_summary = {

401

"total": len(replica_list),

402

"healthy": 0,

403

"creating": 0,

404

"failed": 0,

405

"deleting": 0,

406

"unknown": 0

407

}

408

409

for replica in replica_list:

410

state = replica.provisioning_state

411

412

print(f"\n📍 Replica: {replica.name}")

413

print(f" Location: {replica.location}")

414

print(f" Endpoint: {replica.endpoint}")

415

print(f" Status: {state}")

416

417

# Categorize health status

418

if state == ReplicaProvisioningState.SUCCEEDED:

419

health_summary["healthy"] += 1

420

print(" 🟢 Status: Healthy")

421

elif state == ReplicaProvisioningState.CREATING:

422

health_summary["creating"] += 1

423

print(" 🟡 Status: Creating...")

424

elif state == ReplicaProvisioningState.FAILED:

425

health_summary["failed"] += 1

426

print(" 🔴 Status: Failed")

427

elif state == ReplicaProvisioningState.DELETING:

428

health_summary["deleting"] += 1

429

print(" 🟠 Status: Deleting...")

430

else:

431

health_summary["unknown"] += 1

432

print(" ⚪ Status: Unknown")

433

434

# Additional health checks could include:

435

# - Network connectivity tests

436

# - Configuration synchronization status

437

# - Performance metrics

438

439

if replica.system_data:

440

print(f" Created: {replica.system_data.created_at}")

441

print(f" Created by: {replica.system_data.created_by}")

442

443

# Health summary

444

print(f"\n=== Health Summary ===")

445

print(f"Total Replicas: {health_summary['total']}")

446

print(f"🟢 Healthy: {health_summary['healthy']}")

447

print(f"🟡 Creating: {health_summary['creating']}")

448

print(f"🔴 Failed: {health_summary['failed']}")

449

print(f"🟠 Deleting: {health_summary['deleting']}")

450

451

if health_summary["failed"] > 0:

452

print(f"\n⚠️ {health_summary['failed']} replica(s) require attention")

453

454

healthy_percentage = (health_summary["healthy"] / health_summary["total"]) * 100

455

print(f"Health Score: {healthy_percentage:.1f}%")

456

457

return health_summary

458

459

# Run health monitoring

460

health_status = monitor_replica_health()

461

```

462

463

### Replica Performance Optimization

464

465

```python { .api }

466

def optimize_replica_distribution():

467

"""Analyze and optimize replica distribution for performance."""

468

469

print("=== Replica Distribution Analysis ===")

470

471

# Get all replicas

472

replicas = client.replicas.list_by_configuration_store(

473

resource_group, store_name

474

)

475

476

replica_locations = []

477

for replica in replicas:

478

if replica.provisioning_state == ReplicaProvisioningState.SUCCEEDED:

479

replica_locations.append({

480

"name": replica.name,

481

"location": replica.location,

482

"endpoint": replica.endpoint

483

})

484

485

print(f"Active replicas: {len(replica_locations)}")

486

487

# Define region groups for analysis

488

region_groups = {

489

"US East": ["East US", "East US 2", "Central US"],

490

"US West": ["West US", "West US 2", "West Central US"],

491

"Europe": ["West Europe", "North Europe", "UK South"],

492

"Asia": ["Southeast Asia", "East Asia", "Japan East"],

493

"Other": []

494

}

495

496

# Categorize replicas by region group

497

distribution = {group: [] for group in region_groups.keys()}

498

499

for replica in replica_locations:

500

location = replica["location"]

501

assigned = False

502

503

for group, regions in region_groups.items():

504

if location in regions:

505

distribution[group].append(replica)

506

assigned = True

507

break

508

509

if not assigned:

510

distribution["Other"].append(replica)

511

512

# Analysis results

513

print("\nDistribution by region:")

514

for group, replicas in distribution.items():

515

print(f" {group}: {len(replicas)} replica(s)")

516

for replica in replicas:

517

print(f" - {replica['name']} ({replica['location']})")

518

519

# Optimization recommendations

520

print("\n=== Optimization Recommendations ===")

521

522

total_replicas = len(replica_locations)

523

524

if total_replicas == 0:

525

print("⚠️ No active replicas found. Consider creating replicas for:")

526

print(" - Geographic regions where your users are located")

527

print(" - Disaster recovery purposes")

528

return

529

530

# Check for regional gaps

531

empty_regions = [group for group, replicas in distribution.items()

532

if len(replicas) == 0 and group != "Other"]

533

534

if empty_regions:

535

print(f"🌍 Geographic gaps detected in: {', '.join(empty_regions)}")

536

print(" Consider adding replicas in these regions for better global coverage")

537

538

# Check for over-concentration

539

max_replicas_per_region = max(len(replicas) for replicas in distribution.values())

540

if max_replicas_per_region > 2:

541

concentrated_regions = [group for group, replicas in distribution.items()

542

if len(replicas) > 2]

543

print(f"📍 High concentration in: {', '.join(concentrated_regions)}")

544

print(" Consider distributing replicas more evenly across regions")

545

546

# Cost optimization

547

if total_replicas > 5:

548

print(f"💰 Cost optimization: {total_replicas} replicas may be more than needed")

549

print(" Review usage patterns and consider consolidating underused replicas")

550

551

# Performance recommendations

552

print("\n🚀 Performance recommendations:")

553

print(" - Place replicas close to your application users")

554

print(" - Use replica endpoints in application configuration")

555

print(" - Implement failover logic for high availability")

556

print(" - Monitor replica synchronization lag")

557

558

return distribution

559

560

# Run optimization analysis

561

distribution_analysis = optimize_replica_distribution()

562

```

563

564

### Replica Disaster Recovery

565

566

```python { .api }

567

def setup_disaster_recovery_replicas():

568

"""Set up replicas specifically for disaster recovery purposes."""

569

570

print("=== Disaster Recovery Replica Setup ===")

571

572

# Get primary store details

573

primary_store = client.configuration_stores.get(resource_group, store_name)

574

primary_region = primary_store.location

575

576

print(f"Primary store location: {primary_region}")

577

578

# Define disaster recovery regions based on primary location

579

dr_regions = {

580

"East US": ["West US 2", "Central US"],

581

"East US 2": ["West US 2", "South Central US"],

582

"West US": ["East US 2", "Central US"],

583

"West US 2": ["East US 2", "South Central US"],

584

"Central US": ["East US 2", "West US 2"],

585

"West Europe": ["North Europe", "UK South"],

586

"North Europe": ["West Europe", "UK West"],

587

"Southeast Asia": ["East Asia", "Australia East"]

588

}

589

590

recommended_dr_regions = dr_regions.get(primary_region, ["East US 2", "West US 2"])

591

592

print(f"Recommended DR regions for {primary_region}: {recommended_dr_regions}")

593

594

# Check existing replicas

595

existing_replicas = client.replicas.list_by_configuration_store(

596

resource_group, store_name

597

)

598

599

existing_locations = {replica.location for replica in existing_replicas

600

if replica.provisioning_state == ReplicaProvisioningState.SUCCEEDED}

601

602

print(f"Existing replica locations: {existing_locations}")

603

604

# Create DR replicas

605

dr_replicas_needed = [region for region in recommended_dr_regions

606

if region not in existing_locations]

607

608

if not dr_replicas_needed:

609

print("✓ Disaster recovery replicas already exist")

610

return

611

612

print(f"Creating DR replicas in: {dr_replicas_needed}")

613

614

dr_results = []

615

616

for i, dr_region in enumerate(dr_replicas_needed):

617

replica_name = f"dr-replica-{i+1}"

618

619

print(f"Creating DR replica: {replica_name} in {dr_region}")

620

621

try:

622

replica_params = Replica(location=dr_region)

623

624

create_poller = client.replicas.begin_create(

625

resource_group,

626

store_name,

627

replica_name,

628

replica_params

629

)

630

631

print(f" ⏳ Creation started...")

632

replica = create_poller.result()

633

634

dr_results.append({

635

"name": replica.name,

636

"location": replica.location,

637

"endpoint": replica.endpoint,

638

"status": "success"

639

})

640

641

print(f" ✓ DR replica created: {replica.endpoint}")

642

643

except Exception as e:

644

print(f" ✗ Failed to create DR replica: {e}")

645

dr_results.append({

646

"name": replica_name,

647

"location": dr_region,

648

"status": "failed",

649

"error": str(e)

650

})

651

652

# DR readiness summary

653

print(f"\n=== DR Readiness Summary ===")

654

successful_dr = [r for r in dr_results if r["status"] == "success"]

655

656

print(f"Primary region: {primary_region}")

657

print(f"DR replicas created: {len(successful_dr)}")

658

659

for replica in successful_dr:

660

print(f" - {replica['name']}: {replica['location']}")

661

print(f" Endpoint: {replica['endpoint']}")

662

663

if len(successful_dr) >= 1:

664

print("✅ Basic disaster recovery capability established")

665

if len(successful_dr) >= 2:

666

print("✅ Enhanced disaster recovery with multiple regions")

667

668

# Generate DR runbook

669

print(f"\n=== Disaster Recovery Runbook ===")

670

print("In case of primary region failure:")

671

print("1. Verify primary store is inaccessible")

672

print("2. Update application configuration to use DR endpoints:")

673

674

for replica in successful_dr:

675

print(f" - {replica['endpoint']}")

676

677

print("3. Monitor application functionality")

678

print("4. When primary region recovers, switch back to primary endpoint")

679

print("5. Verify configuration synchronization")

680

681

return dr_results

682

683

# Set up disaster recovery

684

dr_setup_results = setup_disaster_recovery_replicas()

685

```

686

687

### Replica Maintenance and Cleanup

688

689

```python { .api }

690

def maintain_replicas():

691

"""Perform maintenance tasks on replicas."""

692

693

print("=== Replica Maintenance ===")

694

695

# Get all replicas

696

replicas = client.replicas.list_by_configuration_store(

697

resource_group, store_name

698

)

699

700

replica_list = list(replicas)

701

702

maintenance_actions = []

703

704

for replica in replica_list:

705

print(f"\nAnalyzing replica: {replica.name}")

706

print(f" Location: {replica.location}")

707

print(f" Status: {replica.provisioning_state}")

708

709

# Check for failed replicas

710

if replica.provisioning_state == ReplicaProvisioningState.FAILED:

711

maintenance_actions.append({

712

"action": "delete_failed",

713

"replica": replica,

714

"reason": "Replica is in failed state and should be removed"

715

})

716

print(f" 🔴 Action needed: Remove failed replica")

717

718

# Check for long-running creation

719

elif replica.provisioning_state == ReplicaProvisioningState.CREATING:

720

# In a real scenario, you might check creation timestamp

721

maintenance_actions.append({

722

"action": "monitor_creation",

723

"replica": replica,

724

"reason": "Replica has been creating for extended period"

725

})

726

print(f" 🟡 Action needed: Monitor creation progress")

727

728

# Check for successful replicas (health check placeholder)

729

elif replica.provisioning_state == ReplicaProvisioningState.SUCCEEDED:

730

print(f" ✅ Replica is healthy")

731

732

# Execute maintenance actions

733

if maintenance_actions:

734

print(f"\n=== Maintenance Actions ({len(maintenance_actions)}) ===")

735

736

for action in maintenance_actions:

737

print(f"\nAction: {action['action']}")

738

print(f"Replica: {action['replica'].name}")

739

print(f"Reason: {action['reason']}")

740

741

if action['action'] == 'delete_failed':

742

response = input(f"Delete failed replica '{action['replica'].name}'? (y/N): ")

743

744

if response.lower() == 'y':

745

try:

746

delete_poller = client.replicas.begin_delete(

747

resource_group,

748

store_name,

749

action['replica'].name

750

)

751

delete_poller.wait()

752

print(f" ✓ Deleted failed replica: {action['replica'].name}")

753

754

except Exception as e:

755

print(f" ✗ Failed to delete replica: {e}")

756

else:

757

print(" Skipped deletion")

758

759

elif action['action'] == 'monitor_creation':

760

# Get updated status

761

try:

762

current_replica = client.replicas.get(

763

resource_group, store_name, action['replica'].name

764

)

765

print(f" Current status: {current_replica.provisioning_state}")

766

767

if current_replica.provisioning_state == ReplicaProvisioningState.SUCCEEDED:

768

print(f" ✅ Replica creation completed successfully")

769

elif current_replica.provisioning_state == ReplicaProvisioningState.FAILED:

770

print(f" ❌ Replica creation failed")

771

772

except Exception as e:

773

print(f" ✗ Could not check replica status: {e}")

774

else:

775

print("\n✅ No maintenance actions required")

776

777

# Final status summary

778

print(f"\n=== Final Status ===")

779

final_replicas = client.replicas.list_by_configuration_store(

780

resource_group, store_name

781

)

782

783

status_counts = {}

784

for replica in final_replicas:

785

state = replica.provisioning_state

786

status_counts[state] = status_counts.get(state, 0) + 1

787

788

for status, count in status_counts.items():

789

print(f" {status}: {count}")

790

791

# Run maintenance

792

maintain_replicas()

793

```

794

795

## Asynchronous Operations

796

797

```python { .api }

798

from azure.mgmt.appconfiguration.aio import AppConfigurationManagementClient

799

from azure.identity.aio import DefaultAzureCredential

800

import asyncio

801

802

async def async_replica_operations():

803

"""Demonstrate asynchronous replica operations."""

804

805

credential = DefaultAzureCredential()

806

807

async with AppConfigurationManagementClient(credential, "subscription-id") as client:

808

809

# Create multiple replicas concurrently

810

replica_tasks = []

811

regions = ["West US 2", "West Europe", "Southeast Asia"]

812

813

for i, region in enumerate(regions):

814

replica_name = f"async-replica-{i+1}"

815

replica_params = Replica(location=region)

816

817

task = client.replicas.begin_create(

818

resource_group, store_name, replica_name, replica_params

819

)

820

replica_tasks.append((replica_name, region, task))

821

822

print("Creating replicas concurrently...")

823

824

# Wait for all creation operations to start

825

pollers = []

826

for replica_name, region, task in replica_tasks:

827

try:

828

poller = await task

829

pollers.append((replica_name, region, poller))

830

print(f"✓ Started creation of {replica_name} in {region}")

831

except Exception as e:

832

print(f"✗ Failed to start {replica_name}: {e}")

833

834

# Wait for all replicas to be created

835

print("Waiting for replica creation to complete...")

836

837

completed_replicas = []

838

for replica_name, region, poller in pollers:

839

try:

840

replica = await poller.result()

841

completed_replicas.append(replica)

842

print(f"✅ {replica_name} created: {replica.endpoint}")

843

except Exception as e:

844

print(f"❌ {replica_name} failed: {e}")

845

846

# List all replicas

847

print(f"\nFinal replica list:")

848

replicas = client.replicas.list_by_configuration_store(

849

resource_group, store_name

850

)

851

852

async for replica in replicas:

853

print(f" - {replica.name}: {replica.location} ({replica.provisioning_state})")

854

855

# Run async operations

856

asyncio.run(async_replica_operations())

857

```

858

859

## Best Practices

860

861

### Replica Naming Conventions

862

863

```python { .api }

864

def demonstrate_naming_conventions():

865

"""Show recommended naming conventions for replicas."""

866

867

naming_examples = {

868

"Geographic": {

869

"pattern": "{region-code}-replica",

870

"examples": ["usw2-replica", "euw-replica", "sea-replica"],

871

"use_case": "Simple geographic identification"

872

},

873

"Purpose-based": {

874

"pattern": "{purpose}-{region}-replica",

875

"examples": ["dr-usw2-replica", "perf-euw-replica", "test-sea-replica"],

876

"use_case": "Identify replica purpose and location"

877

},

878

"Environment": {

879

"pattern": "{env}-{region}-replica",

880

"examples": ["prod-usw2-replica", "stage-euw-replica", "dev-sea-replica"],

881

"use_case": "Environment-specific replicas"

882

},

883

"Sequential": {

884

"pattern": "replica-{number}",

885

"examples": ["replica-01", "replica-02", "replica-03"],

886

"use_case": "Simple sequential numbering"

887

}

888

}

889

890

print("=== Replica Naming Convention Guidelines ===")

891

892

for convention, details in naming_examples.items():

893

print(f"\n{convention} Convention:")

894

print(f" Pattern: {details['pattern']}")

895

print(f" Examples: {', '.join(details['examples'])}")

896

print(f" Use case: {details['use_case']}")

897

898

print(f"\nRecommendations:")

899

print(f" - Keep names under 64 characters")

900

print(f" - Use lowercase letters, numbers, and hyphens only")

901

print(f" - Be consistent across your organization")

902

print(f" - Include region information for geographic distribution")

903

print(f" - Consider including purpose or environment when relevant")

904

905

demonstrate_naming_conventions()

906

```