Class: Rudy::AWS::EC2::Instances

Inherits:
Object
  • Object
show all
Includes:
Base, ObjectBase
Defined in:
lib/rudy/aws/ec2/instance.rb

Constant Summary collapse

KNOWN_STATES =
[:running, :pending, :shutting_down, :terminated, :degraded].freeze

Instance Attribute Summary

Attributes included from Base

#ec2

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Base

#initialize

Methods included from Huxtable

change_environment, change_position, change_region, change_role, change_zone, #check_keys, #config_dirname, create_domain, #current_group_name, #current_machine_address, #current_machine_count, #current_machine_group, #current_machine_hostname, #current_machine_image, #current_machine_name, #current_machine_size, #current_user, #current_user_keypairpath, debug?, #debug?, domain, domain_exists?, #group_metadata, #has_keypair?, #has_keys?, #has_pem_keys?, #has_root_keypair?, keypair_path_to_name, #known_machine_group?, #root_keypairname, #root_keypairpath, #switch_user, update_config, update_global, update_logger, #user_keypairname, #user_keypairpath

Class Method Details

.from_hash(h) ⇒ Object

h is a hash of instance properties in the format returned by EC2::Base#describe_instances:

kernelId: aki-9b00e5f2
amiLaunchIndex: "0"
keyName: solutious-default
launchTime: "2009-03-14T12:48:15.000Z"
instanceType: m1.small
imageId: ami-0734d36e
privateDnsName: 
reason: 
placement: 
  availabilityZone: us-east-1b
dnsName: 
instanceId: i-cdaa34a4
instanceState: 
  name: pending
  code: "0"

Returns an Instance object.



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/rudy/aws/ec2/instance.rb', line 374

def self.from_hash(h)
  inst = Rudy::AWS::EC2::Instance.new
  inst.aki = h['kernelId']
  inst.ami = h['imageId']
  inst.launch_time = h['launchTime']
  inst.keyname = h['keyName']
  inst.launch_index = h['amiLaunchIndex']
  inst.size = h['instanceType']
  inst.dns_private = h['privateDnsName']
  inst.dns_public = h['dnsName']
  inst.reason = h['reason']
  inst.zone = h['placement']['availabilityZone']
  inst.awsid = h['instanceId']
  inst.state = h['instanceState']['name']
  inst
end

.known_state?(state) ⇒ Boolean

Is state a known EC2 machine instance state? See: KNOWN_STATES

Returns:

  • (Boolean)


392
393
394
395
396
397
# File 'lib/rudy/aws/ec2/instance.rb', line 392

def self.known_state?(state)
  return false unless state
  state &&= state.to_sym
  state = :shutting_down if state == :'shutting-down'
  KNOWN_STATES.member?(state)
end

Instance Method Details

#any?(state = :any, inst_ids = []) ⇒ Boolean

Returns:

  • (Boolean)


317
318
319
# File 'lib/rudy/aws/ec2/instance.rb', line 317

def any?(state=:any, inst_ids=[])
  !list(state, inst_ids).nil?
end

#any_group?(group = nil, state = :any) ⇒ Boolean

Returns:

  • (Boolean)


325
326
327
328
# File 'lib/rudy/aws/ec2/instance.rb', line 325

def any_group?(group=nil, state=:any)
  ret = list_group(group, state)
  !ret.nil?
end

#attached_volume?(id, device) ⇒ Boolean

Returns:

  • (Boolean)


289
290
291
292
293
294
295
# File 'lib/rudy/aws/ec2/instance.rb', line 289

def attached_volume?(id, device)
  list = volumes(id)
  list.each do |v|
    return true if v.device == device
  end
  false
end

#console(inst_id, &each_inst) ⇒ Object

System console output.

  • inst_id instance ID (String) or Instance object.

NOTE: Amazon sends the console outputs as a Base64 encoded string. This method DOES NOT decode in order to remain compliant with the data formats returned by Amazon.

You can decode it like this:

require 'base64'
Base64.decode64(output)


281
282
283
284
285
286
287
# File 'lib/rudy/aws/ec2/instance.rb', line 281

def console(inst_id, &each_inst)
  inst_ids = objects_to_instance_ids([inst_id])
  response = execute_request({}) { 
    @ec2.get_console_output(:instance_id => inst_ids.first)
  }
  response['output']
end

#create(opts = {}, &each_inst) ⇒ Object

Return an Array of Instance objects. Note: These objects will not have DNS data because they will still be in pending state. The DNS info becomes available once the instance enters the running state.

opts supports the following parameters:

  • :ami

  • :group

  • :size

  • :keypair

  • :private true or false (default)

  • :machine_data

  • :min count

  • :max count

Raises:



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/rudy/aws/ec2/instance.rb', line 93

