public
Last active

Update Route53 DNS records from your EC2 instance using this simple Ruby script. You can call it from rc.local after setting your hostname locally. First parameter is the desired <hostname>.<domain> Domain and other parameters are hardcoded. This script is useful for handling internal DNS changes in your systems after instance changes. Attached is also IAM policy for your AWS IAM user. You should create a new user for this and not use your admin credentials to keep the security tight.

  • Download Gist
aws_iam_policy.json
JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
{
"Statement": [
{
"Action": [
"route53:ChangeResourceRecordSets",
"route53:GetHostedZone",
"route53:ListResourceRecordSets"
],
"Effect": "Allow",
"Resource": [
"arn:aws:route53:::hostedzone/<your hosted zone id>"
]
}
]
}
aws_update_dns.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#!/usr/bin/env ruby
require 'aws-sdk'
require 'net/http'
 
AWS.config({
:access_key_id => '<iam user key>',
:secret_access_key => '<iam user secret>'
})
 
hostname = ARGV[0].to_s
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
}]
 
#update DNS records
rrsets = AWS::Route53::HostedZone.new(zone).rrsets
records.each{ |record|
rrset = rrsets[
record[ :alias ],
'CNAME'
]
 
if rrset.exists?
rrset.delete
end
 
rrset = rrsets.create(
record[ :alias ],
'CNAME',
:ttl => ttl,
:resource_records => [
{ :value => record[ :target ] }
]
)
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.