Class: Pec2::Ec2

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

Instance Method Summary collapse

Constructor Details

#initializeEc2

Returns a new instance of Ec2.



15
16
17
18
19
# File 'lib/pec2/ec2.rb', line 15

def initialize
  @logger = Logger.new(STDOUT)
  ENV['AWS_REGION'] = ENV['AWS_REGION'] || get_document['region']
  @ec2 = Aws::EC2::Client.new
end

Instance Method Details

#get_documentObject



32
33
34
# File 'lib/pec2/ec2.rb', line 32

def get_document
  JSON.parse(('/latest/dynamic/instance-identity/document/'))
end

#get_metadata(path) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pec2/ec2.rb', line 36

def (path)
  begin
    result = {}
    Timeout.timeout(TIME_OUT) {
      body = open('http://169.254.169.254' + path).read
      return body
    }
    return result
  rescue Timeout::Error => e
    raise "not EC2 instance"
  end
end

#instances_hash(condition) ⇒ Object



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

def instances_hash(condition)
  filter = []
  condition.each do |key, value|
    filter << { name: "tag:#{key}", values: ["#{value}"] }
  end
  filter << { name: 'instance-state-name', values: ['running'] }
  @ec2.describe_instances(
    filters: filter
  ).data.to_h[:reservations].map { |instance| Pec2Mash.new(instance[:instances].first) }
end