-
-
Save apsoto/806105 to your computer and use it in GitHub Desktop.
Rake task to update Amazon Route53 DNS from by Chef node search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- ruby -*- | |
# Needs following parameters configured in rake.rb: | |
# DNS_DOMAIN: domain for which to set entries, including trailing dot | |
# (e.g. "example.com.") | |
# DNS_ATTRIBUTE: attribute containing hostname to CNAME to, defaults | |
# to 'fqdn'; for EC2, use "ec2.public_hostname" | |
# DNS_ENTRIES: hash mapping hostname to node search query, | |
# e.g. {'buildbot' => 'recipes:buildbot', 'monitoring' => | |
# 'roles:monitoring'} | |
DNS_ATTRIBUTE ||= 'fqdn' | |
desc "Update Route53 entries within #{DNS_DOMAIN}" | |
task :update_dns do | |
require 'escape' | |
require 'fog' | |
require 'json' | |
# Build up table of DNS entries | |
dns = {} | |
DNS_ENTRIES.each_pair do |hostname, query| | |
q = Escape::shell_single_word query | |
r = JSON::load `knife search node #{q} -a #{DNS_ATTRIBUTE}` | |
if r["total"].zero? | |
puts "WARN: No host found for #{query} - not touching #{hostname}" | |
else | |
dns["#{hostname}.#{DNS_DOMAIN}"] = r["rows"][0][DNS_ATTRIBUTE] | |
if r["total"] != 1 | |
puts "WARN: Multiple results found for #{query}, using first" | |
end | |
end | |
end | |
if ENV['VERBOSE'] | |
require 'pp' | |
pp dns | |
end | |
# https://github.com/geemus/excon/issues#issue/13 | |
# "certificate verify failed" workaround | |
Excon.ssl_verify_peer = false | |
r53 = Fog::DNS.new(:provider => "AWS", | |
:aws_access_key_id => AWS_ACCESS_KEY_ID, | |
:aws_secret_access_key => AWS_SECRET_ACCESS_KEY) | |
zone = r53.zones.find { |z| z.domain == DNS_DOMAIN } | |
zone.records.find_all { |r| | |
not dns.keys.include? r.name | |
}.each do |r| | |
puts "- #{r.name}" | |
r.destroy | |
end | |
zone.records.find_all { |r| | |
(dns.keys.include? r.name) and (r.ip[0] != dns[r.name]) | |
}.each do |r| | |
puts "* #{r.name} -> #{dns[r.name]}" | |
r.ip = [ dns[r.name] ] | |
r.save | |
end | |
(dns.keys - zone.records.map { |r| r.name }).each do |name| | |
puts "+ #{name} -> #{dns[name]}" | |
zone.records.create(:ip => dns[name], | |
:name => name, | |
:type => "CNAME") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment