Class RightAws::Ec2
In: lib/ec2/right_ec2.rb
Parent: RightAwsBase

RightAWS::EC2 — RightScale Amazon EC2 interface

The RightAws::EC2 class provides a complete interface to Amazon‘s Elastic Compute Cloud service, as well as the associated EBS (Elastic Block Store). For explanations of the semantics of each call, please refer to Amazon‘s documentation at developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=87

Examples:

Create an EC2 interface handle:

  @ec2   = RightAws::Ec2.new(aws_access_key_id,
                              aws_secret_access_key)

Create a new SSH key pair:

 @key   = 'right_ec2_awesome_test_key'
 new_key = @ec2.create_key_pair(@key)
 keys = @ec2.describe_key_pairs

Create a security group:

 @group = 'right_ec2_awesome_test_security_group'
 @ec2.create_security_group(@group,'My awesome test group')
 group = @ec2.describe_security_groups([@group])[0]

Configure a security group:

 @ec2.authorize_security_group_named_ingress(@group, account_number, 'default')
 @ec2.authorize_security_group_IP_ingress(@group, 80,80,'udp','192.168.1.0/8')

Describe the available images:

 images = @ec2.describe_images

Launch an instance:

 ec2.run_instances('ami-9a9e7bf3', 1, 1, ['default'], @key, 'SomeImportantUserData', 'public')

Describe running instances:

 @ec2.describe_instances

Error handling: all operations raise an RightAws::AwsError in case of problems. Note that transient errors are automatically retried.

Methods

Included Modules

RightAwsBaseInterface

Constants

API_VERSION = "2008-12-01"   Amazon EC2 API version being used
DEFAULT_HOST = "ec2.amazonaws.com"
DEFAULT_PATH = '/'
DEFAULT_PROTOCOL = 'https'
DEFAULT_PORT = 443
DEFAULT_ADDRESSING_TYPE = 'public'   Default addressing type (public=NAT, direct=no-NAT) used when launching instances.
DNS_ADDRESSING_SET = ['public','direct']
DEFAULT_INSTANCE_TYPE = 'm1.small'   Amazon EC2 Instance Types : www.amazon.com/b?ie=UTF8&node=370375011 Default EC2 instance type (platform)
INSTANCE_TYPES = ['m1.small','c1.medium','m1.large','m1.xlarge','c1.xlarge']

Public Class methods

Create a new handle to an EC2 account. All handles share the same per process or per thread HTTP connection to Amazon EC2. Each handle is for a specific account. The params have the following options:

  • :endpoint_url a fully qualified url to Amazon API endpoint (this overwrites: :server, :port, :service, :protocol and :region). Example: ‘eu-west-1.ec2.amazonaws.com/’
  • :server: EC2 service host, default: DEFAULT_HOST
  • :region: EC2 region (North America by default)
  • :port: EC2 service port, default: DEFAULT_PORT
  • :protocol: ‘http’ or ‘https’, default: DEFAULT_PROTOCOL
  • :multi_thread: true=HTTP connection per thread, false=per process
  • :logger: for log messages, default: RAILS_DEFAULT_LOGGER else STDOUT
  • :signature_version: The signature version : ‘0’ or ‘1’(default)
  • :cache: true/false: caching for: ec2_describe_images, describe_instances,

describe_images_by_owner, describe_images_by_executable_by, describe_availability_zones, describe_security_groups, describe_key_pairs, describe_addresses, describe_volumes, describe_snapshots methods, default: false.

Public Instance methods

Acquire a new elastic IP address for use with your account. Returns allocated IP address or an exception.

 ec2.allocate_address #=> '75.101.154.140'

Associate an elastic IP address with an instance. Returns true or an exception.

 ec2.associate_address('i-d630cbbf', '75.101.154.140') #=> true

Attach the specified EBS volume to a specified instance, exposing the volume using the specified device name.

 ec2.attach_volume('vol-898a6fe0', 'i-7c905415', '/dev/sdh') #=>
   { :aws_instance_id => "i-7c905415",
     :aws_device      => "/dev/sdh",
     :aws_status      => "attaching",
     :aws_attached_at => "2008-03-28T14:14:39.000Z",
     :aws_id          => "vol-898a6fe0" }

Add permission to a security group. Returns true or an exception. protocol is one of :’tcp’|’udp’|’icmp’.

 ec2.authorize_security_group_IP_ingress('my_awesome_group', 80, 82, 'udp', '192.168.1.0/8') #=> true
 ec2.authorize_security_group_IP_ingress('my_awesome_group', -1, -1, 'icmp') #=> true

Authorize named ingress for security group. Allows instances that are member of someone else‘s security group to open connections to instances in my group.

 ec2.authorize_security_group_named_ingress('my_awesome_group', '7011-0219-8268', 'their_group_name') #=> true

Bundle a Windows image. Internally, it queues the bundling task and shuts down the instance. It then takes a snapshot of the Windows volume bundles it, and uploads it to S3. After bundling completes, Rightaws::Ec2#register_image may be used to register the new Windows AMI for subsequent launches.

  ec2.bundle_instance('i-e3e24e8a', 'my-awesome-bucket', 'my-win-image-1') #=>
   [{:aws_update_time => "2008-10-16T13:58:25.000Z",
     :s3_bucket       => "kd-win-1",
     :s3_prefix       => "win2pr",
     :aws_state       => "pending",
     :aws_id          => "bun-26a7424f",
     :aws_instance_id => "i-878a25ee",
     :aws_start_time  => "2008-10-16T13:58:02.000Z"}]

Cancel an in‐progress or pending bundle task by id.

 ec2.cancel_bundle_task('bun-73a7421a') #=>
  [{:s3_bucket         => "my-awesome-bucket"
    :aws_id            => "bun-0fa70206",
    :s3_prefix         => "win02",
    :aws_start_time    => "2008-10-14T13:00:29.000Z",
    :aws_error_message => "User has requested bundling operation cancellation",
    :aws_state         => "failed",
    :aws_update_time   => "2008-10-14T13:01:31.000Z",
    :aws_error_code    => "Client.Cancelled",
    :aws_instance_id   => "i-e3e24e8a"}

Return the product code attached to instance or nil otherwise.

 ec2.confirm_product_instance('ami-e444444d','12345678') #=> nil
 ec2.confirm_product_instance('ami-e444444d','00001111') #=> "000000000888"

Create new SSH key. Returns a hash of the key‘s data or an exception.

 ec2.create_key_pair('my_awesome_key') #=>
   {:aws_key_name    => "my_awesome_key",
    :aws_fingerprint => "01:02:03:f4:25:e6:97:e8:9b:02:1a:26:32:4e:58:6b:7a:8c:9f:03",
    :aws_material    => "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAK...Q8MDrCbuQ=\n-----END RSA PRIVATE KEY-----"}

Create new Security Group. Returns true or an exception.

 ec2.create_security_group('default-1',"Default allowing SSH, HTTP, and HTTPS ingress") #=> true

Create a snapshot of specified volume.

 ec2.create_snapshot('vol-898a6fe0') #=>
     {:aws_volume_id  => "vol-fd9f7a94",
      :aws_started_at => Tue Jun 24 18:40:40 UTC 2008,
      :aws_progress   => "",
      :aws_status     => "pending",
      :aws_id         => "snap-d56783bc"}

Create new EBS volume based on previously created snapshot. Size in Gigabytes.

 ec2.create_volume('snap-000000', 10, zone) #=>
     {:snapshot_id    => "snap-e21df98b",
      :aws_status     => "creating",
      :aws_id         => "vol-fc9f7a95",
      :zone           => "merlot",
      :aws_created_at => Tue Jun 24 18:13:32 UTC 2008,
      :aws_size       => 94}

Delete a key pair. Returns true or an exception.

 ec2.delete_key_pair('my_awesome_key') #=> true

Remove Security Group. Returns true or an exception.

 ec2.delete_security_group('default-1') #=> true

Delete the specified snapshot.

 ec2.delete_snapshot('snap-55a5403c') #=> true

Delete the specified EBS volume. This does not deletes any snapshots created from this volume.

 ec2.delete_volume('vol-b48a6fdd') #=> true

Deregister image at Amazon. Returns true or an exception.

 ec2.deregister_image('ami-e444444d') #=> true

List elastic IP addresses assigned to your account. Returns an array of 2 keys (:instance_id and :public_ip) hashes:

 ec2.describe_addresses  #=> [{:instance_id=>"i-d630cbbf", :public_ip=>"75.101.154.140"},
                              {:instance_id=>nil, :public_ip=>"75.101.154.141"}]

 ec2.describe_addresses('75.101.154.140') #=> [{:instance_id=>"i-d630cbbf", :public_ip=>"75.101.154.140"}]

