CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-mgmt-containerinstance

Microsoft Azure Container Instance Client Library for Python providing comprehensive management capabilities for containerized applications in Azure cloud.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

subnet-operations.mddocs/

Subnet Service Association Links

Subnet Service Association Links manage the relationship between Azure Container Instances and virtual network subnets. These operations allow you to control container group integration with virtual networks and clean up network associations when no longer needed.

Capabilities

Delete Subnet Service Association Link { .api }

def begin_delete(
    resource_group_name: str,
    virtual_network_name: str,
    subnet_name: str,
    service_association_link_name: str,
    **kwargs
) -> LROPoller[None]:
    """
    Delete a subnet service association link.
    
    Args:
        resource_group_name (str): Name of the resource group containing the virtual network
        virtual_network_name (str): Name of the virtual network
        subnet_name (str): Name of the subnet
        service_association_link_name (str): Name of the service association link to delete
        
    Returns:
        LROPoller[None]: Long-running operation poller for the deletion
        
    Example:
        # Delete a subnet service association link
        delete_operation = client.subnet_service_association_link.begin_delete(
            resource_group_name="my-resource-group",
            virtual_network_name="my-vnet",
            subnet_name="container-subnet",
            service_association_link_name="my-container-group-link"
        )
        
        # Wait for deletion to complete
        delete_operation.result()
        print("Subnet service association link deleted successfully")
    """

Usage Examples

Clean Up Container Group Network Associations

def cleanup_container_group_network_associations(
    client,
    resource_group_name,
    virtual_network_name,
    subnet_name,
    container_group_names
):
    """
    Clean up subnet service association links for multiple container groups.
    
    Args:
        client: ContainerInstanceManagementClient instance
        resource_group_name (str): Resource group name
        virtual_network_name (str): Virtual network name
        subnet_name (str): Subnet name
        container_group_names (List[str]): List of container group names to clean up
        
    Returns:
        List[dict]: Results of cleanup operations
    """
    
    cleanup_results = []
    
    for container_group_name in container_group_names:
        try:
            # Generate service association link name (typically matches container group name)
            link_name = f"{container_group_name}-link"
            
            print(f"Deleting subnet association for container group: {container_group_name}")
            
            # Delete the service association link
            delete_operation = client.subnet_service_association_link.begin_delete(
                resource_group_name=resource_group_name,
                virtual_network_name=virtual_network_name,
                subnet_name=subnet_name,
                service_association_link_name=link_name
            )
            
            # Wait for completion
            delete_operation.result()
            
            cleanup_results.append({
                'container_group': container_group_name,
                'link_name': link_name,
                'status': 'success',
                'message': 'Subnet association link deleted successfully'
            })
            
        except Exception as e:
            cleanup_results.append({
                'container_group': container_group_name,
                'link_name': link_name,
                'status': 'error',
                'message': str(e)
            })
    
    return cleanup_results

# Usage
container_groups_to_cleanup = [
    "web-app-container-group",
    "api-container-group", 
    "worker-container-group"
]

results = cleanup_container_group_network_associations(
    client=client,
    resource_group_name="production-rg",
    virtual_network_name="production-vnet",
    subnet_name="container-subnet",
    container_group_names=container_groups_to_cleanup
)

# Report results
print("Cleanup Results:")
for result in results:
    status_symbol = "✅" if result['status'] == 'success' else "❌"
    print(f"{status_symbol} {result['container_group']}: {result['message']}")

Bulk Network Cleanup After Container Group Deletion

import time

