import boto3 def lambda_handler(event, context): if 'detail' in event: if 'instance-id' in event['detail']: instance_id = event['detail']['instance-id'] else: return else: return client_ec2 = boto3.client('ec2') instance_details = client_ec2.describe_instances(InstanceIds=[instance_id]) for tag in instance_details['Reservations'][0]['Instances'][0]['Tags']: if tag['Key'] == 'Name': tag_name = tag['Value'] if tag['Key'] == 'DNSName': tag_dnsname = tag['Value'] if tag['Key'] == 'HostedZoneId': tag_hostedzoneid = tag['Value'] try: print('Found tags: {}, {}, {}'.format(tag_name, tag_dnsname, tag_hostedzoneid)) except: print('Required tags missing.') return client_r53 = boto3.client('route53') client_r53.change_resource_record_sets( HostedZoneId=tag_hostedzoneid, ChangeBatch={ 'Changes': [ { 'Action': 'UPSERT', 'ResourceRecordSet': { 'Name': tag_dnsname, 'Type': 'A', 'TTL': 360, 'ResourceRecords': [ { 'Value': instance_details['Reservations'][0]['Instances'][0]['PublicIpAddress'] } ] } } ] } ) print('Updated {} for {} to {}'.format(tag_dnsname,instance_id,instance_details['Reservations'][0]['Instances'][0]['PublicIpAddress'])) return