0
# Traffic Manager Client
1
2
Primary client class for managing all Traffic Manager resources with Azure authentication and subscription-based operations. The client provides access to all Traffic Manager management capabilities through organized operation groups.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Creates a Traffic Manager management client with Azure authentication and subscription context.
9
10
```python { .api }
11
class TrafficManagerManagementClient:
12
"""Main client for Traffic Manager management operations."""
13
14
def __init__(
15
self,
16
credential: TokenCredential,
17
subscription_id: str,
18
base_url: str = "https://management.azure.com",
19
**kwargs
20
):
21
"""
22
Initialize Traffic Manager management client.
23
24
Args:
25
credential (TokenCredential): Azure authentication credential
26
subscription_id (str): Azure subscription ID
27
base_url (str): Azure Resource Manager endpoint URL
28
**kwargs: Additional client configuration options
29
"""
30
31
def close(self) -> None:
32
"""Close the client and release resources."""
33
34
def __enter__(self) -> "TrafficManagerManagementClient":
35
"""Context manager entry."""
36
37
def __exit__(self, *exc_details) -> None:
38
"""Context manager exit with cleanup."""
39
```
40
41
### Client Configuration Examples
42
43
```python
44
from azure.mgmt.trafficmanager import TrafficManagerManagementClient
45
from azure.identity import DefaultAzureCredential, ClientSecretCredential, ManagedIdentityCredential
46
47
# Basic client with default credential
48
credential = DefaultAzureCredential()
49
client = TrafficManagerManagementClient(credential, "your-subscription-id")
50
51
# Client with service principal authentication
52
credential = ClientSecretCredential(
53
tenant_id="your-tenant-id",
54
client_id="your-client-id",
55
client_secret="your-client-secret"
56
)
57
client = TrafficManagerManagementClient(credential, "your-subscription-id")
58
59
# Client with managed identity (for Azure resources)
60
credential = ManagedIdentityCredential()
61
client = TrafficManagerManagementClient(credential, "your-subscription-id")
62
63
# Client with custom endpoint (e.g., Azure Government)
64
client = TrafficManagerManagementClient(
65
credential,
66
"your-subscription-id",
67
base_url="https://management.usgovcloudapi.net"
68
)
69
70
# Context manager usage for automatic cleanup
71
with TrafficManagerManagementClient(credential, subscription_id) as client:
72
profiles = list(client.profiles.list_by_subscription())
73
# Client automatically closed when exiting context
74
```
75
76
### Async Client
77
78
For asynchronous operations, use the async version of the client.
79
80
```python { .api }
81
from azure.mgmt.trafficmanager.aio import TrafficManagerManagementClient
82
83
class TrafficManagerManagementClient:
84
"""Async Traffic Manager management client."""
85
86
def __init__(
87
self,
88
credential: AsyncTokenCredential,
89
subscription_id: str,
90
base_url: str = "https://management.azure.com",
91
**kwargs
92
): ...
93
94
async def close(self) -> None:
95
"""Close the async client and release resources."""
96
97
async def __aenter__(self) -> "TrafficManagerManagementClient":
98
"""Async context manager entry."""
99
100
async def __aexit__(self, *exc_details) -> None:
101
"""Async context manager exit with cleanup."""
102
```
103
104
**Async Usage Examples:**
105
106
```python
107
import asyncio
108
from azure.mgmt.trafficmanager.aio import TrafficManagerManagementClient
109
from azure.identity.aio import DefaultAzureCredential
110
111
async def manage_traffic_manager():
112
credential = DefaultAzureCredential()
113
114
async with TrafficManagerManagementClient(credential, subscription_id) as client:
115
# List all profiles asynchronously
116
profiles = []
117
async for profile in client.profiles.list_by_subscription():
118
profiles.append(profile)
119
120
# Create multiple operations concurrently
121
tasks = []
122
for i in range(3):
123
task = client.profiles.get("my-rg", f"profile-{i}")
124
tasks.append(task)
125
126
results = await asyncio.gather(*tasks, return_exceptions=True)
127
128
for result in results:
129
if isinstance(result, Exception):
130
print(f"Error: {result}")
131
else:
132
print(f"Profile: {result.name}")
133
134
# Run async operations
135
asyncio.run(manage_traffic_manager())
136
```
137
138
## Client Operation Groups
139
140
The client provides access to Traffic Manager operations through specialized operation group properties:
141
142
### Operations Groups
143
144
```python { .api }
145
class TrafficManagerManagementClient:
146
"""Client operation groups for Traffic Manager resources."""
147
148
# Profile management operations
149
profiles: ProfilesOperations
150
151
# Endpoint management operations
152
endpoints: EndpointsOperations
153
154
# Geographic hierarchy operations
155
geographic_hierarchies: GeographicHierarchiesOperations
156
157
# Heat map and analytics operations
158
heat_map: HeatMapOperations
159
160
# Real user metrics operations
161
traffic_manager_user_metrics_keys: TrafficManagerUserMetricsKeysOperations
162
```
163
164
### Operation Group Usage
165
166
```python
167
# Access different operation groups through the client
168
client = TrafficManagerManagementClient(credential, subscription_id)
169
170
# Profile operations
171
profiles = list(client.profiles.list_by_subscription())
172
profile = client.profiles.get("my-rg", "my-profile")
173
174
# Endpoint operations
175
endpoint = client.endpoints.get("my-rg", "my-profile", "AzureEndpoints", "my-endpoint")
176
177
# Geographic operations
178
geo_hierarchy = client.geographic_hierarchies.get_default()
179
180
# Analytics operations
181
heat_map = client.heat_map.get("my-rg", "my-profile")
182
183
# User metrics operations
184
rum_key = client.traffic_manager_user_metrics_keys.create_or_update()
185
```
186
187
## Advanced Client Configuration
188
189
### Retry and Timeout Configuration
190
191
```python
192
from azure.core.pipeline.policies import RetryPolicy
193
from azure.mgmt.trafficmanager import TrafficManagerManagementClient
194
195
# Configure custom retry policy
196
retry_policy = RetryPolicy(
197
retry_total=5,
198
retry_backoff_factor=2.0,
199
retry_on_status_codes=[408, 429, 500, 502, 503, 504]
200
)
201
202
client = TrafficManagerManagementClient(
203
credential,
204
subscription_id,
205
retry_policy=retry_policy,
206
timeout=60 # 60 second timeout
207
)
208
```
209
210
### Custom Headers and User Agent
211
212
```python
213
# Add custom headers and user agent
214
client = TrafficManagerManagementClient(
215
credential,
216
subscription_id,
217
user_agent_policy=UserAgentPolicy("MyApp/1.0"),
218
headers_policy=HeadersPolicy({"X-Custom-Header": "MyValue"})
219
)
220
```
221
222
### Logging Configuration
223
224
```python
225
import logging
226
from azure.mgmt.trafficmanager import TrafficManagerManagementClient
227
228
# Enable Azure SDK logging
229
logging.basicConfig(level=logging.DEBUG)
230
logger = logging.getLogger("azure.mgmt.trafficmanager")
231
logger.setLevel(logging.DEBUG)
232
233
# Client will now log HTTP requests and responses
234
client = TrafficManagerManagementClient(credential, subscription_id)
235
```
236
237
## Error Handling
238
239
### Common Exception Types
240
241
```python
242
from azure.core.exceptions import (
243
HttpResponseError,
244
ResourceNotFoundError,
245
ClientAuthenticationError,
246
ResourceExistsError
247
)
248
249
try:
250
profile = client.profiles.get("my-rg", "nonexistent-profile")
251
except ResourceNotFoundError as e:
252
print(f"Profile not found: {e.message}")
253
except ClientAuthenticationError as e:
254
print(f"Authentication failed: {e.message}")
255
except HttpResponseError as e:
256
print(f"HTTP error {e.status_code}: {e.message}")
257
```
258
259
### Comprehensive Error Handling
260
261
```python
262
def safe_traffic_manager_operation():
263
try:
264
client = TrafficManagerManagementClient(credential, subscription_id)
265
266
# Attempt operation
267
profile = client.profiles.create_or_update(
268
"my-rg",
269
"my-profile",
270
profile_config
271
)
272
273
return profile
274
275
except ClientAuthenticationError:
276
print("Authentication failed - check credentials")
277
raise
278
except ResourceExistsError:
279
print("Profile already exists - use update instead")
280
return client.profiles.get("my-rg", "my-profile")
281
except ResourceNotFoundError:
282
print("Resource group not found - create it first")
283
raise
284
except HttpResponseError as e:
285
if e.status_code == 429:
286
print("Rate limited - retry after delay")
287
time.sleep(60)
288
return safe_traffic_manager_operation()
289
else:
290
print(f"Unexpected HTTP error: {e.status_code} - {e.message}")
291
raise
292
except Exception as e:
293
print(f"Unexpected error: {type(e).__name__} - {e}")
294
raise
295
finally:
296
# Always close client
297
client.close()
298
```
299
300
## Authentication Patterns
301
302
### Service Principal Authentication
303
304
```python
305
from azure.identity import ClientSecretCredential
306
307
# Service principal with secret
308
credential = ClientSecretCredential(
309
tenant_id="00000000-0000-0000-0000-000000000000",
310
client_id="11111111-1111-1111-1111-111111111111",
311
client_secret="your-client-secret"
312
)
313
314
# Service principal with certificate
315
from azure.identity import CertificateCredential
316
317
credential = CertificateCredential(
318
tenant_id="00000000-0000-0000-0000-000000000000",
319
client_id="11111111-1111-1111-1111-111111111111",
320
certificate_path="/path/to/cert.pem"
321
)
322
```
323
324
### Managed Identity Authentication
325
326
```python
327
from azure.identity import ManagedIdentityCredential
328
329
# System-assigned managed identity
330
credential = ManagedIdentityCredential()
331
332
# User-assigned managed identity
333
credential = ManagedIdentityCredential(
334
client_id="22222222-2222-2222-2222-222222222222"
335
)
336
```
337
338
### Development Authentication
339
340
```python
341
from azure.identity import AzureCliCredential, InteractiveBrowserCredential
342
343
# Use Azure CLI credentials (for development)
344
credential = AzureCliCredential()
345
346
# Interactive browser authentication (for development)
347
credential = InteractiveBrowserCredential(
348
tenant_id="00000000-0000-0000-0000-000000000000"
349
)
350
```
351
352
### Credential Chain
353
354
```python
355
from azure.identity import DefaultAzureCredential, ChainedTokenCredential
356
357
# Default credential chain (recommended for production)
358
credential = DefaultAzureCredential()
359
360
# Custom credential chain
361
credential = ChainedTokenCredential(
362
ManagedIdentityCredential(), # Try managed identity first
363
ClientSecretCredential(...), # Then service principal
364
AzureCliCredential() # Finally CLI credentials
365
)
366
```