def bulk_network_cleanup_after_deletion(
    client,
    resource_group_name,
    virtual_network_name,
    subnet_name,
    container_group_operations
):
    """
    Perform network cleanup after bulk container group deletion.
    
    Args:
        client: ContainerInstanceManagementClient instance
        resource_group_name (str): Resource group name
        virtual_network_name (str): Virtual network name
        subnet_name (str): Subnet name
        container_group_operations (List[dict]): List of container group deletion operations
        
    Returns:
        dict: Summary of cleanup operations
    """
    
    print("Waiting for container group deletions to complete...")
    
    # Wait for all container group deletions to complete first
    successful_deletions = []
    failed_deletions = []
    
    for operation_info in container_group_operations:
        try:
            # Wait for the container group deletion to complete
            operation_info['operation'].result()
            successful_deletions.append(operation_info['name'])
            print(f"✅ Container group '{operation_info['name']}' deleted successfully")
        except Exception as e:
            failed_deletions.append({
                'name': operation_info['name'],
                'error': str(e)
            })
            print(f"❌ Failed to delete container group '{operation_info['name']}': {e}")
    
    print(f"\nContainer group deletions complete: {len(successful_deletions)} successful, {len(failed_deletions)} failed")
    
    # Now clean up subnet associations for successfully deleted container groups
    if successful_deletions:
        print("\nCleaning up subnet service association links...")
        
        network_cleanup_results = cleanup_container_group_network_associations(
            client=client,
            resource_group_name=resource_group_name,
            virtual_network_name=virtual_network_name,
            subnet_name=subnet_name,
            container_group_names=successful_deletions
        )
        
        successful_network_cleanup = [r for r in network_cleanup_results if r['status'] == 'success']
        failed_network_cleanup = [r for r in network_cleanup_results if r['status'] == 'error']
        
        print(f"Network cleanup complete: {len(successful_network_cleanup)} successful, {len(failed_network_cleanup)} failed")
        
        return {
            'container_group_deletions': {
                'successful': successful_deletions,
                'failed': failed_deletions
            },
            'network_cleanup': {
                'successful': successful_network_cleanup,
                'failed': failed_network_cleanup
            },
            'summary': {
                'total_operations': len(container_group_operations),
                'fully_completed': len(successful_network_cleanup),
                'partial_failures': len(successful_deletions) - len(successful_network_cleanup),
                'complete_failures': len(failed_deletions)
            }
        }
    
    return {
        'container_group_deletions': {
            'successful': [],
            'failed': failed_deletions
        },
        'network_cleanup': {
            'successful': [],
            'failed': []
        },
        'summary': {
            'total_operations': len(container_group_operations),
            'fully_completed': 0,
            'partial_failures': 0,
            'complete_failures': len(failed_deletions)
        }
    }

# Example usage
# First, start container group deletions
container_group_names = ["app1-cg", "app2-cg", "app3-cg"]
deletion_operations = []

for cg_name in container_group_names:
    try:
        operation = client.container_groups.begin_delete(
            resource_group_name="production-rg",
            container_group_name=cg_name
        )
        deletion_operations.append({
            'name': cg_name,
            'operation': operation
        })
        print(f"Started deletion of container group: {cg_name}")
    except Exception as e:
        print(f"Failed to start deletion of {cg_name}: {e}")

# Then perform bulk cleanup
if deletion_operations:
    cleanup_summary = bulk_network_cleanup_after_deletion(
        client=client,
        resource_group_name="production-rg",
        virtual_network_name="production-vnet",
        subnet_name="container-subnet",
        container_group_operations=deletion_operations
    )
    
    print("\n=== Cleanup Summary ===")
    print(f"Total operations: {cleanup_summary['summary']['total_operations']}")
    print(f"Fully completed: {cleanup_summary['summary']['fully_completed']}")
    print(f"Partial failures: {cleanup_summary['summary']['partial_failures']}")
    print(f"Complete failures: {cleanup_summary['summary']['complete_failures']}")

Network Integration Troubleshooting

def troubleshoot_network_integration(
    client,
    resource_group_name,
    container_group_name,
    virtual_network_name,
    subnet_name
):
    """
    Troubleshoot network integration issues for a container group.
    
    Args:
        client: ContainerInstanceManagementClient instance
        resource_group_name (str): Resource group name
        container_group_name (str): Container group name
        virtual_network_name (str): Virtual network name
        subnet_name (str): Subnet name
        
    Returns:
        dict: Troubleshooting information
    """
    
    troubleshooting_info = {
        'container_group_status': {},
        'network_dependencies': [],
        'recommendations': []
    }
    
    try:
        # Check container group status
        container_group = client.container_groups.get(
            resource_group_name=resource_group_name,
            container_group_name=container_group_name
        )
        
        troubleshooting_info['container_group_status'] = {
            'name': container_group.name,
            'provisioning_state': container_group.provisioning_state,
            'has_ip_address': container_group.ip_address is not None,
            'ip_type': container_group.ip_address.type if container_group.ip_address else None,
            'subnet_ids': [subnet.id for subnet in container_group.subnet_ids] if container_group.subnet_ids else []
        }
        
        # Check network dependencies
        try:
            dependencies = client.container_groups.get_outbound_network_dependencies_endpoints(
                resource_group_name=resource_group_name,
                container_group_name=container_group_name
            )
            troubleshooting_info['network_dependencies'] = dependencies
        except Exception as e:
            troubleshooting_info['network_dependencies'] = f"Error retrieving dependencies: {e}"
        
        # Generate recommendations
        recommendations = []
        
        if container_group.provisioning_state != "Succeeded":
            recommendations.append(f"Container group is in '{container_group.provisioning_state}' state. Check deployment logs.")
        
        if not container_group.ip_address:
            recommendations.append("Container group has no IP address configured. Check networking configuration.")
        elif container_group.ip_address.type == "Private" and not container_group.subnet_ids:
            recommendations.append("Private IP configured but no subnet specified. Verify virtual network integration.")
        
        if container_group.subnet_ids:
            recommendations.append("Container group is using virtual network integration. Consider cleaning up subnet service association links if removing the container group.")
        
        troubleshooting_info['recommendations'] = recommendations
        
    except Exception as e:
        troubleshooting_info['error'] = f"Failed to retrieve container group information: {e}"
    
    return troubleshooting_info

# Usage
troubleshooting_results = troubleshoot_network_integration(
    client=client,
    resource_group_name="production-rg",
    container_group_name="web-app-cg",
    virtual_network_name="production-vnet",
    subnet_name="container-subnet"
)

print("=== Network Integration Troubleshooting ===")
if 'error' in troubleshooting_results:
    print(f"❌ Error: {troubleshooting_results['error']}")
else:
    cg_status = troubleshooting_results['container_group_status']
    print(f"Container Group: {cg_status['name']}")
    print(f"Provisioning State: {cg_status['provisioning_state']}")
    print(f"Has IP Address: {cg_status['has_ip_address']}")
    if cg_status['has_ip_address']:
        print(f"IP Type: {cg_status['ip_type']}")
    
    if cg_status['subnet_ids']:
        print("Subnet IDs:")
        for subnet_id in cg_status['subnet_ids']:
            print(f"  - {subnet_id}")
    
    if troubleshooting_results['network_dependencies']:
        print("Network Dependencies:")
        if isinstance(troubleshooting_results['network_dependencies'], list):
            for dep in troubleshooting_results['network_dependencies']:
                print(f"  - {dep}")
        else:
            print(f"  {troubleshooting_results['network_dependencies']}")
    
    if troubleshooting_results['recommendations']:
        print("Recommendations:")
        for rec in troubleshooting_results['recommendations']:
            print(f"  💡 {rec}")

Important Notes

  • Subnet service association links are automatically created when container groups are deployed to virtual network subnets
  • These links must be cleaned up manually when container groups are deleted to avoid orphaned network resources
  • The service association link name typically follows the pattern {container-group-name}-link but may vary
  • Deleting a service association link is a long-running operation and should be monitored for completion
  • Network cleanup should only be performed after confirming that container groups have been successfully deleted

Install with Tessl CLI

npx tessl i tessl/pypi-azure-mgmt-containerinstance

docs

authentication.md

container-groups.md

containers.md

index.md

location.md

models.md

operations.md

subnet-operations.md

tile.json