def create(opts={}, &each_inst)
  raise NoAMI unless opts[:ami]
  raise NoGroup unless opts[:group]
  
  opts = {
    :size => 'm1.small',
    :min => 1,
    :max => nil
  }.merge(opts)
  
  old_opts = {
    :image_id => opts[:ami].to_s,
    :min_count => opts[:min],
    :max_count => opts[:max] || opts[:min],
    :key_name => (opts[:keypair] || '').to_s,
    :group_id => [opts[:group]].flatten.compact,
    #:user_data => opts[:machine_data],  # Error: Invalid BASE64 encoding of user data ??
    :availability_zone => opts[:zone].to_s,
    :addressing_type => opts[:private] ? 'private' : 'public',
    :instance_type => opts[:size].to_s,
    :kernel_id => nil
  }
  #p opts[:machine_data]
  #exit
  
  response = execute_request({}) { @ec2.run_instances(old_opts) }
  return nil unless response['instancesSet'].is_a?(Hash)
  instances = response['instancesSet']['item'].collect do |inst|
    self.class.from_hash(inst)
  end
  instances.each { |inst| 
    each_inst.call(inst) 
  } if each_inst
  instances
end

#destroy(inst_ids = [], &each_inst) ⇒ Object

Raises:



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/rudy/aws/ec2/instance.rb', line 139

def destroy(inst_ids=[], &each_inst)
  instances = list(:running, inst_ids, &each_inst) || [] 
  raise NoRunningInstances if instances.empty?

  inst_ids = objects_to_instance_ids(inst_ids)
      
  response = execute_request({}) {
    @ec2.terminate_instances(:instance_id => inst_ids)
  }

  #instancesSet: 
  #  item: 
  #  - instanceId: i-ebdcb882
  #    shutdownState: 
  #      code: "48"
  #      name: terminated
  #    previousState: 
  #      code: "48"
  #      name: terminated

  raise MalformedResponse unless response['instancesSet'].is_a?(Hash)
  instances_shutdown = []
  response['instancesSet']['item'].collect do |inst|
    next unless inst['shutdownState'].is_a?(Hash) && inst['shutdownState']['name'] == 'shutting-down'
    instances_shutdown << inst['instanceId']
  end
  success = instances_shutdown.size == inst_ids.size
  success
end

#destroy_group(group, &each_inst) ⇒ Object



175
176
177
178
179
# File 'lib/rudy/aws/ec2/instance.rb', line 175

def destroy_group(group, &each_inst)
  instances = list_group(group, :running, &each_inst) || []
  inst_ids = objects_to_instance_ids(instances)
  destroy(inst_ids, :skip_check)
end

#device_volume(id, device) ⇒ Object



304
305
306
# File 'lib/rudy/aws/ec2/instance.rb', line 304

def device_volume(id, device)
  volumes(id).select { |v| v.device === device }
end

#exists?(inst_ids) ⇒ Boolean

Returns:

  • (Boolean)


321
322
323
# File 'lib/rudy/aws/ec2/instance.rb', line 321

def exists?(inst_ids)
  any?(:any, inst_ids)
end

#get(inst_id) ⇒ Object

inst_id is an instance ID Returns an Instance object



310
311
312
313
314
315
# File 'lib/rudy/aws/ec2/instance.rb', line 310

def get(inst_id)
  inst_id = inst_id.awsid if inst_id.is_a?(Rudy::AWS::EC2::Instance)
  inst = list(:any, inst_id) 
  inst &&= inst.first
  inst
end

#list(state = nil, inst_ids = [], &each_inst) ⇒ Object

  • state is an optional instance state. If specified, must be one of: running (default), pending, terminated.

  • inst_ids is an Array of instance IDs.

Returns an Array of Rudy::AWS::EC2::Instance objects.



184
185
186
187
188
189
# File 'lib/rudy/aws/ec2/instance.rb', line 184

def list(state=nil, inst_ids=[], &each_inst)
  instances = list_as_hash(state, inst_ids, &each_inst)
  instances &&= instances.values
  instances = nil if instances && instances.empty? # Don't return an empty hash
  instances
end

#list_as_hash(state = nil, inst_ids = [], &each_inst) ⇒ Object

  • state is an optional instance state. If specified, must be

one of: running (default), pending, terminated, any

  • inst_ids is an Array of instance IDs or Rudy::AWS::EC2::Instance objects.

Returns a Hash of Rudy::AWS::EC2::Instance objects. The key is the instance ID.

  • each_inst a block to execute for every instance in the list.



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/rudy/aws/ec2/instance.rb', line 221

def list_as_hash(state=nil, inst_ids=[], &each_inst)
  state &&= state.to_sym
  state = nil if state == :any
  raise "Unknown state: #{state}" if state && !Instances.known_state?(state)
  state = :'shutting-down' if state == :shutting_down # EC2 uses a dash

  # If we got Instance objects, we want just the IDs.
  # This method always returns an Array.
  inst_ids = objects_to_instance_ids(inst_ids)

  response = execute_request({}) {
    @ec2.describe_instances(:instance_id => inst_ids)
  }

  # requestId: c16878ac-28e4-4859-9878-ef93af45789c
  # reservationSet: 
  #   item: 
  #   - reservationId: r-e493148d
  #     groupSet: 
  #       item: 
  #       - groupId: default
  #     instancesSet: 
  #       item:
  return nil unless response['reservationSet'].is_a?(Hash)  # No instances 

  resids = []
  instances = {}
  response['reservationSet']['item'].each do |res|      
    resids << res['reservationId']
    groups = res['groupSet']['item'].collect { |g| g['groupId'] }
    # And each reservation can have 1 or more instances
    next unless res['instancesSet'].is_a?(Hash)
    res['instancesSet']['item'].each do |props|
      inst = Instances.from_hash(props)
      next if state && inst.state != state.to_s
      inst.groups = groups
      #puts "STATE: #{inst.state} #{state}"
      instances[inst.awsid] = inst
    end
  end
  
  instances.each_value { |inst| each_inst.call(inst) } if each_inst
  
  instances = nil if instances.empty? # Don't return an empty hash
  instances
end

#list_group(group = nil, state = nil, inst_ids = [], &each_inst) ⇒ Object

  • group is a security group name.

  • state is an optional instance state. If specified, must be one of: running (default), pending, terminated.

  • inst_ids is an Array of instance IDs.



194
195
196
197
198
199
# File 'lib/rudy/aws/ec2/instance.rb', line 194

def list_group(group=nil, state=nil, inst_ids=[], &each_inst)
  instances = list_group_as_hash(group, state, inst_ids, &each_inst)
  instances &&= instances.values
  instances = nil if instances && instances.empty? # Don't return an empty hash
  instances
end

#list_group_as_hash(group = nil, state = nil, inst_ids = [], &each_inst) ⇒ Object

  • group is a security group name.

  • state is an optional instance state. If specified, must be one of: running (default), pending, terminated.

  • inst_ids is an Array of instance IDs.



205
206
207
208
209
210
211
212
213
214
# File 'lib/rudy/aws/ec2/instance.rb', line 205

def list_group_as_hash(group=nil, state=nil, inst_ids=[], &each_inst)
  instances = list_as_hash(state, inst_ids)
  # Remove instances that are not in the specified group
  if instances
    instances = instances.reject { |id,inst| !inst.groups.member?(group) } if group
    instances.each_value { |inst| each_inst.call(inst) } if each_inst
  end
  instances = nil if instances && instances.empty? # Don't return an empty hash
  instances
end

#pending?(inst_ids) ⇒ Boolean

Returns:

  • (Boolean)


333
334
335
# File 'lib/rudy/aws/ec2/instance.rb', line 333

def pending?(inst_ids)
  compare_instance_lists(list(:pending, inst_ids), inst_ids)
end

#restart(inst_ids = [], &each_inst) ⇒ Object

Raises:



129
130
131
132
133
134
135
136
137
# File 'lib/rudy/aws/ec2/instance.rb', line 129

def restart(inst_ids=[], &each_inst)
  instances = list(:running, inst_ids, &each_inst) || []
  raise NoRunningInstances if instances.empty?
  inst_ids = objects_to_instance_ids(inst_ids)
  response = execute_request({}) {
    @ec2.reboot_instances(:instance_id => inst_ids)
  }
  response['return'] == 'true'
end

#restart_group(group, &each_inst) ⇒ Object



169
170
171
172
173
# File 'lib/rudy/aws/ec2/instance.rb', line 169

def restart_group(group, &each_inst)
  instances = list_group(group, :running, &each_inst) || []
  inst_ids = objects_to_instance_ids(instances)
  restart(inst_ids, :skip_check)
end

#running?(inst_ids) ⇒ Boolean

Returns:

  • (Boolean)


330
331
332
# File 'lib/rudy/aws/ec2/instance.rb', line 330

def running?(inst_ids)
  compare_instance_lists(list(:running, inst_ids), inst_ids)
end

#shutting_down?(inst_ids) ⇒ Boolean

Returns:

  • (Boolean)


339
340
341
# File 'lib/rudy/aws/ec2/instance.rb', line 339

def shutting_down?(inst_ids)
  compare_instance_lists(list(:shutting_down, inst_ids), inst_ids)
end

#terminated?(inst_ids) ⇒ Boolean

Returns:

  • (Boolean)


336
337
338
# File 'lib/rudy/aws/ec2/instance.rb', line 336

def terminated?(inst_ids)
  compare_instance_lists(list(:terminated, inst_ids), inst_ids)
end

#unavailable?(inst_ids) ⇒ Boolean

Returns:

  • (Boolean)


343
344
345
346
347
348
349
350
351
# File 'lib/rudy/aws/ec2/instance.rb', line 343

def unavailable?(inst_ids)
  instances = list(:any, inst_ids) || []
  instances.reject! { |inst| 
    (inst.state == "shutting-down" || 
     inst.state == "pending" || 
     inst.state == "terminated") 
  }
  compare_instance_lists(instances, inst_ids)
end

#volumes(id) ⇒ Object



297
298
299
300
301
302
# File 'lib/rudy/aws/ec2/instance.rb', line 297

def volumes(id)
  rvol = Rudy::AWS::EC2::Volumes.new
  rvol.ec2 = @ec2 
  rvol.list || []
  list.select { |v| v.attached? && v.instid === id }
end