Describes availability zones that are currently available to the account and their states. Returns an array of 2 keys (:zone_name and :zone_state) hashes:

 ec2.describe_availability_zones  #=> [{:region_name=>"us-east-1",
                                        :zone_name=>"us-east-1a",
                                        :zone_state=>"available"}, ... ]

 ec2.describe_availability_zones('us-east-1c') #=> [{:region_name=>"us-east-1",
                                                     :zone_state=>"available",
                                                     :zone_name=>"us-east-1c"}]

Describe the status of the Windows AMI bundlings. If list is omitted the returns the whole list of tasks.

 ec2.describe_bundle_tasks(['bun-4fa74226']) #=>
   [{:s3_bucket         => "my-awesome-bucket"
     :aws_id            => "bun-0fa70206",
     :s3_prefix         => "win1pr",
     :aws_start_time    => "2008-10-14T16:27:57.000Z",
     :aws_update_time   => "2008-10-14T16:37:10.000Z",
     :aws_error_code    => "Client.S3Error",
     :aws_error_message =>
      "AccessDenied(403)- Invalid according to Policy: Policy Condition failed: [\"eq\", \"$acl\", \"aws-exec-read\"]",
     :aws_state         => "failed",
     :aws_instance_id   => "i-e3e24e8a"}]

Describe image attributes. Currently ‘launchPermission’, ‘productCodes’, ‘kernel’, ‘ramdisk’ and ‘blockDeviceMapping’ are supported.

 ec2.describe_image_attribute('ami-e444444d') #=> {:groups=>["all"], :users=>["000000000777"]}

Retrieve a list of images. Returns array of hashes describing the images or an exception: image_type = ‘machine’ || ‘kernel’ || ‘ramdisk‘

 ec2.describe_images #=>
   [{:aws_owner => "522821470517",
     :aws_id => "ami-e4b6538d",
     :aws_state => "available",
     :aws_location => "marcins_cool_public_images/ubuntu-6.10.manifest.xml",
     :aws_is_public => true,
     :aws_architecture => "i386",
     :aws_image_type => "machine"},
    {...},
    {...} ]

If list param is set, then retrieve information about the listed images only:

 ec2.describe_images(['ami-e4b6538d']) #=>
   [{:aws_owner => "522821470517",
     :aws_id => "ami-e4b6538d",
     :aws_state => "available",
     :aws_location => "marcins_cool_public_images/ubuntu-6.10.manifest.xml",
     :aws_is_public => true,
     :aws_architecture => "i386",
     :aws_image_type => "machine"}]

Example:

 ec2.describe_images_by_executable_by('522821470517')
 ec2.describe_images_by_executable_by('self')
 ec2.describe_images_by_executable_by('all')

Example:

 ec2.describe_images_by_owner('522821470517')
 ec2.describe_images_by_owner('self')

Retrieve information about EC2 instances. If list is omitted then returns the list of all instances.

 ec2.describe_instances #=>
   [{:aws_image_id       => "ami-e444444d",
     :aws_reason         => "",
     :aws_state_code     => "16",
     :aws_owner          => "000000000888",
     :aws_instance_id    => "i-123f1234",
     :aws_reservation_id => "r-aabbccdd",
     :aws_state          => "running",
     :dns_name           => "domU-12-34-67-89-01-C9.usma2.compute.amazonaws.com",
     :ssh_key_name       => "staging",
     :aws_groups         => ["default"],
     :private_dns_name   => "domU-12-34-67-89-01-C9.usma2.compute.amazonaws.com",
     :aws_instance_type  => "m1.small",
     :aws_launch_time    => "2008-1-1T00:00:00.000Z"},
     :aws_availability_zone => "us-east-1b",
     :aws_kernel_id      => "aki-ba3adfd3",
     :aws_ramdisk_id     => "ari-badbad00",
      ..., {...}]

Retrieve a list of SSH keys. Returns an array of keys or an exception. Each key is represented as a two-element hash.

 ec2.describe_key_pairs #=>
   [{:aws_fingerprint=> "01:02:03:f4:25:e6:97:e8:9b:02:1a:26:32:4e:58:6b:7a:8c:9f:03", :aws_key_name=>"key-1"},
    {:aws_fingerprint=> "1e:29:30:47:58:6d:7b:8c:9f:08:11:20:3c:44:52:69:74:80:97:08", :aws_key_name=>"key-2"},
     ..., {...} ]

Describe regions.

 ec2.describe_regions  #=> ["eu-west-1", "us-east-1"]

Retrieve Security Group information. If list is omitted the returns the whole list of groups.

 ec2.describe_security_groups #=>
   [{:aws_group_name  => "default-1",
     :aws_owner       => "000000000888",
     :aws_description => "Default allowing SSH, HTTP, and HTTPS ingress",
     :aws_perms       =>
       [{:owner => "000000000888", :group => "default"},
        {:owner => "000000000888", :group => "default-1"},
        {:to_port => "-1",  :protocol => "icmp", :from_port => "-1",  :cidr_ips => "0.0.0.0/0"},
        {:to_port => "22",  :protocol => "tcp",  :from_port => "22",  :cidr_ips => "0.0.0.0/0"},
        {:to_port => "80",  :protocol => "tcp",  :from_port => "80",  :cidr_ips => "0.0.0.0/0"},
        {:to_port => "443", :protocol => "tcp",  :from_port => "443", :cidr_ips => "0.0.0.0/0"}]},
   ..., {...}]

Describe all EBS snapshots.

ec2.describe_snapshots #=>

  [ { :aws_progress   => "100%",
      :aws_status     => "completed",
      :aws_id         => "snap-72a5401b",
      :aws_volume_id  => "vol-5582673c",
      :aws_started_at => "2008-02-23T02:50:48.000Z"},
    { :aws_progress   => "100%",
      :aws_status     => "completed",
      :aws_id         => "snap-75a5401c",
      :aws_volume_id  => "vol-5582673c",
      :aws_started_at => "2008-02-23T16:23:19.000Z" },...]

Describe all EBS volumes.

 ec2.describe_volumes #=>
     [{:aws_size              => 94,
       :aws_device            => "/dev/sdc",
       :aws_attachment_status => "attached",
       :zone                  => "merlot",
       :snapshot_id           => nil,
       :aws_attached_at       => Wed Jun 18 08:19:28 UTC 2008,
       :aws_status            => "in-use",
       :aws_id                => "vol-60957009",
       :aws_created_at        => Wed Jun 18 08:19:20s UTC 2008,
       :aws_instance_id       => "i-c014c0a9"},
      {:aws_size       => 1,
       :zone           => "merlot",
       :snapshot_id    => nil,
       :aws_status     => "available",
       :aws_id         => "vol-58957031",
       :aws_created_at => Wed Jun 18 08:19:21 UTC 2008,}, ... ]

Detach the specified EBS volume from the instance to which it is attached.

  ec2.detach_volume('vol-898a6fe0') #=>
    { :aws_instance_id => "i-7c905415",
      :aws_device      => "/dev/sdh",
      :aws_status      => "detaching",
      :aws_attached_at => "2008-03-28T14:38:34.000Z",
      :aws_id          => "vol-898a6fe0"}

Disassociate the specified elastic IP address from the instance to which it is assigned. Returns true or an exception.

 ec2.disassociate_address('75.101.154.140') #=> true

Retreive EC2 instance OS logs. Returns a hash of data or an exception.

 ec2.get_console_output('i-f222222d') =>
   {:aws_instance_id => 'i-f222222d',
    :aws_timestamp   => "2007-05-23T14:36:07.000-07:00",
    :timestamp       => Wed May 23 21:36:07 UTC 2007,          # Time instance
    :aws_output      => "Linux version 2.6.16-xenU (builder@patchbat.amazonsa) (gcc version 4.0.1 20050727 ..."

Get initial Windows Server setup password from an instance console output.

 my_awesome_key = ec2.create_key_pair('my_awesome_key') #=>
   {:aws_key_name    => "my_awesome_key",
    :aws_fingerprint => "01:02:03:f4:25:e6:97:e8:9b:02:1a:26:32:4e:58:6b:7a:8c:9f:03",
    :aws_material    => "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAK...Q8MDrCbuQ=\n-----END RSA PRIVATE KEY-----"}

 my_awesome_instance = ec2.run_instances('ami-a000000a',1,1,['my_awesome_group'],'my_awesome_key', 'WindowsInstance!!!') #=>
  [{:aws_image_id       => "ami-a000000a",
    :aws_instance_id    => "i-12345678",
    ...
    :aws_availability_zone => "us-east-1b"
    }]

 # wait until instance enters 'operational' state and get it's initial password

 puts ec2.get_initial_password(my_awesome_instance[:aws_instance_id], my_awesome_key[:aws_material]) #=> "MhjWcgZuY6"

Launch new EC2 instances. Returns a list of launched instances or an exception.

lparams keys (default values in parenthesis):

 :min_count              fixnum, (1)
 :max_count              fixnum, (1)
 :group_ids              array or string ([] == 'default')
 :instance_type          string (DEFAULT_INSTACE_TYPE)
 :addressing_type        string (DEFAULT_ADDRESSING_TYPE
 :key_name               string
 :kernel_id              string
 :ramdisk_id             string
 :availability_zone      string
 :block_device_mappings  string
 :user_data              string

 ec2.launch_instances('ami-e444444d', :group_ids => 'my_awesome_group',
                                      :user_data => "Woohoo!!!",
                                      :addressing_type => "public",
                                      :key_name => "my_awesome_key",
                                      :availability_zone => "us-east-1c") #=>
  [{:aws_image_id       => "ami-e444444d",
    :aws_reason         => "",
    :aws_state_code     => "0",
    :aws_owner          => "000000000888",
    :aws_instance_id    => "i-123f1234",
    :aws_reservation_id => "r-aabbccdd",
    :aws_state          => "pending",
    :dns_name           => "",
    :ssh_key_name       => "my_awesome_key",
    :aws_groups         => ["my_awesome_group"],
    :private_dns_name   => "",
    :aws_instance_type  => "m1.small",
    :aws_launch_time    => "2008-1-1T00:00:00.000Z",
    :aws_ramdisk_id     => "ari-8605e0ef"
    :aws_kernel_id      => "aki-9905e0f0",
    :ami_launch_index   => "0",
    :aws_availability_zone => "us-east-1c"
    }]

Modify an image‘s attributes. It is recommended that you use modify_image_launch_perm_add_users, modify_image_launch_perm_remove_users, etc. instead of modify_image_attribute because the signature of modify_image_attribute may change with EC2 service changes.

 attribute      : currently, only 'launchPermission' is supported.
 operation_type : currently, only 'add' & 'remove' are supported.
 vars:
   :user_group  : currently, only 'all' is supported.
   :user_id
   :product_code

Add image launch permissions for users groups (currently only ‘all’ is supported, which gives public launch permissions). Returns true or an exception.

 ec2.modify_image_launch_perm_add_groups('ami-e444444d') #=> true

Grant image launch permissions to users. Parameter userId is a list of user AWS account ids. Returns true or an exception.

 ec2.modify_image_launch_perm_add_users('ami-e444444d',['000000000777','000000000778']) #=> true

Remove image launch permissions for users groups (currently only ‘all’ is supported, which gives public launch permissions).

 ec2.modify_image_launch_perm_remove_groups('ami-e444444d') #=> true

Revokes image launch permissions for users. userId is a list of users AWS accounts ids. Returns true or an exception.

 ec2.modify_image_launch_perm_remove_users('ami-e444444d',['000000000777','000000000778']) #=> true

Add product code to image

 ec2.modify_image_product_code('ami-e444444d','0ABCDEF') #=> true

Reboot an EC2 instance. Returns true or an exception.

 ec2.reboot_instances(['i-f222222d','i-f222222e']) #=> true

Register new image at Amazon. Returns new image id or an exception.

 ec2.register_image('bucket/key/manifest') #=> 'ami-e444444d'

Release an elastic IP address associated with your account. Returns true or an exception.

 ec2.release_address('75.101.154.140') #=> true

Reset image attribute. Currently, only ‘launchPermission’ is supported. Returns true or an exception.

 ec2.reset_image_attribute('ami-e444444d') #=> true

Remove permission from a security group. Returns true or an exception. protocol is one of :’tcp’|’udp’|’icmp’ (‘tcp’ is default).

 ec2.revoke_security_group_IP_ingress('my_awesome_group', 80, 82, 'udp', '192.168.1.0/8') #=> true

Revoke named ingress for security group.

 ec2.revoke_security_group_named_ingress('my_awesome_group', aws_user_id, 'another_group_name') #=> true

Launch new EC2 instances. Returns a list of launched instances or an exception.

 ec2.run_instances('ami-e444444d',1,1,['my_awesome_group'],'my_awesome_key', 'Woohoo!!!', 'public') #=>
  [{:aws_image_id       => "ami-e444444d",
    :aws_reason         => "",
    :aws_state_code     => "0",
    :aws_owner          => "000000000888",
    :aws_instance_id    => "i-123f1234",
    :aws_reservation_id => "r-aabbccdd",
    :aws_state          => "pending",
    :dns_name           => "",
    :ssh_key_name       => "my_awesome_key",
    :aws_groups         => ["my_awesome_group"],
    :private_dns_name   => "",
    :aws_instance_type  => "m1.small",
    :aws_launch_time    => "2008-1-1T00:00:00.000Z"
    :aws_ramdisk_id     => "ari-8605e0ef"
    :aws_kernel_id      => "aki-9905e0f0",
    :ami_launch_index   => "0",
    :aws_availability_zone => "us-east-1b"
    }]

Terminates EC2 instances. Returns a list of termination params or an exception.

 ec2.terminate_instances(['i-f222222d','i-f222222e']) #=>
   [{:aws_shutdown_state      => "shutting-down",
     :aws_instance_id         => "i-f222222d",
     :aws_shutdown_state_code => 32,
     :aws_prev_state          => "running",
     :aws_prev_state_code     => 16},
    {:aws_shutdown_state      => "shutting-down",
     :aws_instance_id         => "i-f222222e",
     :aws_shutdown_state_code => 32,
     :aws_prev_state          => "running",
     :aws_prev_state_code     => 16}]

Create a snapshot of specified volume, but with the normal retry algorithms disabled. This method will return immediately upon error. The user can specify connect and read timeouts (in s) for the connection to AWS. If the user does not specify timeouts, try_create_snapshot uses the default values in Rightscale::HttpConnection.

 ec2.try_create_snapshot('vol-898a6fe0') #=>
     {:aws_volume_id  => "vol-fd9f7a94",
      :aws_started_at => Tue Jun 24 18:40:40 UTC 2008,
      :aws_progress   => "",
      :aws_status     => "pending",
      :aws_id         => "snap-d56783bc"}

[Validate]