pythonazurenetwork-programmingazure-sdk

Deleting an Azure Loadbalancer Frontend IP configuration from python?


I'm writing something to clean up our old Azure resources, and one thing that comes up from time to time is public-ips still bound to a kubernetes-created loadbalancer even after the Ingress was deleted.

Using the azure CLI, I can get the public IP, find the ipConfiguration from that, which is used to name the load balancer rules and frontend ipconfig for that IP. I can get the load balancer rule resource IDs and delete those with "az resource delete" or the ResourceManagementClient. However I can't do the same with the LB Front End config even though it does have a resource_id. The AZ CLI has az network lb frontend-ip delete but I can't find the Azure API that this is calling. NetworkManagementClient.load_balancer_frontend_ip_configurations only has list() and get() methods, not delete().

I did try looking at the AZ CLI source here, but it is not easy reading! https://github.com/Azure/azure-cli/blob/dev/src/azure-cli/azure/cli/command_modules/network/aaz/latest/network/lb/frontend_ip/_delete.py#L64

What is the "approved" way to do this?


Solution

  • Deleting an Azure Loadbalancer Frontend IP configuration from python?

    Here is the Python code to delete the Azure Loadbalancer Frontend IP configuration using SDK NetworkManagementClient

    from azure.identity import DefaultAzureCredential
    from azure.mgmt.network import NetworkManagementClient
    
    
    credential = DefaultAzureCredential()
    subscription_id = "8332bf56-fnfnvnvnv4daa-a507-d7e60e5f09a9"
    network_client = NetworkManagementClient(credential, subscription_id)
    
    
    resource_group_name = "biceprg"
    lb_name = "venkat-lb"
    frontend_ip_name = "venkat-frontend"
    
    
    load_balancer = network_client.load_balancers.get(resource_group_name, lb_name)
    
    configuration
    if len(load_balancer.frontend_ip_configurations) <= 1:
        print(f"Cannot delete the only frontend IP configuration from load balancer '{lb_name}'.")
    else:
    
        new_frontend_ip_configurations = [
            ipconfig for ipconfig in load_balancer.frontend_ip_configurations
            if ipconfig.name != frontend_ip_name
        ]
    
    
        load_balancer.frontend_ip_configurations = new_frontend_ip_configurations
    
    
        poller = network_client.load_balancers.begin_create_or_update(
            resource_group_name,
            lb_name,
            load_balancer
        )
    
        result = poller.result()
        print(f"Frontend IP configuration '{frontend_ip_name}' deleted successfully.")
    
    

    Before executing the python script, I have 2 Frontend IP configurations.

    enter image description here

    After executing the code, the frontend named venkat-frontend configuration from the load balancer has been deleted successfully.

    enter image description here