Updating a DNS Record on An Autoscaling Event Using Lambda
One of the many things you can do with Amazon's serverless function service is to automate the updating of a DNS record.
Join the DZone community and get the full member experience.
Join For FreeWhen hosting a service on an EC2 that you need to access, it's a good idea to assign a DNS name to that service so you're not using the EC2 IP address in your code. However, a problem can occur when that EC2 is handled by an autoscaling group where you don't control the IP of the EC2 changes. The traditional method of handling this is to have a load balancer pointing to the autoscaling group. The cheaper alternative approach is to have a lambda update the CNAME of a Route53 recordset.
To trigger the lambda, I use the following CloudWatch event:
{
"detail-type": [
"EC2 Instance Launch Successful"
],
"detail": {
"AutoScalingGroupName": [
"myAutoScalingGroup"
]
},
"source": [
"aws.autoscaling"
]
}
When this event is triggered, the lambda gets the details of the new EC2 using describe_instances()
with the instance ID found in the lambda event. You can then use change_resource_sets()
to point the CNAME to the private DNS of the new EC2. Alternatively, you could use an A-record to point to the IP address.
import boto3
import logging
import os
logger = logging.getLogger(name=__name__)
env_level = os.environ.get("LOG_LEVEL")
log_level = logging.INFO if not env_level else env_level
logger.setLevel(log_level)
def lambda_handler(event, context):
zone_id = os.environ['HostedZoneId']
host_dns = os.environ['HostDns']
instance_id = event["detail"]["EC2InstanceId"]
if event["detail-type"] == "EC2 Instance Launch Successful":
logger.info(f"Instance: {instance_id} launched")
route53_client = boto3.client("route53")
ec2_client = boto3.client("ec2")
instance_details = ec2_client.describe_instances(InstanceIds=[instance_id])
instance_dns = instance_details['Reservations'][0]['Instances'][0]['PrivateDnsName']
response = route53_client.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
'Comment': 'Dns to ec2 instance',
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': {
'Name': host_dns,
'Type': 'CNAME',
'TTL': 120,
'ResourceRecords': [
{
'Value': instance_dns
}
]
}
}
]
}
)
logger.info("UPSERT CNAME record response: %s", response)
The lambda needs a role that contains the following policy together with one of the basic managed lambda policies.
{
"Statement": [
{
"Action": [
"route53:ChangeResourceRecordSets",
"ec2:DescribeInstances"
],
"Resource": [
"*"
],
"Effect": "Allow"
}
]
}
Opinions expressed by DZone contributors are their own.
Comments