DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Hidden Latency of Autoscaling
  • Your Network, Your Rules: Take Charge With Own DNS
  • Understanding DNS Records: What They Are and Why They Matter
  • Automate DNS Records Creation With ExternalDNS on AWS Elastic Kubernetes Service

Trending

  • Data Contracts as the "Circuit Breaker" for Model Reliability
  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)
  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka
  • How to Parse Large XML Files in PHP Without Running Out of Memory
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Updating a DNS Record on An Autoscaling Event Using Lambda

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.

By 
Henrik Lernmark user avatar
Henrik Lernmark
·
Updated Jul. 31, 19 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
6.1K Views

Join the DZone community and get the full member experience.

Join For Free

When 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"
        }
    ]
}


Domain Name System Event Autoscaling Record (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • The Hidden Latency of Autoscaling
  • Your Network, Your Rules: Take Charge With Own DNS
  • Understanding DNS Records: What They Are and Why They Matter
  • Automate DNS Records Creation With ExternalDNS on AWS Elastic Kubernetes Service

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook