Skip to content

Instantly share code, notes, and snippets.

@bjjb
Created January 2, 2013 20:43
Show Gist options
  • Save bjjb/4437813 to your computer and use it in GitHub Desktop.
Save bjjb/4437813 to your computer and use it in GitHub Desktop.
A simple Ruby script for creating or updating a Linode DNS A record for the current host (i.e. - Dynamic DNS)
#!/usr/bin/env ruby
require 'linode'
require 'open-uri'
$api_key = "MY LINODE API KEY"
$subdomain = "my.subdomain.example.com"
# Updates a Linode DNS record. Can be used to create a dynamic DNS within a
# domain of your own. Just set the subdomain to whatever.
# Requires Ruby, linode (`gem install linode`), and an account with Linode
# (linode.com).
class DNSUp
attr_accessor :linode, :subdomain, :domain, :name, :target, :type
def initialize(options = {})
options = {
:api_key => $api_key,
:subdomain => $subdomain,
:type => 'A'
}.merge(options)
@linode = Linode.new(:api_key => options[:api_key])
@subdomain = options[:subdomain]
@name = @subdomain.split('.').first
@domain = @subdomain.sub(/\A#{@name}\./, '')
@type = options[:type] || 'A'
@target = options[:target] || self.class.remote_ip
end
def self.remote_ip
@remote_ip ||= open('http://icanhazip.com').read.chomp
end
def domain_id
@domain_id ||= @linode.domain.list.find do |d|
d.domain == @domain
end.domainid
end
def resource_list
raise(InvalidDomain, @domain) if domain_id.nil?
@resource_list ||= @linode.domain.resource.list(:DomainID => domain_id)
end
def resource
@resource ||= resource_list.find { |r| r.name == @name }
end
def resource_options
{
:DomainID => domain_id,
:Target => target,
:Name => name
}
end
def update
if resource.nil?
create
else
options = resource_options.merge(:ResourceID => resource.resourceid)
puts "Updating... #{options.inspect}"
@linode.domain.resource.update(options)
end
end
def create
options = resource_options.merge(:Type => type)
puts "Creating... #{options.inspect}"
@linode.domain.resource.create(options)
end
class InvalidDomain < Exception; end
end
if __FILE__ == $0
DNSUp.new.update
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment