''' This file is a runbook which is intended to be run via an Azure Automation account! ''' import socket from azure.mgmt.network import NetworkManagementClient import azure.mgmt.resource import automationassets SUBSCRIPTION_ID="w-x-y-z" LOCATION="westeurope" RESOURCE_GROUP_NAME = "Azure-2-Home" LOCAL_NETWORK_GATEWAY_NAME = "A2H-LNG" FRITZBOX_DYNDNS = "...vc.myfritz.net" def get_automation_runas_credential(runas_connection): from OpenSSL import crypto import binascii from msrestazure import azure_active_directory import adal # Get the Azure Automation RunAs service principal certificate cert = automationassets.get_automation_certificate("AzureRunAsCertificate") pks12_cert = crypto.load_pkcs12(cert) pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey()) # Get run as connection information for the Azure Automation service principal application_id = runas_connection["ApplicationId"] thumbprint = runas_connection["CertificateThumbprint"] tenant_id = runas_connection["TenantId"] # Authenticate with service principal certificate resource ="https://management.core.windows.net/" authority_url = ("https://login.microsoftonline.com/"+tenant_id) context = adal.AuthenticationContext(authority_url) return azure_active_directory.AdalAuthentication( lambda: context.acquire_token_with_client_certificate( resource, application_id, pem_pkey, thumbprint) ) # Authenticate to Azure using the Azure Automation RunAs service principal runas_connection = automationassets.get_automation_connection("AzureRunAsConnection") azure_credential = get_automation_runas_credential(runas_connection) network_client = NetworkManagementClient(azure_credential, SUBSCRIPTION_ID) LNGIP = network_client.local_network_gateways.get(RESOURCE_GROUP_NAME, LOCAL_NETWORK_GATEWAY_NAME).gateway_ip_address LANIP = network_client.local_network_gateways.get(RESOURCE_GROUP_NAME, LOCAL_NETWORK_GATEWAY_NAME).local_network_address_space FBIP = socket.gethostbyname(FRITZBOX_DYNDNS) print("FRITZ!Box IP: {ip:s}".format(ip=FBIP)) print("LNG IP : {ip:s}".format(ip=LNGIP)) if LNGIP == FBIP: print("Nothing to do") else: print("Updating LNG IP from {lip:s} to {fip:s}".format(lip=LNGIP, fip=FBIP)) LNG_PARAM = {'location': LOCATION, 'gateway_ip_address': FBIP, 'local_network_address_space': LANIP} network_client.local_network_gateways.create_or_update(RESOURCE_GROUP_NAME, LOCAL_NETWORK_GATEWAY_NAME, LNG_PARAM) LNGIP = network_client.local_network_gateways.get(RESOURCE_GROUP_NAME, LOCAL_NETWORK_GATEWAY_NAME).gateway_ip_address print("FRITZ!Box IP: {ip:s}".format(ip=FBIP)) print("LNG IP : {ip:s}".format(ip=LNGIP))