Skip to content

Instantly share code, notes, and snippets.

@kixorz
Last active June 3, 2022 11:27
Show Gist options
  • Save kixorz/81287bb06dbc5e16e96b to your computer and use it in GitHub Desktop.
Save kixorz/81287bb06dbc5e16e96b 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'
`touch /var/lock/subsys/ec2hostname`
hostname = '<hostname>'
domain = '<your domain name>'
zone = '<your hosted zone id>'
ttl = 60
metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
hostname_local = Net::HTTP.get( URI.parse( metadata_endpoint + 'local-hostname' ) )
hostname_public = Net::HTTP.get( URI.parse( metadata_endpoint + 'public-hostname' ) )
records = [{
:alias => [ hostname, domain, '' ] * '.',
:target => hostname_local
}, {
:alias => [ hostname + '-public', domain, '' ] * '.',
:target => hostname_public
}]
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