Module: Enscalator::Helpers::Dns

Included in:
Enscalator::Helpers
Defined in:
lib/enscalator/helpers/dns.rb

Instance Method Summary collapse

Instance Method Details

#get_dns_records(zone_name: nil) ⇒ Object

Get existing DNS records

Parameters:

  • zone_name (String) (defaults to: nil)

    name of the hosted zone



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/enscalator/helpers/dns.rb', line 7

def get_dns_records(zone_name: nil)
  client = route53_client(nil)
  zone = client.list_hosted_zones[:hosted_zones].find { |x| x.name == zone_name }
  records = client.list_resource_record_sets(hosted_zone_id: zone.id)
  records.values.flatten.map do |x|
    {
      name: x.name,
      type: x.type,
      records: x.resource_records.map(&:value)
    } if x.is_a?(Aws::Structure)
  end.compact
end

#upsert_dns_record(region: nil, zone_name: nil, record_name: nil, type: 'A', values: [], ttl: 300, suffix: '') ⇒ Object

Create DNS record in given hosted zone

Parameters:

  • region (String) (defaults to: nil)

    aws valid region identifier

  • zone_name (String) (defaults to: nil)

    name of the hosted zone

  • record_name (String) (defaults to: nil)

    name of the dns record

  • type (String) (defaults to: 'A')

    record type (NS, MX, CNAME and etc.)

  • values (Array) (defaults to: [])

    list of record values

  • ttl (Integer) (defaults to: 300)

    time to live

  • suffix (String) (defaults to: '')

    additional identifier following region



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/enscalator/helpers/dns.rb', line 29

def upsert_dns_record(region: nil,
                      zone_name: nil,
                      record_name: nil,
                      type: 'A',
                      values: [],
                      ttl: 300,
                      suffix: '')
  client = route53_client(region: region)
  zone = client.list_hosted_zones[:hosted_zones].find { |x| x.name == zone_name }
  record_tokens = [record_name.gsub(zone_name, ''), region]
  record_tokens << suffix if suffix && !suffix.empty?
  record_name = [record_tokens.join, zone_name].join('.')

  client.change_resource_record_sets(
    hosted_zone_id: zone.id,
    change_batch: {
      comment: "dns record for #{record_name}",
      changes: [
        {
          action: 'UPSERT',
          resource_record_set: {
            name: record_name,
            type: type,
            resource_records: values.map { |x| { value: x } },
            ttl: ttl
          }
        }
      ]
    }
  )
end