from ipaddress import ip_address, IPv4Address from kubernetes import client, config import boto3 import time import os HOSTED_ZONE=os.environ['HOSTED_ZONE'] COTURN_DOMAIN_NAME=os.environ['COTURN_DOMAIN_NAME'] config.load_incluster_config() v1 = client.CoreV1Api() def validIPAddress(IP: str) -> str: try: return "IPv4" if type(ip_address(IP)) is IPv4Address else "IPv6" except ValueError: return "Invalid" while(True): ips=[] pods = v1.list_namespaced_pod(namespace="coturn") for i in pods.items: node_status = v1.read_node(name=i.spec.node_name) for adr in node_status.status.addresses: # only collect IPv4 addresses, because we are only updating A records here if adr.type=="ExternalIP" and validIPAddress(adr.address) == "IPv4": ips.append({'Value': adr.address}) print("Node IPs: "+str(ips)) client = boto3.client('route53') response = client.change_resource_record_sets( HostedZoneId=HOSTED_ZONE, ChangeBatch= { 'Comment': 'COTURN NODES', 'Changes': [ { 'Action': 'UPSERT', 'ResourceRecordSet': { 'Name': COTURN_DOMAIN_NAME, 'Type': 'A', 'TTL': 300, 'ResourceRecords': ips } }] }) time.sleep(60)