Class: DynamicDns::DnsUpdater

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic_dns/dns_updater.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(domain, subdomain = nil) ⇒ DnsUpdater

Returns a new instance of DnsUpdater.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/dynamic_dns/dns_updater.rb', line 8

def initialize(domain, subdomain = nil)
  log 'created instance'
  # error handling
  domain.is_a? String or raise RuntimeError, "Invalid domain, must be a String: #{domain}"
  subdomain and subdomain.is_a? String or raise RuntimeError, "Invalid subdomain, must be nil or a String: #{subdomain}"
  # set up constants
  @DOMAIN = domain
  @NAME = create_name(@DOMAIN, subdomain)
  @RECORD_TYPE = 'A'
  @CLIENT = Aws::Route53::Client.new(region: 'us-east-1')
  # fetch the available hosted zones
  log('fetch hosted zones')
  zones = @CLIENT.list_hosted_zones_by_name
  zones = zones.hosted_zones
  # search for the hosted zone matching the configured domain
  log("match hosted zone for domain: #{@DOMAIN}")
  @ZONE = zones.bsearch { |z| z.name.match?("^#{@DOMAIN}") }
  @ZONE or raise RuntimeError, "No hosted zones match #{@DOMAIN}"
end

Instance Attribute Details

#DOMAINObject (readonly)

accessor methods



29
30
31
# File 'lib/dynamic_dns/dns_updater.rb', line 29

def DOMAIN
  @DOMAIN
end

#NAMEObject (readonly)

Returns the value of attribute NAME.



30
31
32
# File 'lib/dynamic_dns/dns_updater.rb', line 30

def NAME
  @NAME
end

Instance Method Details

#create_name(domain, subdomain) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/dynamic_dns/dns_updater.rb', line 32

def create_name(domain, subdomain)
  if subdomain
    "#{subdomain}.#{domain}"
  else
    domain
  end
end

#log(msg) ⇒ Object

prefixed log function



68
69
70
# File 'lib/dynamic_dns/dns_updater.rb', line 68

def log(msg)
  puts "[dynamic-dns:dns-updater] #{msg}"
end

#update_record_ip(ip, ttl = 60) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/dynamic_dns/dns_updater.rb', line 40

def update_record_ip(ip, ttl = 60)
  log "update #{@RECORD_TYPE} record for #{@NAME} to point to #{ip}"
  resp = @CLIENT.change_resource_record_sets({
    change_batch: {
      changes: [
        {
          action: 'UPSERT',
          resource_record_set: {
            name: @NAME,
            resource_records: [
              {
                value: ip
              }
            ],
            type: @RECORD_TYPE,
            ttl: ttl 
          }
        }
      ],
      comment: 'Update from dynamic dns ruby script'
    },
    hosted_zone_id: @ZONE.id
  })
  resp = resp.change_info
  log "update of id #{resp.id} is #{resp.status} at #{resp.}"
end