Skip to content

Instantly share code, notes, and snippets.

@filipeandre
Created November 7, 2024 10:57
Show Gist options
  • Save filipeandre/7cf4a6da8f534645210d36af15900c66 to your computer and use it in GitHub Desktop.
Save filipeandre/7cf4a6da8f534645210d36af15900c66 to your computer and use it in GitHub Desktop.
It collects the ELB's private IPs from EC2 network interfaces within a specified VPC. It fetches the existing Route53 records to check for differences. If the IPs have changed, it updates the Route53 A record.
import boto3
import sys
# AWS Configuration
vpc_id = 'your-vpc-id'
elb_network_description = 'Your ELB network interface description (generated like "ELB your-elb-name")'
route53_internal_hosted_zone_id = 'Your Route53 Internal hosted zone ID'
route53_internal_record_name = 'your-route53-record.internal.' # Ending with dot
aws_access_key = 'Your IAM Key'
aws_secret_key = 'Your IAM Secret'
aws_region = 'us-west-1'
# Initialize EC2 client
ec2_client = boto3.client(
'ec2',
region_name=aws_region,
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key
)
# Get ELB network interfaces
response = ec2_client.describe_network_interfaces(
Filters=[
{'Name': 'description', 'Values': [elb_network_description]},
{'Name': 'vpc-id', 'Values': [vpc_id]}
]
)
# Collect ELB IPs
elb_ips = sorted([interface['PrivateIpAddress'] for interface in response['NetworkInterfaces']])
# Initialize Route53 client
route53_client = boto3.client(
'route53',
region_name='us-east-1', # Route53 operates globally, but us-east-1 is typically used
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key
)
# Get existing Route53 record IPs
records = route53_client.list_resource_record_sets(
HostedZoneId=route53_internal_hosted_zone_id,
StartRecordName=route53_internal_record_name
)
route53_elb_ips = sorted([record['Value'] for record in records['ResourceRecordSets'][0]['ResourceRecords']])
# Check if update is needed
if elb_ips == route53_elb_ips:
print('Same IPs detected - no update needed')
sys.exit()
# Prepare new records
route53_resource_records = [{'Value': ip} for ip in elb_ips]
# Update Route53 records
route53_client.change_resource_record_sets(
HostedZoneId=route53_internal_hosted_zone_id,
ChangeBatch={
'Comment': 'ELB Private IPs update',
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': {
'Name': route53_internal_record_name,
'TTL': 60,
'Type': 'A',
'ResourceRecords': route53_resource_records
}
}
]
}
)
print('Route53 record updated successfully.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment