Introduction
One of the primary obstacles encountered by numerous organisations operating workloads in AWS is the dynamic management of DNS records for their AWS EC2 instances. In the ever-evolving digital landscape, it is crucial for businesses to guarantee high availability and seamless access to their applications and services. To achieve this, it is crucial to have an efficient and reliable method for managing DNS records. In this article, we will explore how to automatically register and deregister your EC2 instances with Amazon Route 53, a scalable and reliable DNS web service. This method provides a seamless way to manage the DNS entries for your instances, simplifying the process and reducing manual intervention. By automating this crucial aspect of your infrastructure, your organisation can benefit from increased agility, improved reliability, and a more streamlined management process.
Solution Overview and Requirements
The objective of this solution is to provide a scalable, reliable, and easy-to-implement approach for automating the registration and deregistration of EC2 instances in Route 53. The solution must:
1. Automatically register and deregister EC2 instances based on their launch and termination events.
2. Ensure prompt creation and removal of DNS records.
3. Scale automatically with the number of EC2 instances.
4. Utilise managed AWS services for ease of implementation and maintenance.
The key components and services required to implement the solution include:
- AWS Lambda: Executes the logic for registering and deregistering instances in Route 53.
- Amazon EventBridge: Triggers the Lambda function based on EC2 instance launch and termination events.
- Amazon Route 53: Manages DNS records for instances.
- Amazon EC2: Launches and terminates instances.
- AWS Identity and Access Management (IAM): Creates and manages roles and policies for granting necessary permissions.
Implementation
Step 1: Create an IAM role for Lambda
To create the required IAM role for your Lambda function and attach the necessary policies, follow these detailed steps:
1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.
2. In the navigation pane, click on “Roles,” and then click the “Create role” button.
3. Select “AWS service” as the trusted entity type, and then choose “Lambda” as the use case. Click the “Next: Permissions” button to proceed.
4. In the “Permissions policies” section, search for the following policies in the search box:
· AmazonEC2ReadOnlyAccess
· AmazonRoute53FullAccess
5. Select the checkboxes next to these policies to attach them to the new IAM role. Click the “Next” button to proceed.
6. Give it a Name and Description and click on Create Rule
Step 2: Create a Lambda function
To create a new Lambda function with the Python 3.10 runtime environment and assign the IAM role created in Step 1, follow these detailed steps:
1. Sign into the AWS Management Console and open the AWS Lambda console at https://console.aws.amazon.com/lambda/.
2. In the Lambda console, click the “Create function” button.
3. Select the “Author from scratch” option. Provide a name for your Lambda function.
4. Under the “Runtime” dropdown menu, select a Python 3.10 version.
5. Under the “Architecture” dropdown menu, select a x86_64.
6. Under the “Execution role” select a Use an existing role and pick the IAM rule created earlier.
7. Click on “Create Function”.
8. Under “Code source” click “Upload from” and choose .zip file containing your Python script. I have attached a sample code below so make sure to change and replace the required values if you’re going to use my code.
import boto3
import os
# Initialize AWS SDK clients
ec2 = boto3.client(‘ec2’)
route53 = boto3.client(‘route53’)
# Replace with your hosted zone ID
HOSTED_ZONE_ID = os.environ.get(‘HOSTED_ZONE_ID’, ‘YOUR_HOSTED_ZONE_ID’)
# Replace with your desired domain name
DOMAIN_NAME = os.environ.get(‘DOMAIN_NAME’, ‘example.com’)
def lambda_handler(event, context):
instance_id = event[‘detail’][‘instance-id’]
instance_state = event[‘detail’][‘state’]
# Retrieve instance information
instance_info = ec2.describe_instances(InstanceIds=[instance_id])
instance = instance_info[‘Reservations’][0][‘Instances’][0]
instance_name = get_instance_name(instance)
instance_ip = instance[‘PrivateIpAddress’]
# Determine if the instance is being launched or terminated
if instance_state == ‘running’:
# Register the instance in Route 53
create_route53_record_set(instance_name, instance_ip)
elif instance_state == ‘terminated’ or instance_state == ‘shutting-down’:
# Deregister the instance in Route 53
delete_route53_record_set(instance_name)
def get_instance_name(instance):
for tag in instance[‘Tags’]:
if tag[‘Key’] == ‘Name’:
return tag[‘Value’]
return ”
def create_route53_record_set(instance_name, instance_ip):
route53.change_resource_record_sets(
HostedZoneId=HOSTED_ZONE_ID,
ChangeBatch={
‘Changes’: [
{
‘Action’: ‘UPSERT’,
‘ResourceRecordSet’: {
‘Name’: f'{instance_name}.{DOMAIN_NAME}’,
‘Type’: ‘A’,
‘TTL’: 300,
‘ResourceRecords’: [
{
‘Value’: instance_ip
}
]
}
}
]
}
)
def delete_route53_record_set(instance_name):
try:
record_set = route53.list_resource_record_sets(
HostedZoneId=HOSTED_ZONE_ID,
StartRecordName=f'{instance_name}.{DOMAIN_NAME}’,
StartRecordType=’A’,
MaxItems=’1′
)
if record_set[‘ResourceRecordSets’]:
route53.change_resource_record_sets(
HostedZoneId=HOSTED_ZONE_ID,
ChangeBatch={
‘Changes’: [
{
‘Action’: ‘DELETE’,
‘ResourceRecordSet’: record_set[‘ResourceRecordSets’][0]
}
]
}
)
except Exception as e:
print(f’Error deleting record set: {e}’)
Step 3: Create an EC2 launch and termination event
To create an EventBridge rule that triggers on EC2 instance state-change events and adds the Lambda function as the target, follow these detailed steps:
- Sign into the AWS Management Console and open the Amazon EventBridge console at https://console.aws.amazon.com/events/.
- In the navigation pane, click on “Rules” and then click the “Create rule” button.
- Provide a name and description for the rule.
- Leave “Event bus” as Default and click “Next”
- In the “Event source” select “AWS events or EventBridge partner events”
6. In the “Creation method” section, choose “Use pattern form” as the method.
7. In the “Event source” section, select “AWS service”.
8. In the “AWS service” dropdown, select “EC2” as the AWS service.
9. Once you have selected “EC2“, the console will provide a set of event patterns related to EC2 events. Look for the “EC2 Instance State-change Notification” and leave the rest as “Any state”
Your generated event pattern JSON should look like this:
{
“source”: [“aws.ec2”],
“detail-type”: [“EC2 Instance State-change Notification”]
}
11. Click “Next”
12. In the Select targets(s) screen under “Target 1” section, under “Target types“, choose “AWS service” as the target type.
13. In the “Select a target” dropdown, a list of AWS services that can be used as targets will appear. Scroll down the list and select “Lambda function“.
14. After selecting “Lambda function”, you should see another dropdown labeled “Function“. Click on this dropdown and select the Lambda function you created earlier.
15. Click “Next” and “Next”
16. On the “Review and create” screen click “Create rule’
Testing and Optimisation:
After implementing the solution, test it by launching and terminating EC2 instances. Observe that the corresponding DNS records in Route 53 are created and deleted automatically. Modify and optimise the solution as needed based on test results.
Conclusion
Adhering to these steps enables seamless automation of AWS EC2 instance registration and deregistration with Route 53, prioritising cloud security. This method streamlines DNS management, minimises manual input, and guarantees accurate domain-instance linkage. Moreover, it bolsters your organisation’s asset protection by following best security practices. Utilising these strategies empowers you to deliver resilient, agile, and secure infrastructure solutions tailored to your organisation’s requirements. Embracing a security-centric approach throughout your cloud journey is crucial for safeguarding your organisation’s data, resources, and ultimately, its reputation and success.