Microsoft Azure Container Instance Client Library for Python providing comprehensive management capabilities for containerized applications in Azure cloud.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Location operations provide information about Azure regions, their capabilities, and resource usage for Azure Container Instances deployment planning.
def list_usage(location: str, **kwargs) -> UsageListResult:
"""
Get resource usage information for a specific Azure region.
Args:
location (str): Azure region name (e.g., "eastus", "westeurope", "southeastasia")
Returns:
UsageListResult: Usage statistics including current usage and limits
Example:
# Get usage for East US region
usage_info = client.location.list_usage("eastus")
for usage in usage_info.value:
print(f"Resource: {usage.name.localized_value}")
print(f"Current: {usage.current_value}")
print(f"Limit: {usage.limit}")
print(f"Unit: {usage.unit}")
print("---")
"""def list_capabilities(location: str, **kwargs) -> CapabilitiesListResult:
"""
Get container capabilities and features available in a specific Azure region.
Args:
location (str): Azure region name (e.g., "eastus", "westeurope", "southeastasia")
Returns:
CapabilitiesListResult: Available capabilities including OS types, resource limits, and features
Example:
# Get capabilities for West Europe region
capabilities = client.location.list_capabilities("westeurope")
for capability in capabilities.value:
print(f"OS Type: {capability.os_type}")
print(f"Location: {capability.location}")
print(f"Max CPU: {capability.max_cpu}")
print(f"Max Memory GB: {capability.max_memory_in_gb}")
print(f"Max GPU Count: {capability.max_gpu_count}")
print("---")
"""def list_cached_images(location: str, **kwargs) -> CachedImagesListResult:
"""
Get list of cached container images available in a specific Azure region.
Cached images provide faster container startup times.
Args:
location (str): Azure region name (e.g., "eastus", "westeurope", "southeastasia")
Returns:
CachedImagesListResult: List of cached container images with OS types
Example:
# Get cached images for South East Asia region
cached_images = client.location.list_cached_images("southeastasia")
for image_group in cached_images.value:
print(f"OS Type: {image_group.os_type}")
print("Available Images:")
for image in image_group.images:
print(f" - {image}")
print("---")
"""def find_optimal_region(client, required_cpu, required_memory, preferred_regions=None):
"""
Find the best Azure region for container deployment based on requirements.
Args:
client: ContainerInstanceManagementClient instance
required_cpu (float): Required CPU cores
required_memory (float): Required memory in GB
preferred_regions (List[str], optional): Preferred regions to check first
Returns:
str: Optimal region name for deployment
"""
# Default regions to check if none specified
if not preferred_regions:
preferred_regions = ["eastus", "westus2", "westeurope", "southeastasia", "centralus"]
suitable_regions = []
for region in preferred_regions:
try:
# Check capabilities
capabilities = client.location.list_capabilities(region)
for capability in capabilities.value:
if (capability.max_cpu >= required_cpu and
capability.max_memory_in_gb >= required_memory):
# Check current usage to avoid quota issues
usage = client.location.list_usage(region)
# Look for container groups usage
for usage_item in usage.value:
if "containerGroups" in usage_item.name.value:
available_capacity = usage_item.limit - usage_item.current_value
if available_capacity > 0:
suitable_regions.append({
'region': region,
'max_cpu': capability.max_cpu,
'max_memory': capability.max_memory_in_gb,
'available_capacity': available_capacity
})
break
break
except Exception as e:
print(f"Error checking region {region}: {e}")
continue
if not suitable_regions:
raise ValueError("No suitable regions found for the specified requirements")
# Sort by available capacity (descending)
suitable_regions.sort(key=lambda x: x['available_capacity'], reverse=True)
best_region = suitable_regions[0]
print(f"Selected region: {best_region['region']}")
print(f"Max CPU: {best_region['max_cpu']}, Max Memory: {best_region['max_memory']} GB")
print(f"Available capacity: {best_region['available_capacity']} container groups")
return best_region['region']
# Usage
optimal_region = find_optimal_region(
client=client,
required_cpu=2.0,
required_memory=4.0,
preferred_regions=["eastus", "westus2", "westeurope"]
)def check_resource_availability(client, location, required_container_groups=1):
"""
Check if sufficient resources are available in a region for deployment.
Args:
client: ContainerInstanceManagementClient instance
location (str): Azure region to check
required_container_groups (int): Number of container groups needed
Returns:
dict: Resource availability information
"""
try:
usage_info = client.location.list_usage(location)
capabilities_info = client.location.list_capabilities(location)
result = {
'location': location,
'can_deploy': True,
'usage_details': {},
'capabilities': {},
'warnings': []
}
# Check usage limits
for usage in usage_info.value:
usage_name = usage.name.value
current = usage.current_value
limit = usage.limit
available = limit - current
result['usage_details'][usage_name] = {
'current': current,
'limit': limit,
'available': available,
'unit': usage.unit
}
# Check if we have enough container groups available
if 'containerGroups' in usage_name and available < required_container_groups:
result['can_deploy'] = False
result['warnings'].append(f"Insufficient container group quota: need {required_container_groups}, available {available}")
# Get capabilities
for capability in capabilities_info.value:
result['capabilities'][capability.os_type] = {
'max_cpu': capability.max_cpu,
'max_memory_gb': capability.max_memory_in_gb,
'max_gpu_count': capability.max_gpu_count
}
return result
except Exception as e:
return {
'location': location,
'can_deploy': False,
'error': str(e)
}
# Usage
availability = check_resource_availability(client, "eastus", required_container_groups=5)
if availability['can_deploy']:
print(f"✅ Region {availability['location']} is suitable for deployment")
print(f"Container Groups available: {availability['usage_details'].get('containerGroups', {}).get('available', 'Unknown')}")
else:
print(f"❌ Region {availability['location']} cannot accommodate deployment")
for warning in availability.get('warnings', []):
print(f" - {warning}")def get_cached_images_for_optimization(client, location, os_type="Linux"):
"""
Get cached images available in a region for faster container startup.
Args:
client: ContainerInstanceManagementClient instance
location (str): Azure region
os_type (str): Operating system type ("Linux" or "Windows")
Returns:
List[str]: List of cached image names for the specified OS
"""
try:
cached_images = client.location.list_cached_images(location)
for image_group in cached_images.value:
if image_group.os_type.lower() == os_type.lower():
return image_group.images
return []
except Exception as e:
print(f"Error retrieving cached images for {location}: {e}")
return []
def recommend_base_image(client, location, application_type):
"""
Recommend cached base images for faster deployment.
Args:
client: ContainerInstanceManagementClient instance
location (str): Azure region
application_type (str): Type of application ("web", "api", "worker", etc.)
Returns:
List[str]: Recommended cached images
"""
cached_images = get_cached_images_for_optimization(client, location, "Linux")
recommendations = []
image_patterns = {
'web': ['nginx', 'httpd', 'node'],
'api': ['node', 'python', 'openjdk', 'dotnet'],
'worker': ['python', 'openjdk', 'golang'],
'database': ['mysql', 'postgres', 'redis'],
'monitoring': ['prometheus', 'grafana']
}
if application_type in image_patterns:
patterns = image_patterns[application_type]
for image in cached_images:
for pattern in patterns:
if pattern in image.lower():
recommendations.append(image)
return recommendations[:5] # Return top 5 recommendations
# Usage
print("Cached images in East US:")
cached = get_cached_images_for_optimization(client, "eastus", "Linux")
for image in cached[:10]: # Show first 10
print(f" - {image}")
print("\nRecommended images for web applications:")
web_images = recommend_base_image(client, "eastus", "web")
for image in web_images:
print(f" - {image}")def plan_multi_region_deployment(client, regions, container_specs):
"""
Plan deployment across multiple regions with capability and usage checks.
Args:
client: ContainerInstanceManagementClient instance
regions (List[str]): List of target regions
container_specs (dict): Container requirements
Returns:
dict: Deployment plan with region assignments
"""
deployment_plan = {
'feasible_regions': [],
'infeasible_regions': [],
'recommendations': []
}
required_cpu = container_specs.get('cpu', 1.0)
required_memory = container_specs.get('memory_gb', 1.0)
for region in regions:
try:
# Check capabilities
capabilities = client.location.list_capabilities(region)
usage = client.location.list_usage(region)
cached_images = client.location.list_cached_images(region)
region_info = {
'region': region,
'max_cpu': 0,
'max_memory': 0,
'available_capacity': 0,
'cached_images_count': 0,
'can_deploy': False
}
# Analyze capabilities
for capability in capabilities.value:
if capability.os_type == "Linux": # Assuming Linux containers
region_info['max_cpu'] = capability.max_cpu
region_info['max_memory'] = capability.max_memory_in_gb
if (capability.max_cpu >= required_cpu and
capability.max_memory_in_gb >= required_memory):
region_info['can_deploy'] = True
break
# Check usage
for usage_item in usage.value:
if 'containerGroups' in usage_item.name.value:
region_info['available_capacity'] = usage_item.limit - usage_item.current_value
break
# Count cached images
for image_group in cached_images.value:
if image_group.os_type == "Linux":
region_info['cached_images_count'] = len(image_group.images)
break
# Categorize region
if region_info['can_deploy'] and region_info['available_capacity'] > 0:
deployment_plan['feasible_regions'].append(region_info)
# Add recommendations based on cached images
if region_info['cached_images_count'] > 50:
deployment_plan['recommendations'].append(
f"Region {region} has {region_info['cached_images_count']} cached images - good for fast startup"
)
else:
deployment_plan['infeasible_regions'].append(region_info)
except Exception as e:
deployment_plan['infeasible_regions'].append({
'region': region,
'error': str(e),
'can_deploy': False
})
# Sort feasible regions by available capacity
deployment_plan['feasible_regions'].sort(
key=lambda x: x['available_capacity'],
reverse=True
)
return deployment_plan
# Usage
container_requirements = {
'cpu': 2.0,
'memory_gb': 4.0,
'os_type': 'Linux'
}
target_regions = ["eastus", "westus2", "westeurope", "southeastasia", "japaneast"]
plan = plan_multi_region_deployment(client, target_regions, container_requirements)
print("Deployment Plan:")
print(f"✅ Feasible regions ({len(plan['feasible_regions'])}):")
for region in plan['feasible_regions']:
print(f" - {region['region']}: {region['available_capacity']} available slots, {region['cached_images_count']} cached images")
print(f"\n❌ Infeasible regions ({len(plan['infeasible_regions'])}):")
for region in plan['infeasible_regions']:
if 'error' in region:
print(f" - {region['region']}: Error - {region['error']}")
else:
print(f" - {region['region']}: Insufficient resources or capacity")
print(f"\n💡 Recommendations:")
for rec in plan['recommendations']:
print(f" - {rec}")Install with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-containerinstance