pythonazureazure-functionsazure-sdk-python

Deleting and creating a Azure VPN-Gateway with python Azure SDK


I have some Azure Python functions which I would use to build and destroy a VPN Gateway every day. In a first step I tried to delete an existing Gateway with that code:

import azure.functions as func
from azure.identity import ClientSecretCredential
from azure.mgmt.network import NetworkManagementClient
import logging


def main(mytimer: func.TimerRequest) -> None:

    logger = logging.getLogger("azure.core.pipeline.policies.http_logging_policy")
    logger.setLevel(logging.WARNING)

    subscription_id ="xxx"
    client_id ="xxx"
    secret="xxx"
    tenant="xxx"
    rgroup = "xxx"
    gateway = "xxx"
    credential = ClientSecretCredential(
        tenant_id=tenant,
        client_id=client_id,
        client_secret=secret
    )
    network_client = NetworkManagementClient(credential, subscription_id )
    LROPoller = network_client.vpn_gateways.begin_delete(rgroup, gateway)

    logging.info(str(LROPoller.status()))

the result from the LROPoller.status is succeeded, but still the gateway is in my environment. Unfortunately the documentation is sub optimal, so I don't understand what I am doing wrong.


Solution

  • I tried in my environment and got the below results:

    You can use the python code to delete the virtual network (VPN) gateways and also you can add them to your azure function app code.

    Code:

    from azure.identity import DefaultAzureCredential
    from azure.mgmt.network import NetworkManagementClient
    import time
    
    start=time.time()
    credential=DefaultAzureCredential()
    subscription_id="Your sub id"
    gateway="your gateway name"
    network_client = NetworkManagementClient(credential, subscription_id )
    resource_group_name = network_client.virtual_network_gateways.get(
        "<your resource grp name>", gateway).id.split('/')[4]
    network_client.virtual_network_gateways.begin_delete(resource_group_name, gateway).result()
    end=time.time()
    print("VPN Gateway is deleted with time taken",end-start)
    

    Output: enter image description here

    For creation you can use the below code:

    Code:

    from azure.identity import DefaultAzureCredential
    from azure.mgmt.network import NetworkManagementClient
    from azure.mgmt.network.v2021_03_01.models import (VirtualNetworkGateway,
                                                       VirtualNetworkGatewayIpConfiguration,
                                                       SubResource)
    
    # Set the subscription ID and resource group name
    subscription_id = 'your-sub-id'
    resource_group_name = 'your resources -grp name '
    
    # Initialize the Network Management client
    credential = DefaultAzureCredential()
    network_client = NetworkManagementClient(credential, subscription_id)
    
    # Create a Virtual Network Gateway object
    gateway = VirtualNetworkGateway(
        gateway_type='Vpn',
        vpn_type='RouteBased',
        sku={'name': 'VpnGw1', 'tier': 'VpnGw1'},
        location='<your-location>',
        ip_configurations=[
            VirtualNetworkGatewayIpConfiguration(
                name='GatewayIpConfig',
                subnet=SubResource(id='<your-subnet-id>'),
                public_ip_address=SubResource(id='<your-public-ip-id>')
            )
        ]
    )
    
    # Create the VPN gateway
    async_operation = network_client.virtual_network_gateways.create_or_update(
        resource_group_name,
        '<your-vpn-gateway-name>',
        gateway
    )
    
    async_operation.wait()
    print("Virtual Network Gateway created successfully!")
    

    Note: According to this MS-Docs a virtual vpn gateway can take 45 minutes or more to fully create and deploy.

    Reference:

    azure.mgmt.network.v2016_12_01.operations.VirtualNetworkGatewaysOperations class | Microsoft Learn