Class: InstantEC2

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(credentials: [], region: 'us-east-1') ⇒ InstantEC2

Returns a new instance of InstantEC2.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/instant_ec2.rb', line 28

def initialize(credentials: [], region: 'us-east-1')

  @ec2 = Aws::EC2::Client.new(region: region, 
                             credentials: Aws::Credentials.new(*credentials))

  r = @ec2.describe_instances.reservations
  image_ids = r.map{|x| x[:instances][0][:image_id] }
  image_names = @ec2.describe_images(image_ids: image_ids).images.\
                                                           map{|x| x.name }
  instance_ids = r.map{|x| x.instances[0].instance_id}

  @images = image_names.zip(instance_ids).inject([]) do |r, x|

    name, id = x
    r << EC2Instance.new({image_name: name, instance_id: id}, @ec2)
    
  end

end

Instance Attribute Details

#imagesObject (readonly)

Returns the value of attribute images.



26
27
28
# File 'lib/instant_ec2.rb', line 26

def images
  @images
end

Instance Method Details

#find_image(s) ⇒ Object



48
49
50
# File 'lib/instant_ec2.rb', line 48

def find_image(s)
  @images.find {|x| x[:image_name][/#{s}/i]}
end

#find_runningObject Also known as: running



52
53
54
55
56
57
58
# File 'lib/instant_ec2.rb', line 52

def find_running()

  r = @ec2.describe_instances.reservations.detect do |x|
    x.instances[0].state.name != 'stopped'
  end

end

#ipObject



60
61
62
63
# File 'lib/instant_ec2.rb', line 60

def ip()
  r = self.find_running
  r.instances[0].public_ip_address if r
end

#on_runningObject



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/instant_ec2.rb', line 65

def on_running()
  
  # timeout after 30 seconds
  t1 = Time.now
  sleep 1; ip = self.ip until ip or Time.now > t1 + 30
  
  if ip then 
    yield(ip) 
  else
    puts 'on_running timedout'
  end
  
end

#on_stoppingObject



100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/instant_ec2.rb', line 100

def on_stopping()
  
  # timeout after 30 seconds
  t1 = Time.now
  sleep 1; ip = self.ip until ip.nil? or Time.now > t1 + 30
  
  if ip.nil? then 
    yield
  else
    puts 'on_stopping timedout'
  end
  
end

#start(s) ⇒ Object



81
82
83
# File 'lib/instant_ec2.rb', line 81

def start(s)
  self.find_image(s).start
end

#stopObject



85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/instant_ec2.rb', line 85

def stop

  r = self.find_running()

  if r then
    
    puts 'stopping ...'
    instance_id = r.instances[0].instance_id      
    @ec2.stop_instances instance_ids: [instance_id]
    
  else
    puts 'no instances to stop'
  end
end