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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Set MX Records via API: Automate Email Routing Programmatically
  • The Hidden Latency of Autoscaling
  • Your Network, Your Rules: Take Charge With Own DNS
  • Understanding DNS Records: What They Are and Why They Matter

Trending

  • Building a Claude Code Observability Dashboard With Grafana and Microsoft Fabric
  • How to Tell If Code Is AI-Generated (and What to Ask)
  • Why Successful LLM Demos Fail in Production
  • How Has AI Impacted Code Obfuscation?

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Updated Jul. 31, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
6.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • How to Set MX Records via API: Automate Email Routing Programmatically
  • The Hidden Latency of Autoscaling
  • Your Network, Your Rules: Take Charge With Own DNS
  • Understanding DNS Records: What They Are and Why They Matter

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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