Created
April 16, 2018 14:20
-
-
Save arouene/50c83ff531ba62625beaab0da731cdc1 to your computer and use it in GitHub Desktop.
add ec2 instances with tag Name in Route53 Domain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import boto3 | |
HOSTED_ZONE_ID = "ABCDEF123456789" | |
DOMAIN_NAME = ".example.lan." | |
def lambda_handler(): | |
# Setup Boto3 client | |
boto3.setup_default_session(region_name='us-east-1') | |
ec2 = boto3.client("ec2") | |
dns = boto3.client("route53") | |
reservations = ec2.describe_instances() | |
for reservation in reservations['Reservations']: | |
for instance in reservation['Instances']: | |
register_instance(ec2, dns, instance) | |
def register_instance(ec2, dns, instance): | |
# Get instance's name | |
tags = instance['Tags'] | |
name = list(filter(lambda x: x['Key'] == 'Name', tags))[0]['Value'] | |
new_ip = instance['PrivateIpAddress'] | |
# Change / Create DNS Record | |
dns.change_resource_record_sets( | |
HostedZoneId=HOSTED_ZONE_ID, | |
ChangeBatch={ | |
'Changes': [ | |
{ | |
'Action': 'UPSERT', | |
'ResourceRecordSet': { | |
'Name': name + DOMAIN_NAME, | |
'Type': 'A', | |
'TTL': 300, | |
'ResourceRecords': [ | |
{ | |
'Value': new_ip | |
}, | |
] | |
} | |
} | |
] | |
}) | |
lambda_handler() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment