0
# Location Operations
1
2
Location operations provide information about Azure regions, their capabilities, and resource usage for Azure Container Instances deployment planning.
3
4
## Usage Information
5
6
### List Usage Statistics { .api }
7
8
```python
9
def list_usage(location: str, **kwargs) -> UsageListResult:
10
"""
11
Get resource usage information for a specific Azure region.
12
13
Args:
14
location (str): Azure region name (e.g., "eastus", "westeurope", "southeastasia")
15
16
Returns:
17
UsageListResult: Usage statistics including current usage and limits
18
19
Example:
20
# Get usage for East US region
21
usage_info = client.location.list_usage("eastus")
22
23
for usage in usage_info.value:
24
print(f"Resource: {usage.name.localized_value}")
25
print(f"Current: {usage.current_value}")
26
print(f"Limit: {usage.limit}")
27
print(f"Unit: {usage.unit}")
28
print("---")
29
"""
30
```
31
32
## Capabilities Information
33
34
### List Capabilities { .api }
35
36
```python
37
def list_capabilities(location: str, **kwargs) -> CapabilitiesListResult:
38
"""
39
Get container capabilities and features available in a specific Azure region.
40
41
Args:
42
location (str): Azure region name (e.g., "eastus", "westeurope", "southeastasia")
43
44
Returns:
45
CapabilitiesListResult: Available capabilities including OS types, resource limits, and features
46
47
Example:
48
# Get capabilities for West Europe region
49
capabilities = client.location.list_capabilities("westeurope")
50
51
for capability in capabilities.value:
52
print(f"OS Type: {capability.os_type}")
53
print(f"Location: {capability.location}")
54
print(f"Max CPU: {capability.max_cpu}")
55
print(f"Max Memory GB: {capability.max_memory_in_gb}")
56
print(f"Max GPU Count: {capability.max_gpu_count}")
57
print("---")
58
"""
59
```
60
61
## Cached Images
62
63
### List Cached Images { .api }
64
65
```python
66
def list_cached_images(location: str, **kwargs) -> CachedImagesListResult:
67
"""
68
Get list of cached container images available in a specific Azure region.
69
Cached images provide faster container startup times.
70
71
Args:
72
location (str): Azure region name (e.g., "eastus", "westeurope", "southeastasia")
73
74
Returns:
75
CachedImagesListResult: List of cached container images with OS types
76
77
Example:
78
# Get cached images for South East Asia region
79
cached_images = client.location.list_cached_images("southeastasia")
80
81
for image_group in cached_images.value:
82
print(f"OS Type: {image_group.os_type}")
83
print("Available Images:")
84
for image in image_group.images:
85
print(f" - {image}")
86
print("---")
87
"""
88
```
89
90
## Usage Examples
91
92
### Region Selection for Deployment
93
94
```python
95
def find_optimal_region(client, required_cpu, required_memory, preferred_regions=None):
96
"""
97
Find the best Azure region for container deployment based on requirements.
98
99
Args:
100
client: ContainerInstanceManagementClient instance
101
required_cpu (float): Required CPU cores
102
required_memory (float): Required memory in GB
103
preferred_regions (List[str], optional): Preferred regions to check first
104
105
Returns:
106
str: Optimal region name for deployment
107
"""
108
109
# Default regions to check if none specified
110
if not preferred_regions:
111
preferred_regions = ["eastus", "westus2", "westeurope", "southeastasia", "centralus"]
112
113
suitable_regions = []
114
115
for region in preferred_regions:
116
try:
117
# Check capabilities
118
capabilities = client.location.list_capabilities(region)
119
120
for capability in capabilities.value:
121
if (capability.max_cpu >= required_cpu and
122
capability.max_memory_in_gb >= required_memory):
123
124
# Check current usage to avoid quota issues
125
usage = client.location.list_usage(region)
126
127
# Look for container groups usage
128
for usage_item in usage.value:
129
if "containerGroups" in usage_item.name.value:
130
available_capacity = usage_item.limit - usage_item.current_value
131
if available_capacity > 0:
132
suitable_regions.append({
133
'region': region,
134
'max_cpu': capability.max_cpu,
135
'max_memory': capability.max_memory_in_gb,
136
'available_capacity': available_capacity
137
})
138
break
139
break
140
141
except Exception as e:
142
print(f"Error checking region {region}: {e}")
143
continue
144
145
if not suitable_regions:
146
raise ValueError("No suitable regions found for the specified requirements")
147
148
# Sort by available capacity (descending)
149
suitable_regions.sort(key=lambda x: x['available_capacity'], reverse=True)
150
151
best_region = suitable_regions[0]
152
print(f"Selected region: {best_region['region']}")
153
print(f"Max CPU: {best_region['max_cpu']}, Max Memory: {best_region['max_memory']} GB")
154
print(f"Available capacity: {best_region['available_capacity']} container groups")
155
156
return best_region['region']
157
158
# Usage
159
optimal_region = find_optimal_region(
160
client=client,
161
required_cpu=2.0,
162
required_memory=4.0,
163
preferred_regions=["eastus", "westus2", "westeurope"]
164
)
165
```
166
167
### Check Resource Availability
168
169
```python
170
def check_resource_availability(client, location, required_container_groups=1):
171
"""
172
Check if sufficient resources are available in a region for deployment.
173
174
Args:
175
client: ContainerInstanceManagementClient instance
176
location (str): Azure region to check
177
required_container_groups (int): Number of container groups needed
178
179
Returns:
180
dict: Resource availability information
181
"""
182
183
try:
184
usage_info = client.location.list_usage(location)
185
capabilities_info = client.location.list_capabilities(location)
186
187
result = {
188
'location': location,
189
'can_deploy': True,
190
'usage_details': {},
191
'capabilities': {},
192
'warnings': []
193
}
194
195
# Check usage limits
196
for usage in usage_info.value:
197
usage_name = usage.name.value
198
current = usage.current_value
199
limit = usage.limit
200
available = limit - current
201
202
result['usage_details'][usage_name] = {
203
'current': current,
204
'limit': limit,
205
'available': available,
206
'unit': usage.unit
207
}
208
209
# Check if we have enough container groups available
210
if 'containerGroups' in usage_name and available < required_container_groups:
211
result['can_deploy'] = False
212
result['warnings'].append(f"Insufficient container group quota: need {required_container_groups}, available {available}")
213
214
# Get capabilities
215
for capability in capabilities_info.value:
216
result['capabilities'][capability.os_type] = {
217
'max_cpu': capability.max_cpu,
218
'max_memory_gb': capability.max_memory_in_gb,
219
'max_gpu_count': capability.max_gpu_count
220
}
221
222
return result
223
224
except Exception as e:
225
return {
226
'location': location,
227
'can_deploy': False,
228
'error': str(e)
229
}
230
231
# Usage
232
availability = check_resource_availability(client, "eastus", required_container_groups=5)
233
234
if availability['can_deploy']:
235
print(f"β Region {availability['location']} is suitable for deployment")
236
print(f"Container Groups available: {availability['usage_details'].get('containerGroups', {}).get('available', 'Unknown')}")
237
else:
238
print(f"β Region {availability['location']} cannot accommodate deployment")
239
for warning in availability.get('warnings', []):
240
print(f" - {warning}")
241
```
242
243
### Optimize Image Selection
244
245
```python
246
def get_cached_images_for_optimization(client, location, os_type="Linux"):
247
"""
248
Get cached images available in a region for faster container startup.
249
250
Args:
251
client: ContainerInstanceManagementClient instance
252
location (str): Azure region
253
os_type (str): Operating system type ("Linux" or "Windows")
254
255
Returns:
256
List[str]: List of cached image names for the specified OS
257
"""
258
259
try:
260
cached_images = client.location.list_cached_images(location)
261
262
for image_group in cached_images.value:
263
if image_group.os_type.lower() == os_type.lower():
264
return image_group.images
265
266
return []
267
268
except Exception as e:
269
print(f"Error retrieving cached images for {location}: {e}")
270
return []
271
272
def recommend_base_image(client, location, application_type):
273
"""
274
Recommend cached base images for faster deployment.
275
276
Args:
277
client: ContainerInstanceManagementClient instance
278
location (str): Azure region
279
application_type (str): Type of application ("web", "api", "worker", etc.)
280
281
Returns:
282
List[str]: Recommended cached images
283
"""
284
285
cached_images = get_cached_images_for_optimization(client, location, "Linux")
286
287
recommendations = []
288
image_patterns = {
289
'web': ['nginx', 'httpd', 'node'],
290
'api': ['node', 'python', 'openjdk', 'dotnet'],
291
'worker': ['python', 'openjdk', 'golang'],
292
'database': ['mysql', 'postgres', 'redis'],
293
'monitoring': ['prometheus', 'grafana']
294
}
295
296
if application_type in image_patterns:
297
patterns = image_patterns[application_type]
298
for image in cached_images:
299
for pattern in patterns:
300
if pattern in image.lower():
301
recommendations.append(image)
302
303
return recommendations[:5] # Return top 5 recommendations
304
305
# Usage
306
print("Cached images in East US:")
307
cached = get_cached_images_for_optimization(client, "eastus", "Linux")
308
for image in cached[:10]: # Show first 10
309
print(f" - {image}")
310
311
print("\nRecommended images for web applications:")
312
web_images = recommend_base_image(client, "eastus", "web")
313
for image in web_images:
314
print(f" - {image}")
315
```
316
317
### Multi-Region Deployment Planning
318
319
```python
320
def plan_multi_region_deployment(client, regions, container_specs):
321
"""
322
Plan deployment across multiple regions with capability and usage checks.
323
324
Args:
325
client: ContainerInstanceManagementClient instance
326
regions (List[str]): List of target regions
327
container_specs (dict): Container requirements
328
329
Returns:
330
dict: Deployment plan with region assignments
331
"""
332
333
deployment_plan = {
334
'feasible_regions': [],
335
'infeasible_regions': [],
336
'recommendations': []
337
}
338
339
required_cpu = container_specs.get('cpu', 1.0)
340
required_memory = container_specs.get('memory_gb', 1.0)
341
342
for region in regions:
343
try:
344
# Check capabilities
345
capabilities = client.location.list_capabilities(region)
346
usage = client.location.list_usage(region)
347
cached_images = client.location.list_cached_images(region)
348
349
region_info = {
350
'region': region,
351
'max_cpu': 0,
352
'max_memory': 0,
353
'available_capacity': 0,
354
'cached_images_count': 0,
355
'can_deploy': False
356
}
357
358
# Analyze capabilities
359
for capability in capabilities.value:
360
if capability.os_type == "Linux": # Assuming Linux containers
361
region_info['max_cpu'] = capability.max_cpu
362
region_info['max_memory'] = capability.max_memory_in_gb
363
364
if (capability.max_cpu >= required_cpu and
365
capability.max_memory_in_gb >= required_memory):
366
region_info['can_deploy'] = True
367
break
368
369
# Check usage
370
for usage_item in usage.value:
371
if 'containerGroups' in usage_item.name.value:
372
region_info['available_capacity'] = usage_item.limit - usage_item.current_value
373
break
374
375
# Count cached images
376
for image_group in cached_images.value:
377
if image_group.os_type == "Linux":
378
region_info['cached_images_count'] = len(image_group.images)
379
break
380
381
# Categorize region
382
if region_info['can_deploy'] and region_info['available_capacity'] > 0:
383
deployment_plan['feasible_regions'].append(region_info)
384
385
# Add recommendations based on cached images
386
if region_info['cached_images_count'] > 50:
387
deployment_plan['recommendations'].append(
388
f"Region {region} has {region_info['cached_images_count']} cached images - good for fast startup"
389
)
390
else:
391
deployment_plan['infeasible_regions'].append(region_info)
392
393
except Exception as e:
394
deployment_plan['infeasible_regions'].append({
395
'region': region,
396
'error': str(e),
397
'can_deploy': False
398
})
399
400
# Sort feasible regions by available capacity
401
deployment_plan['feasible_regions'].sort(
402
key=lambda x: x['available_capacity'],
403
reverse=True
404
)
405
406
return deployment_plan
407
408
# Usage
409
container_requirements = {
410
'cpu': 2.0,
411
'memory_gb': 4.0,
412
'os_type': 'Linux'
413
}
414
415
target_regions = ["eastus", "westus2", "westeurope", "southeastasia", "japaneast"]
416
417
plan = plan_multi_region_deployment(client, target_regions, container_requirements)
418
419
print("Deployment Plan:")
420
print(f"β Feasible regions ({len(plan['feasible_regions'])}):")
421
for region in plan['feasible_regions']:
422
print(f" - {region['region']}: {region['available_capacity']} available slots, {region['cached_images_count']} cached images")
423
424
print(f"\nβ Infeasible regions ({len(plan['infeasible_regions'])}):")
425
for region in plan['infeasible_regions']:
426
if 'error' in region:
427
print(f" - {region['region']}: Error - {region['error']}")
428
else:
429
print(f" - {region['region']}: Insufficient resources or capacity")
430
431
print(f"\nπ‘ Recommendations:")
432
for rec in plan['recommendations']:
433
print(f" - {rec}")
434
```