You are here: Home / presentations / Open Cloud / APIs / Fog (code)

Fog (code)

by Alan Milligan last modified Sep 05, 2012 05:27 AM
rubygem-fog
require 'rubygems'
require 'fog'
require 'optparse'
require 'pp'

$opt = { :ttl => 3600, :cname => ['www', 'mail'] }

optparse = OptionParser.new do|opts|
opts.on('-c', '--create', 'Create zone') do
$opt[:create] = true
end
opts.on('-d', '--delete', 'Remove zone') do
$opt[:delete] = true
end
opts.on('-r', '--reload', 'Delete and re-add all the resource recs') do
$opt[:reload] = true  # force delete of old recs w old cnames
$opt[:create] = true  # force create of new recs w new cnames
end
opts.on('-z', '--zone ZONE', 'Zone dn') do |v|
$opt[:zone] = v
end
opts.on('-i', '--ip IP', 'IP Addr') do |v|
$opt[:ip] = v
end
opts.on('--hostname HOSTNAME', 'host/machine name') do |v|
$opt[:hostname] = v
end
opts.on('--cname a,b,c', Array, 'CNAME list') do |v|
$opt[:cname] = v
end
opts.on('-t', '--ttl TTL', Integer, 'time to live') do |v|
$opt[:ttl] = v
end
# This displays the help screen, all programs are
# assumed to have this option.
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end

optparse.parse!

def zone(zones, zonename)
# retrieve a Zone ...
zones.each do |zone|
if zone.domain == "#{$opt[:zone]}."
return zone
end
end
return nil
end

def create_rr(zone, value, name, type)
# check existance and create a resource record in the zone
zone.records.each do |rr|
if rr.name.start_with?(name) and rr.type == type
return
end
end
zone.records.create(:value => value, :name => name, :type => type, :ttl => $opt[:ttl])
end

@dns = Fog::DNS.new({:provider => 'AWS'})

if $opt.has_key?(:delete) or $opt.has_key?(:reload)
# remove resource recs (well not NS and SOA ...)
z = zone(@dns.zones, $opt[:zone])
if z
z.records.each do |rr|
rr.destroy
end
end
end

if $opt.has_key?(:create)
# retrieve or create ...
@zone = zone(@dns.zones, $opt[:zone])
if !@zone
@zone = @dns.zones.create(:domain => $opt[:zone], :email  => "info@#{$opt[:zone]}")
end

@record = create_rr(@zone, $opt[:ip], "#{$opt[:hostname]}.#{$opt[:zone]}", 'A')

$opt[:cname].each do |cname|
@record = create_rr(@zone, "#{$opt[:hostname]}.#{$opt[:zone]}", "#{cname}.#{$opt[:zone]}", 'CNAME')
end

if $opt[:cname].include?('mail')
# set up MX + SPF if a mail CNAME exists
@record = create_rr(@zone, "0 mail.#{$opt[:zone]}", "#{$opt[:hostname]}.#{$opt[:zone]}", 'MX')
['TXT', 'SPF'].each do |type|
# note double-quoted value(s) !!
@record = create_rr(@zone, "\"v=spf1 ip4:#{$opt[:ip]} mx ~all\"", $opt[:zone], type)
end
end
end

if $opt.has_key?(:delete)
z = zone(@dns.zones, $opt[:zone])
if z
z.destroy
end
end

# show what it looks like now...
@dns.zones.each do |zone|
pp zone
zid = zone.id
# seems the nameservers stuff isn't properly populated ...
pp @dns.get_hosted_zone(zid)

#pp zone.records
pp @dns.list_resource_record_sets(zid)
end