Class: UltraDNSUpdater::Ec2

Inherits:
Object
  • Object
show all
Defined in:
lib/ultradns_updater/ec2.rb

Constant Summary collapse

EC2_META_DATA_URL =
"http://169.254.169.254/latest/meta-data"

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Ec2

Returns a new instance of Ec2.



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/ultradns_updater/ec2.rb', line 19

def initialize(opts = {})
  AWS.config(
    :access_key_id => opts[:access_key_id],
    :secret_access_key => opts[:secret_access_key])
    
  @logger = opts[:logger] || Logger.new(STDOUT)
  
  # also configure HTTPI
  HTTPI.logger = @logger
  HTTPI.log_level = :debug
  @tag_name = opts[:name_tag] || 'Name' # default to Name
end

Instance Method Details

#ec2Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/ultradns_updater/ec2.rb', line 71

def ec2
  @ec2_region ||= begin
    ec2 = AWS::EC2.new
    region = nil
    ec2.regions.each do |r| 
      if r.instances.map(&:id).include?(get_instance_id())
        region = r
        break
      end
    end
    @logger.error "No region found for instance: #{get_instance_id()}" if region.nil?
    region
  end
rescue => ex
  @logger.error "Error talking to AWS: #{ex}"
end

#get_instance_idObject



32
33
34
35
36
37
38
39
# File 'lib/ultradns_updater/ec2.rb', line 32

def get_instance_id
  @instance_id ||= begin    
    response = HTTPI.get(URI("#{EC2_META_DATA_URL}/instance-id").to_s)
    response.code == 200 ? response.body : ''
  end
  @logger.debug("Instance ID = #{@instance_id}")
  @instance_id
end

#get_instance_public_hostnameObject



41
42
43
44
45
46
47
48
# File 'lib/ultradns_updater/ec2.rb', line 41

def get_instance_public_hostname
  @public_hostname ||= begin
    response = HTTPI.get(URI("#{EC2_META_DATA_URL}/public-hostname").to_s)
    response.code == 200 ? response.body : ''
  end
  @logger.debug("Public Hostname = #{@public_hostname}")
  @public_hostname
end

#get_instance_public_ipv4Object



50
51
52
53
54
55
56
57
# File 'lib/ultradns_updater/ec2.rb', line 50

def get_instance_public_ipv4
  @public_ipv4 ||= begin
    response = HTTPI.get(URI("#{EC2_META_DATA_URL}/public-ipv4").to_s)
    response.code == 200 ? response.body : ''
  end
  @logger.debug("Public IPv4 = #{@public_ipv4}")
  @public_ipv4
end

#get_name_tagObject



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/ultradns_updater/ec2.rb', line 59

def get_name_tag
  dns_cname = ''
  ec2.tags.filter('resource-id', get_instance_id()).each do |tag|
    @logger.debug { tag.resource.inspect } # resource is an EC2 object, e.g. AWS::EC2::VPC
    @logger.debug { tag.name }
    @logger.debug { tag.value }
    dns_cname = tag.value if tag.name == @tag_name
  end
  @logger.debug("Tagged DNS CNAME = #{dns_cname} for #{get_instance_id()}")
  dns_cname
end