Class: Awsum::Ec2

Inherits:
Object show all
Includes:
Requestable
Defined in:
lib/awsum/ec2.rb,
lib/awsum/ec2/tag.rb,
lib/awsum/ec2/image.rb,
lib/awsum/ec2/state.rb,
lib/awsum/ec2/region.rb,
lib/awsum/ec2/volume.rb,
lib/awsum/ec2/address.rb,
lib/awsum/ec2/keypair.rb,
lib/awsum/ec2/instance.rb,
lib/awsum/ec2/snapshot.rb,
lib/awsum/ec2/security_group.rb,
lib/awsum/ec2/availability_zone.rb,
lib/awsum/ec2/reserved_instance.rb,
lib/awsum/ec2/parsers/tag_parser.rb,
lib/awsum/ec2/parsers/image_parser.rb,
lib/awsum/ec2/parsers/region_parser.rb,
lib/awsum/ec2/parsers/volume_parser.rb,
lib/awsum/ec2/parsers/address_parser.rb,
lib/awsum/ec2/parsers/keypair_parser.rb,
lib/awsum/ec2/parsers/instance_parser.rb,
lib/awsum/ec2/parsers/snapshot_parser.rb,
lib/awsum/ec2/reserved_instances_offering.rb,
lib/awsum/ec2/parsers/register_image_parser.rb,
lib/awsum/ec2/parsers/security_group_parser.rb,
lib/awsum/ec2/parsers/availability_zone_parser.rb,
lib/awsum/ec2/parsers/reserved_instance_parser.rb,
lib/awsum/ec2/parsers/reserved_instances_offering_parser.rb,
lib/awsum/ec2/parsers/purchase_reserved_instances_offering_parser.rb

Overview

Handles all interaction with Amazon EC2

Getting Started

Create an Awsum::Ec2 object and begin calling methods on it.

require 'rubygems'
require 'awsum'
ec2 = Awsum::Ec2.new('your access id', 'your secret key')
images = ec2.my_images
...

All calls to EC2 can be done directly in this class, or through a more object oriented way through the various returned classes

Examples

ec2.image('ami-ABCDEF').run

ec2.instance('i-123456789').volumes.each do |vol|
  vol.create_snapsot
end

ec2.regions.each do |region|
  region.use
    images.each do |img|
      puts "#{img.id} - #{region.name}"
    end
  end
end

Errors

All methods will raise an Awsum::Error if an error is returned from Amazon

Missing Methods

  • ConfirmProductInstance

  • ModifyImageAttribute

  • DescribeImageAttribute

  • ResetImageAttribute

If you need any of this functionality, please consider getting involved and help complete this library.

Defined Under Namespace

Classes: Address, AddressParser, AvailabilityZone, AvailabilityZoneParser, Image, ImageParser, Instance, InstanceParser, KeyPair, KeyPairParser, PurchaseReservedInstancesOfferingParser, Region, RegionParser, RegisterImageParser, ReservedInstance, ReservedInstanceParser, ReservedInstancesOffering, ReservedInstancesOfferingParser, SecurityGroup, SecurityGroupParser, Snapshot, SnapshotParser, State, Tag, TagParser, Volume, VolumeParser

Instance Method Summary collapse

Constructor Details

#initialize(access_key = nil, secret_key = nil) ⇒ Ec2

Create an new ec2 instance

The access_key and secret_key are both required to do any meaningful work.

If you want to get these keys from environment variables, you can do that in your code as follows:

ec2 = Awsum::Ec2.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])


62
63
64
65
# File 'lib/awsum/ec2.rb', line 62

def initialize(access_key = nil, secret_key = nil)
  @access_key = access_key
  @secret_key = secret_key
end

Instance Method Details

#address(public_ip) ⇒ Object

Get the Address with a specific public ip



466
467
468
# File 'lib/awsum/ec2.rb', line 466

def address(public_ip)
  addresses(public_ip)[0]
end

#addresses(*public_ips) ⇒ Object

List Addresses



453
454
455
456
457
458
459
460
461
462
463
# File 'lib/awsum/ec2.rb', line 453

def addresses(*public_ips)
  action = 'DescribeAddresses'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(public_ips, 'PublicIp'))

  response = send_query_request(params)
  parser = Awsum::Ec2::AddressParser.new(self)
  parser.parse(response.body)
end

#allocate_addressObject

Allocate Address

Will aquire an elastic ip address for use with your account



473
474
475
476
477
478
479
480
481
482
# File 'lib/awsum/ec2.rb', line 473

def allocate_address
  action = 'AllocateAddress'
  params = {
    'Action' => action
  }

  response = send_query_request(params)
  parser = Awsum::Ec2::AddressParser.new(self)
  parser.parse(response.body)[0]
end

#associate_address(instance_id, public_ip) ⇒ Object

Associate Address

Will link an allocated elastic ip address to an Instance

NOTE: If the ip address is already associated with another instance, it will be associated with the new instance.

You can run this command more than once and it will not return an error.



491
492
493
494
495
496
497
498
499
500
501
# File 'lib/awsum/ec2.rb', line 491

def associate_address(instance_id, public_ip)
  action = 'AssociateAddress'
  params = {
    'Action'     => action,
    'InstanceId' => instance_id,
    'PublicIp'   => public_ip
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#attach_volume(volume_id, instance_id, device = '/dev/sdh') ⇒ Object

Attach a volume to an instance



317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/awsum/ec2.rb', line 317

def attach_volume(volume_id, instance_id, device = '/dev/sdh')
  action = 'AttachVolume'
  params = {
    'Action'     => action,
    'VolumeId'   => volume_id,
    'InstanceId' => instance_id,
    'Device'     => device
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#authorize_security_group_ingress(group_name, arguments) ⇒ Object

Authorize access on a specific security group

Usage

User/Group access

ec2.authorize_security_group_ingress(‘security_group’, => :tcp, :from_port => 80, :to_port => 80, :groups => [{:group_name => :authorized_group]})

CIDR IP access

ec2.authorize_security_group_ingress(‘security_group’, => :tcp, :from_port => 80, :to_port => 80, :ip_ranges => [{:cidr_ip => ‘0.0.0.0/0’]})

Raises:

  • (ArgumentError)


647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/awsum/ec2.rb', line 647

def authorize_security_group_ingress(group_name, arguments)
  raise ArgumentError.new('Can only authorize user/group or CIDR IP, not both') if [arguments].flatten.detect{|a| a.has_key?(:ip_ranges) && a.has_key?(:groups)}
  raise ArgumentError.new('ip_protocol can only be one of tcp, udp or icmp') if [arguments].flatten.detect{|a| !%w(tcp udp icmp).detect{|p| p == a[:ip_protocol].to_s } }

  action = 'AuthorizeSecurityGroupIngress'
  params = {
    'Action'    => action,
    'GroupName' => group_name
  }
  params.merge!(array_to_params(arguments, 'IpPermissions'))

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#availability_zones(*zone_names) ⇒ Object

List all AvailabilityZone(s)



417
418
419
420
421
422
423
424
425
426
427
# File 'lib/awsum/ec2.rb', line 417

def availability_zones(*zone_names)
  action = 'DescribeAvailabilityZones'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(zone_names, 'ZoneName'))

  response = send_query_request(params)
  parser = Awsum::Ec2::AvailabilityZoneParser.new(self)
  parser.parse(response.body)
end

#create_key_pair(key_name) ⇒ Object

Create a new KeyPair



573
574
575
576
577
578
579
580
581
582
583
# File 'lib/awsum/ec2.rb', line 573

def create_key_pair(key_name)
  action = 'CreateKeyPair'
  params = {
    'Action'  => action,
    'KeyName' => key_name
  }

  response = send_query_request(params)
  parser = Awsum::Ec2::KeyPairParser.new(self)
  parser.parse(response.body)[0]
end

#create_security_group(name, description) ⇒ Object

Create a new SecurityGroup



616
617
618
619
620
621
622
623
624
625
626
# File 'lib/awsum/ec2.rb', line 616

def create_security_group(name, description)
  action = 'CreateSecurityGroup'
  params = {
    'Action'           => action,
    'GroupName'        => name,
    'GroupDescription' => description
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#create_snapshot(volume_id, options = {}) ⇒ Object

Create a Snapshot of a Volume

Options:

:description => A description for the stapshot :tags => A hash of tags to be associated with the snapshot



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/awsum/ec2.rb', line 367

def create_snapshot(volume_id, options = {})
  action = 'CreateSnapshot'
  params = {
    'Action'   => action,
    'VolumeId' => volume_id
  }
  params['Description'] = options[:description] unless options[:description].blank?

  response = send_query_request(params)
  parser = Awsum::Ec2::SnapshotParser.new(self)
  snapshot = parser.parse(response.body)[0]
  if options[:tags] && options[:tags].size > 0
    create_tags snapshot.id, options[:tags]
  end
  snapshot
end

#create_tags(resource_ids, tags) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
# File 'lib/awsum/ec2.rb', line 254

def create_tags(resource_ids, tags)
  action = 'CreateTags'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(resource_ids, 'ResourceId'))
  params.merge!(parse_tag_keys(tags))

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#create_volume(availability_zone, options = {}) ⇒ Object

Create a new volume

Options:

  • :size - The size of the volume to be created (in GB) (NOTE: Required if you are not creating from a snapshot)

  • :snapshot_id - The snapshot id from which to create the volume

Raises:

  • (ArgumentError)


296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/awsum/ec2.rb', line 296

def create_volume(availability_zone, options = {})
  raise ArgumentError.new('You must specify a size if not creating a volume from a snapshot') if options[:snapshot_id].blank? && options[:size].blank?

  action = 'CreateVolume'
  params = {
    'Action'           => action,
    'AvailabilityZone' => availability_zone
  }
  params['Size'] = options[:size] unless options[:size].blank?
  params['SnapshotId'] = options[:snapshot_id] unless options[:snapshot_id].blank?

  response = send_query_request(params)
  parser = Awsum::Ec2::VolumeParser.new(self)
  volume = parser.parse(response.body)[0]
  if options[:tags] && options[:tags].size > 0
    create_tags volume.id, options[:tags]
  end
  volume
end

#delete_key_pair(key_name) ⇒ Object

Delete a KeyPair



586
587
588
589
590
591
592
593
594
595
# File 'lib/awsum/ec2.rb', line 586

def delete_key_pair(key_name)
  action = 'DeleteKeyPair'
  params = {
    'Action'  => action,
    'KeyName' => key_name
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#delete_security_group(group_name) ⇒ Object

Delete a SecurityGroup



629
630
631
632
633
634
635
636
637
638
# File 'lib/awsum/ec2.rb', line 629

def delete_security_group(group_name)
  action = 'DeleteSecurityGroup'
  params = {
    'Action'  => action,
    'GroupName' => group_name
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#delete_snapshot(snapshot_id) ⇒ Object

Delete a Snapshot



405
406
407
408
409
410
411
412
413
414
# File 'lib/awsum/ec2.rb', line 405

def delete_snapshot(snapshot_id)
  action = 'DeleteSnapshot'
  params = {
    'Action'     => action,
    'SnapshotId' => snapshot_id
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#delete_volume(volume_id) ⇒ Object

Delete a volume



351
352
353
354
355
356
357
358
359
360
# File 'lib/awsum/ec2.rb', line 351

def delete_volume(volume_id)
  action = 'DeleteVolume'
  params = {
    'Action'     => action,
    'VolumeId'   => volume_id
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#deregister_image(image_id) ⇒ Object

Deregister an Image. Once deregistered, you can no longer launch the Image



116
117
118
119
120
121
122
123
124
125
# File 'lib/awsum/ec2.rb', line 116

def deregister_image(image_id)
  action = 'DeregisterImage'
  params = {
      'Action'  => action,
      'ImageId' => image_id
    }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#detach_volume(volume_id, options = {}) ⇒ Object

Detach a volume from an instance

Options

  • :instance_id - The ID of the instance from which the volume will detach

  • :device - The device name

  • :force - Whether to force the detachment. NOTE: If forced you may have data corruption issues.



336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/awsum/ec2.rb', line 336

def detach_volume(volume_id, options = {})
  action = 'DetachVolume'
  params = {
    'Action'     => action,
    'VolumeId'   => volume_id
  }
  params['InstanceId'] = options[:instance_id] unless options[:instance_id].blank?
  params['Device'] = options[:device] unless options[:device].blank?
  params['Force'] = options[:force] unless options[:force].blank?

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#disassociate_address(public_ip) ⇒ Object

Disassociate Address

Will disassociate an allocated elastic ip address from the Instance it’s allocated to

NOTE: You can run this command more than once and it will not return an error.



508
509
510
511
512
513
514
515
516
517
# File 'lib/awsum/ec2.rb', line 508

def disassociate_address(public_ip)
  action = 'DisassociateAddress'
  params = {
    'Action'     => action,
    'PublicIp'   => public_ip
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#hostObject

The host to make all requests against



755
756
757
# File 'lib/awsum/ec2.rb', line 755

def host
  @host ||= 'ec2.amazonaws.com'
end

#host=(host) ⇒ Object



759
760
761
# File 'lib/awsum/ec2.rb', line 759

def host=(host)
  @host = host
end

#image(image_id) ⇒ Object

Retrieve a single Image



98
99
100
# File 'lib/awsum/ec2.rb', line 98

def image(image_id)
  images(:image_ids => [image_id])[0]
end

#images(options = {}) ⇒ Object

Retrieve a list of available Images

Options:

  • :image_ids - array of Image id’s, default: []

  • :owners - array of owner id’s, default: []

  • :executable_by - array of user id’s who have executable permission, default: []

  • :filter - hash of filters (e.g. :filter => => ‘i386’)

  • :tags - hash of tags (e.g. :tags => => ‘Test’)



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/awsum/ec2.rb', line 75

def images(options = {})
  options = {:image_ids => [], :owners => [], :executable_by => []}.merge(options)
  action = 'DescribeImages'
  params = {
      'Action' => action
    }
  #Add options
  params.merge!(array_to_params(options[:image_ids], "ImageId"))
  params.merge!(array_to_params(options[:owners], "Owner"))
  params.merge!(array_to_params(options[:executable_by], "ExecutableBy"))
  params.merge!(parse_filters(options[:filter], options[:tags]))

  response = send_query_request(params)
  parser = Awsum::Ec2::ImageParser.new(self)
  parser.parse(response.body)
end

#instance(instance_id) ⇒ Object

Retrieve the information on a single Instance



196
197
198
# File 'lib/awsum/ec2.rb', line 196

def instance(instance_id)
  instances([instance_id])[0]
end

#instances(*instance_ids) ⇒ Object

Retrieve the information on a number of Instance(s)

Options:

  • :filter - hash of filters (e.g. :filter => => ‘i386’)

  • :tags - hash of tags (e.g. :tags => => ‘Test’)



181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/awsum/ec2.rb', line 181

def instances(*instance_ids)
  options = instance_ids[-1].respond_to?(:keys) ? instance_ids.pop : {}
  action = 'DescribeInstances'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(instance_ids, 'InstanceId'))
  params.merge!(parse_filters(options[:filter], options[:tags]))

  response = send_query_request(params)
  parser = Awsum::Ec2::InstanceParser.new(self)
  parser.parse(response.body)
end

#key_pair(key_name) ⇒ Object

Get a single KeyPair



568
569
570
# File 'lib/awsum/ec2.rb', line 568

def key_pair(key_name)
  key_pairs(key_name)[0]
end

#key_pairs(*key_names) ⇒ Object

List KeyPair(s)



555
556
557
558
559
560
561
562
563
564
565
# File 'lib/awsum/ec2.rb', line 555

def key_pairs(*key_names)
  action = 'DescribeKeyPairs'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(key_names, 'KeyName'))

  response = send_query_request(params)
  parser = Awsum::Ec2::KeyPairParser.new(self)
  parser.parse(response.body)
end

#meObject

Retrieves the currently running Instance This should only be run on a running EC2 instance



202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/awsum/ec2.rb', line 202

def me
  require 'open-uri'
  begin
    instance_id = open('http://169.254.169.254/latest/meta-data/instance-id').read
    availability_zone = open('http://169.254.169.254/latest/meta-data/placement/availability-zone').read
    #NOTE: This relies on the assumption that the region code is
    #      always one less character than the availability zone
    region_code = availability_zone.chop
    region(region_code).use
    instance instance_id
  rescue OpenURI::HTTPError => e
    nil
  end
end

#my_images(options = {}) ⇒ Object

Retrieve all Image(s) owned by you



93
94
95
# File 'lib/awsum/ec2.rb', line 93

def my_images(options = {})
  images options.merge(:owners => 'self')
end

#purchase_reserved_instances_offering(reserved_instances_offering_id, instance_count = 1) ⇒ Object

Purchase reserved instances

Options:

  • :reserved_instances_offering_id - A single reserved instance offering id

  • :instance_count - A number of reserved instances to purchase

Example

ec2.purchase_reserved_instances_offering('reservation-123456', 1)


723
724
725
726
727
728
729
730
731
732
733
734
# File 'lib/awsum/ec2.rb', line 723

def purchase_reserved_instances_offering(reserved_instances_offering_id, instance_count = 1)
  action = 'PurchaseReservedInstancesOffering'
  params = {
    'Action'        => action,
  }
  params['ReservedInstancesOfferingId'] = reserved_instances_offering_id
  params['InstanceCount']               = instance_count

  response = send_query_request(params)
  parser = Awsum::Ec2::PurchaseReservedInstancesOfferingParser.new(self)
  result = parser.parse(response.body)
end

#region(region_name, &block) ⇒ Object

List a Region



443
444
445
446
447
448
449
450
# File 'lib/awsum/ec2.rb', line 443

def region(region_name, &block)
  region = regions(region_name)[0]
  if block_given?
    region.use(&block)
  else
    region
  end
end

#regions(*region_names) ⇒ Object

List all Region(s)



430
431
432
433
434
435
436
437
438
439
440
# File 'lib/awsum/ec2.rb', line 430

def regions(*region_names)
  action = 'DescribeRegions'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(region_names, 'RegionName'))

  response = send_query_request(params)
  parser = Awsum::Ec2::RegionParser.new(self)
  parser.parse(response.body)
end

#register_image(image_location) ⇒ Object

Register an Image



103
104
105
106
107
108
109
110
111
112
113
# File 'lib/awsum/ec2.rb', line 103

def register_image(image_location)
  action = 'RegisterImage'
  params = {
      'Action'        => action,
      'ImageLocation' => image_location
    }

  response = send_query_request(params)
  parser = Awsum::Ec2::RegisterImageParser.new(self)
  parser.parse(response.body)
end

#release_address(public_ip) ⇒ Object

Releases an associated Address

NOTE: This is not a direct call to the Amazon web service. This is a safe operation that will first check to see if the address is allocated to an instance and fail if it is To ensure an address is released whether associated or not, use #release_address!



523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/awsum/ec2.rb', line 523

def release_address(public_ip)
  address = address(public_ip)

  if address.instance_id.nil?
    action = 'ReleaseAddress'
    params = {
      'Action'   => action,
      'PublicIp' => public_ip
    }

    response = send_query_request(params)
    response.is_a?(Net::HTTPSuccess)
  else
    raise 'Address is currently allocated' #FIXME: Add a proper Awsum error here
  end
end

#release_address!(public_ip) ⇒ Object

Releases an associated Address

NOTE: This will disassociate an address automatically if it is associated with an instance



543
544
545
546
547
548
549
550
551
552
# File 'lib/awsum/ec2.rb', line 543

def release_address!(public_ip)
  action = 'ReleaseAddress'
  params = {
    'Action'   => action,
    'PublicIp' => public_ip
  }

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#reserved_instance(reserved_instance_id) ⇒ Object

Retrieve a single reserved instance by id



749
750
751
# File 'lib/awsum/ec2.rb', line 749

def reserved_instance(reserved_instance_id)
  reserved_instances(reserved_instance_id)[0]
end

#reserved_instances(*reserved_instances_ids) ⇒ Object



736
737
738
739
740
741
742
743
744
745
746
# File 'lib/awsum/ec2.rb', line 736

def reserved_instances(*reserved_instances_ids)
  action = 'DescribeReservedInstances'
  params = {
    'Action'        => action
  }
  params.merge!(array_to_params(reserved_instances_ids, 'ReservedInstanceId'))

  response = send_query_request(params)
  parser = Awsum::Ec2::ReservedInstanceParser.new(self)
  parser.parse(response.body)
end

#reserved_instances_offering(id) ⇒ Object

Get a single reserved instances offering by id



711
712
713
# File 'lib/awsum/ec2.rb', line 711

def reserved_instances_offering(id)
  reserved_instances_offerings(:reserved_instances_offering_ids => id)[0]
end

#reserved_instances_offerings(options = {}) ⇒ Object

List all reserved instance offerings that are available for purchase

Options:

  • :reserved_instances_offering_ids - Display the reserved instance offerings with the specified ids. Can be an individual id or an array of ids

  • :instance_type - Display available reserved instance offerings of the specific instance type, can be one of [m1.small, m1.large, m1.xlarge, c1.medium, c1.xlarge], default is all

  • :availability_zone - Display the reserved instance offerings within the specified availability zone

  • :product_description - Display the reserved instance offerings with the specified product description

Example

#To get all offerings for m1.small instances in availability zone us-east-1a
ec2.reserved_instances_offerings(:instance_type => 'm1.small', :availability_zone => 'us-east-1a')


695
696
697
698
699
700
701
702
703
704
705
706
707
708
# File 'lib/awsum/ec2.rb', line 695

def reserved_instances_offerings(options = {})
  action = 'DescribeReservedInstancesOfferings'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(options[:reserved_instances_offering_ids], 'ReservedInstancesOfferingId')) if options[:reserved_instances_offering_ids]
  params['InstanceType'] = options[:instance_type] if options[:instance_type]
  params['AvailabilityZone'] = options[:availability_zone] if options[:availability_zone]
  params['ProductDescription'] = options[:product_description] if options[:product_description]

  response = send_query_request(params)
  parser = Awsum::Ec2::ReservedInstancesOfferingParser.new(self)
  parser.parse(response.body)
end

#revoke_security_group_ingress(group_name, arguments) ⇒ Object

Revoke access on a specific SecurityGroup

Usage

User/Group access

ec2.revoke_security_group_ingress(‘security_group’, => :tcp, :from_port => 80, :to_port => 80, :groups => [{:group_name => :revoked_group]})

CIDR IP access

ec2.revoke_security_group_ingress(‘security_group’, => :tcp, :from_port => 80, :to_port => 80, :ip_ranges => [{:cidr_ip => ‘0.0.0.0/0’]})

Raises:

  • (ArgumentError)


669
670
671
672
673
674
675
676
677
678
679
680
681
682
# File 'lib/awsum/ec2.rb', line 669

def revoke_security_group_ingress(group_name, arguments)
  raise ArgumentError.new('Can only authorize user/group or CIDR IP, not both') if [arguments].flatten.detect{|a| a.has_key?(:ip_ranges) && a.has_key?(:groups)}
  raise ArgumentError.new('ip_protocol can only be one of tcp, udp or icmp') if [arguments].flatten.detect{|a| !%w(tcp udp icmp).detect{|p| p == a[:ip_protocol].to_s } }

  action = 'RevokeSecurityGroupIngress'
  params = {
    'Action'    => action,
    'GroupName' => group_name
  }
  params.merge!(array_to_params(arguments, 'IpPermissions'))

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#run_instances(image_id, options = {}) ⇒ Object Also known as: launch_instances

Launch an ec2 Instance

Options:

  • :min - The minimum number of instances to launch. Default: 1

  • :max - The maximum number of instances to launch. Default: 1

  • :key_name - The name of the key pair with which to launch instances

  • :security_groups - The names of security groups to associate launched instances with

  • :user_data - User data made available to instances (Note: Must be 16K or less, will be base64 encoded by Awsum)

  • :instance_type - The size of the instances to launch, can be one of [m1.small, m1.large, m1.xlarge, c1.medium, c1.xlarge], default is m1.small

  • :availability_zone - The name of the availability zone to launch this Instance in

  • :kernel_id - The ID of the kernel with which to launch instances

  • :ramdisk_id - The ID of the RAM disk with which to launch instances

  • :block_device_map - A ‘hash’ of mappings. E.g. => ‘sdb’



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
168
169
170
171
172
173
# File 'lib/awsum/ec2.rb', line 140

def run_instances(image_id, options = {})
  options = {:min => 1, :max => 1}.merge(options)
  action = 'RunInstances'
  params = {
    'Action'                     => action,
    'ImageId'                    => image_id,
    'MinCount'                   => options[:min],
    'MaxCount'                   => options[:max],
    'KeyName'                    => options[:key_name],
    'UserData'                   => options[:user_data].nil? ? nil : Base64::encode64(options[:user_data]).gsub(/\n/, ''),
    'InstanceType'               => options[:instance_type],
    'Placement.AvailabilityZone' => options[:availability_zone],
    'KernelId'                   => options[:kernel_id],
    'RamdiskId'                  => options[:ramdisk_id]
  }
  if options[:block_device_map].respond_to?(:keys)
    map = options[:block_device_map]
    map.keys.each_with_index do |key, i|
      params["BlockDeviceMapping.#{i+1}.VirtualName"] = key
      params["BlockDeviceMapping.#{i+1}.DeviceName"] = map[key]
    end
  else
    raise ArgumentError.new("options[:block_device_map] - must be a key => value map") unless options[:block_device_map].nil?
  end
  params.merge!(array_to_params(options[:security_groups], "SecurityGroup"))

  response = send_query_request(params)
  parser = Awsum::Ec2::InstanceParser.new(self)
  instances = parser.parse(response.body)
  if options[:tags] && options[:tags].size > 0
    create_tags instances.map{|i| i.id}, options[:tags]
  end
  instances
end

#security_group(group_name) ⇒ Object

Get a single SecurityGroup



611
612
613
# File 'lib/awsum/ec2.rb', line 611

def security_group(group_name)
  security_groups(group_name)[0]
end

#security_groups(*group_names) ⇒ Object

List SecurityGroup(s)



598
599
600
601
602
603
604
605
606
607
608
# File 'lib/awsum/ec2.rb', line 598

def security_groups(*group_names)
  action = 'DescribeSecurityGroups'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(group_names, 'GroupName'))

  response = send_query_request(params)
  parser = Awsum::Ec2::SecurityGroupParser.new(self)
  parser.parse(response.body)
end

#snapshot(snapshot_id) ⇒ Object

Get the information about a Snapshot



400
401
402
# File 'lib/awsum/ec2.rb', line 400

def snapshot(snapshot_id)
  snapshots(snapshot_id)[0]
end

#snapshots(*snapshot_ids) ⇒ Object

List Snapshot(s)



385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/awsum/ec2.rb', line 385

def snapshots(*snapshot_ids)
  options = snapshot_ids[-1].respond_to?(:keys) ? snapshot_ids.pop : {}
  action = 'DescribeSnapshots'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(snapshot_ids, 'SnapshotId'))
  params.merge!(parse_filters(options[:filter], options[:tags]))

  response = send_query_request(params)
  parser = Awsum::Ec2::SnapshotParser.new(self)
  parser.parse(response.body)
end

#tags(filter = {}) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
# File 'lib/awsum/ec2.rb', line 242

def tags(filter = {})
  action = 'DescribeTags'
  params = {
    'Action' => action
  }
  params.merge!(parse_filters(filter))

  response = send_query_request(params)
  parser = Awsum::Ec2::TagParser.new(self)
  parser.parse(response.body)
end

#terminate_instances(*instance_ids) ⇒ Object

Terminates the Instance(s)

Returns true if the terminations succeeds, false otherwise



231
232
233
234
235
236
237
238
239
240
# File 'lib/awsum/ec2.rb', line 231

def terminate_instances(*instance_ids)
  action = 'TerminateInstances'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(instance_ids, 'InstanceId'))

  response = send_query_request(params)
  response.is_a?(Net::HTTPSuccess)
end

#user_dataObject

Retreives the user-data supplied when starting the currently running Instance This should only be run on a running EC2 instance



219
220
221
222
223
224
225
226
# File 'lib/awsum/ec2.rb', line 219

def user_data
  require 'open-uri'
  begin
    open('http://169.254.169.254/latest/user-data').read
  rescue OpenURI::HTTPError => e
    nil
  end
end

#volume(volume_id) ⇒ Object

Retreive information on a Volume



286
287
288
# File 'lib/awsum/ec2.rb', line 286

def volume(volume_id)
  volumes(volume_id)[0]
end

#volumes(*volume_ids) ⇒ Object

Retrieve the information on a number of Volume(s)

Options:

  • :filter - hash of filters (e.g. :filter => => ‘attached’)

  • :tags - hash of tags (e.g. :tags => => ‘Test’)



271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/awsum/ec2.rb', line 271

def volumes(*volume_ids)
  options = volume_ids[-1].respond_to?(:keys) ? volume_ids.pop : {}
  action = 'DescribeVolumes'
  params = {
    'Action' => action
  }
  params.merge!(array_to_params(volume_ids, 'VolumeId'))
  params.merge!(parse_filters(options[:filter], options[:tags]))

  response = send_query_request(params)
  parser = Awsum::Ec2::VolumeParser.new(self)
  parser.parse(response.body)
end