Skip to content

Instantly share code, notes, and snippets.

@kixorz
Last active April 11, 2022 10:32
Show Gist options
  • Save kixorz/5146008 to your computer and use it in GitHub Desktop.
Save kixorz/5146008 to your computer and use it in GitHub Desktop.
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 …
{
"Statement": [
{
"Action": [
"route53:ChangeResourceRecordSets",
"route53:GetHostedZone",
"route53:ListResourceRecordSets"
],
"Effect": "Allow",
"Resource": [
"arn:aws:route53:::hostedzone/<your hosted zone id>"
]
}
]
}
#!/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 ] }
]
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment