Skip to content

Instantly share code, notes, and snippets.

@espen
Forked from kixorz/ec2hostname.rb
Last active October 20, 2016 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save espen/ee483d6c27c4b7ef08b82d64955c91c8 to your computer and use it in GitHub Desktop.
Save espen/ee483d6c27c4b7ef08b82d64955c91c8 to your computer and use it in GitHub Desktop.
EC2 Instance Route53 Hostname registration init.d script. Instance needs to have the attached IAM instance role policy applied.
#!/usr/bin/ruby
# chkconfig: 35 99 01
# description: EC2 DNS registration
# processname: ec2hostname
require 'aws-sdk'
require 'net/http'
require 'socket'
`touch /var/lock/subsys/ec2hostname`
hostname = '<hostname>'
domain = '<your domain name>'
zone = '<your hosted zone id>'
ttl = 60
hostname_local = Socket.ip_address_list.detect{|intf| intf.ipv4_private?}.ip_address()
records = [{
:alias => [ hostname, domain, '' ] * '.',
:target => hostname_local
}]
rrsets = AWS::Route53::HostedZone.new(zone).rrsets
case ARGV[0]
when 'start', 'restart'
records.each{ |record|
rrset = rrsets[
record[ :alias ],
'CNAME'
]
rrset.delete if rrset.exists?
rrset = rrsets.create(
record[ :alias ],
'CNAME',
:ttl => ttl,
:resource_records => [
{ :value => record[ :target ] }
]
)
}
when 'stop'
records.each{ |record|
rrset = rrsets[
record[ :alias ],
'CNAME'
]
rrset.delete if rrset.exists?
}
end
`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>" ]
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment