Last active
December 20, 2015 12:39
-
-
Save sawanoboly/6132885 to your computer and use it in GitHub Desktop.
Create Route53 records from bind zonefile.
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
require 'zonefile' | |
require 'route53' | |
my_access_key = 'REPLACE_TO_YOUR_KEY' | |
my_secret_key = 'REPLACE_TO_YOUR_SECRET' | |
domain = 'example.com.' | |
zone_id = '/hostedzone/ZONEID' | |
default_ttl = '600' | |
conn = Route53::Connection.new(my_access_key,my_secret_key,'2011-05-05' , 'https://route53.amazonaws.com/',false , true) | |
mng_zone = Route53::Zone.new(domain,zone_id,conn) | |
zonefile = Zonefile.from_file('./example.com.zone') | |
# zonefile = Zonefile.new($stdin.read) | |
def build_namelist(records) | |
records.map{|obj| obj[:name]}.uniq | |
end | |
def build_hostlist(name, records) | |
hosts = [] | |
records.each do |rec| | |
hosts << rec[:host] if name == rec[:name] | |
end | |
hosts | |
end | |
def build_mx_hostlist(records) | |
records.map{|mx| [mx[:pri].to_s, mx[:host]].join(' ')} | |
end | |
def prepare_ttl(name, records) | |
records.select{|x| x[:name] == records}.first.tap do |x| | |
break x[:ttl] if x | |
end | |
end | |
%w(a cname txt mx).each do |w| | |
namelist = build_namelist(zonefile.records[w.to_sym]) | |
namelist.each do |name| | |
hosts = build_hostlist(name, zonefile.records[w.to_sym]) | |
ttl = prepare_ttl(name, zonefile.records[w.to_sym]) || default_ttl | |
case w | |
when 'a' | |
if name == '@' | |
new_name = domain | |
elsif name.end_with?('.') | |
new_name = name | |
else | |
new_name = [name ,domain].join('.') | |
end | |
new_record = Route53::DNSRecord.new(new_name, w.to_s.upcase , ttl.to_s, hosts ,mng_zone) | |
when 'cname' | |
if name.end_with?('.') | |
new_name = name | |
else | |
hosts.map!{|h| [h,domain].join('.')} | |
new_name = [name ,domain].join('.') | |
end | |
new_record = Route53::DNSRecord.new(new_name, w.to_s.upcase , ttl.to_s, hosts ,mng_zone) | |
when 'txt' | |
zonefile.records[w.to_sym].each do |record| | |
new_record = Route53::DNSRecord.new(domain, w.to_s.upcase , record[:ttl] || default_ttl, [record[:text]] ,mng_zone) | |
puts new_record | |
new_record.create | |
end | |
next | |
when 'mx' | |
hosts = build_mx_hostlist(zonefile.records[w.to_sym]) | |
new_record = Route53::DNSRecord.new(name, w.to_s.upcase , ttl.to_s, hosts ,mng_zone) | |
else | |
puts "Unsupport resource type detected. -> #{w.to_s.upcase}" | |
end | |
new_record.create | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change their values.
REPLACE_TO_YOUR_KEY
REPLACE_TO_YOUR_SECRET
ZONEID