Skip to content

Instantly share code, notes, and snippets.

@kixorz
Last active June 3, 2022 11:26
Show Gist options
  • Save kixorz/627a9235b21fe9df2f18 to your computer and use it in GitHub Desktop.
Save kixorz/627a9235b21fe9df2f18 to your computer and use it in GitHub Desktop.
EC2 DNS load-balancing init.d script. Instances automatically register themselves in Route53 RecordSets and properly update their records when starting/shutting down. Instances need to use attached IAM role allowing them to modify the Route53 zone.
#!/usr/bin/ruby
# chkconfig: 35 99 01
# description: EC2 DNS loadbalancing
# processname: ec2hostname
require 'aws-sdk'
require 'net/http'
`touch /var/lock/subsys/ec2hostname`
HOSTNAME = '<hostname>'
DOMAIN = '<your domain name>'
ZONE = '<your hosted zone id>'
TYPE = 'A'
TTL = 60
metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
ip_local = Net::HTTP.get( URI.parse( metadata_endpoint + 'local-ipv4' ) )
ip_public = Net::HTTP.get( URI.parse( metadata_endpoint + 'public-ipv4' ) )
records = []
records << { :target => ip_local, :alias => [ HOSTNAME, DOMAIN, '' ] * '.' }
records << { :target => ip_public, :alias => [ HOSTNAME + '-public', DOMAIN, '' ] * '.' }
changes = []
rrsets = AWS::Route53::HostedZone.new(ZONE).rrsets
records.each{ |record|
rrset = rrsets[
record[:alias],
TYPE
]
existing_records = []
if rrset.exists?
existing_records = rrset.resource_records.select{ |r| r[:value] != record[:target] }
changes << AWS::Route53::DeleteRequest.new(record[:alias], TYPE, :ttl => TTL, :resource_records => rrset.resource_records)
end
existing_records << { :value => record[:target] } if ARGV[0] != 'stop'
changes << AWS::Route53::CreateRequest.new(record[:alias], TYPE, :ttl => TTL, :resource_records => existing_records) unless existing_records.empty?
}
r53 = AWS::Route53.new
response = r53.client.change_resource_record_sets({
hosted_zone_id: ZONE,
change_batch: { changes: changes }
})
`rm -f /var/lock/subsys/ec2hostname` if ARGV[0] == 'stop'
{
"Action": [
"route53:ChangeResourceRecordSets",
"route53:GetHostedZone",
"route53:ListResourceRecordSets"
],
"Effect": "Allow",
"Resource": [
[ "arn:aws:route53:::hostedzone/<your hosted zone id>" ]
]
}
@sandeep540
Copy link

Can I define the below 3 in Ec2 Tags and fetch it in program?

HOSTNAME = '<hostname>'
DOMAIN = '<your domain name>'
ZONE = '<your hosted zone id>'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment