Class: RightAws::Ec2

Inherits:
RightAwsBase show all
Includes:
RightAwsBaseInterface
Defined in:
lib/ec2/right_ec2.rb

Overview

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, , '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.

Defined Under Namespace

Classes: QEc2AllocateAddressParser, QEc2CreateKeyPairParser, QEc2DescribeAddressesParser, QEc2DescribeAvailabilityZonesParser, QEc2DescribeKeyPairParser, QEc2DescribeRegionsParser, QEc2DescribeSecurityGroupsParser, QEc2IpPermissionType, QEc2SecurityGroupItemType, QEc2UserIdGroupPairType, RightBoolResponseParser

Constant Summary collapse

API_VERSION =

Amazon EC2 API version being used

"2009-10-31"
DEFAULT_HOST =
"ec2.amazonaws.com"
DEFAULT_PATH =
'/'
DEFAULT_PROTOCOL =
'https'
DEFAULT_PORT =
443
DEFAULT_ADDRESSING_TYPE =

Default addressing type (public=NAT, direct=no-NAT) used when launching instances.

'public'
DNS_ADDRESSING_SET =
['public','direct']
DEFAULT_INSTANCE_TYPE =

Amazon EC2 Instance Types : www.amazon.com/b?ie=UTF8&node=370375011 Default EC2 instance type (platform)

'm1.small'
INSTANCE_TYPES =
['m1.small','c1.medium','m1.large','m1.xlarge','c1.xlarge', 'm2.2xlarge', 'm2.4xlarge']
@@bench =
AwsBenchmarkingBlock.new
@@api =

Current API version (sometimes we have to check it outside the GEM).

ENV['EC2_API_VERSION'] || API_VERSION

Constants included from RightAwsBaseInterface

RightAwsBaseInterface::DEFAULT_SIGNATURE_VERSION

Constants inherited from RightAwsBase

RightAwsBase::AMAZON_PROBLEMS

Instance Attribute Summary

Attributes included from RightAwsBaseInterface

#aws_access_key_id, #cache, #connection, #last_errors, #last_request, #last_request_id, #last_response, #logger, #params, #signature_version

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RightAwsBaseInterface

#amazonize_list, #cache_hits?, caching, caching=, #caching?, #generate_request_impl, #get_connection, #init, #on_exception, #request_cache_or_info, #request_info_impl, #signed_service_params, #update_cache

Methods inherited from RightAwsBase

amazon_problems, amazon_problems=

Constructor Details

#initialize(aws_access_key_id = nil, aws_secret_access_key = nil, params = {}) ⇒ Ec2

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’,‘1’ or ‘2’(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.



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

def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
  init({ :name                => 'EC2',
         :default_host        => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).host   : DEFAULT_HOST,
         :default_port        => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).port   : DEFAULT_PORT,
         :default_service     => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).path   : DEFAULT_PATH,
         :default_protocol    => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).scheme : DEFAULT_PROTOCOL,
         :default_api_version => @@api },
       aws_access_key_id    || ENV['AWS_ACCESS_KEY_ID'] , 
       aws_secret_access_key|| ENV['AWS_SECRET_ACCESS_KEY'],
       params)
end

Class Method Details

.apiObject



96
97
98
# File 'lib/ec2/right_ec2.rb', line 96

def self.api 
  @@api
end

.bench_ec2Object



90
91
92
# File 'lib/ec2/right_ec2.rb', line 90

def self.bench_ec2
  @@bench.service
end

.bench_xmlObject



87
88
89
# File 'lib/ec2/right_ec2.rb', line 87

def self.bench_xml
  @@bench.xml
end

Instance Method Details

#allocate_addressObject

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'


340
341
342
343
344
345
# File 'lib/ec2/right_ec2.rb', line 340

def allocate_address
  link = generate_request("AllocateAddress")
  request_info(link, QEc2AllocateAddressParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#associate_address(instance_id, public_ip) ⇒ Object

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

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


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

def associate_address(instance_id, public_ip)
  link = generate_request("AssociateAddress", 
                          "InstanceId" => instance_id.to_s,
                          "PublicIp"   => public_ip.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#authorize_security_group_IP_ingress(name, from_port, to_port, protocol = 'tcp', cidr_ip = '0.0.0.0/0') ⇒ Object

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


257
258
259
260
261
262
263
264
265
266
267
# File 'lib/ec2/right_ec2.rb', line 257

def authorize_security_group_IP_ingress(name, from_port, to_port, protocol='tcp', cidr_ip='0.0.0.0/0')
  link = generate_request("AuthorizeSecurityGroupIngress", 
                          'GroupName'  => name.to_s,
                          'IpProtocol' => protocol.to_s,
                          'FromPort'   => from_port.to_s,
                          'ToPort'     => to_port.to_s,
                          'CidrIp'     => cidr_ip.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#authorize_security_group_named_ingress(name, owner, group) ⇒ Object

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


228
229
230
231
232
233
234
235
236
# File 'lib/ec2/right_ec2.rb', line 228

def authorize_security_group_named_ingress(name, owner, group)
  link = generate_request("AuthorizeSecurityGroupIngress", 
                          'GroupName'                  => name.to_s,
                            'SourceSecurityGroupName'    => group.to_s,
                          'SourceSecurityGroupOwnerId' => owner.to_s.gsub(/-/,''))
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_key_pair(name) ⇒ Object

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-----"}


311
312
313
314
315
316
317
# File 'lib/ec2/right_ec2.rb', line 311

def create_key_pair(name)
  link = generate_request("CreateKeyPair", 
                          'KeyName' => name.to_s)
  request_info(link, QEc2CreateKeyPairParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_security_group(name, description) ⇒ Object

Create new Security Group. Returns true or an exception.

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


200
201
202
203
204
205
206
207
208
209
# File 'lib/ec2/right_ec2.rb', line 200

def create_security_group(name, description)
  # EC2 doesn't like an empty description...
  description = " " if description.blank?
  link = generate_request("CreateSecurityGroup", 
                          'GroupName'        => name.to_s,
                          'GroupDescription' => description.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_key_pair(name) ⇒ Object

Delete a key pair. Returns true or an exception.

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


323
324
325
326
327
328
329
# File 'lib/ec2/right_ec2.rb', line 323

def delete_key_pair(name)
  link = generate_request("DeleteKeyPair", 
                          'KeyName' => name.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_security_group(name) ⇒ Object

Remove Security Group. Returns true or an exception.

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


215
216
217
218
219
220
221
# File 'lib/ec2/right_ec2.rb', line 215

def delete_security_group(name)
  link = generate_request("DeleteSecurityGroup", 
                          'GroupName' => name.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#describe_addresses(list = []) ⇒ Object

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"}]


369
370
371
372
373
374
375
# File 'lib/ec2/right_ec2.rb', line 369

def describe_addresses(list=[])
  link = generate_request("DescribeAddresses", 
                          amazonize_list('PublicIp',list.to_a))
  request_cache_or_info :describe_addresses, link,  QEc2DescribeAddressesParser, @@bench, list.blank?
rescue Exception
  on_exception
end

#describe_availability_zones(list = []) ⇒ Object

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"}]


418
419
420
421
422
423
424
# File 'lib/ec2/right_ec2.rb', line 418

def describe_availability_zones(list=[])
  link = generate_request("DescribeAvailabilityZones", 
                          amazonize_list('ZoneName',list.to_a))
  request_cache_or_info :describe_availability_zones, link,  QEc2DescribeAvailabilityZonesParser, @@bench, list.blank?
rescue Exception
  on_exception
end

#describe_key_pairs(list = []) ⇒ Object

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"},
    ..., {...} ]


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

def describe_key_pairs(list=[])
  link = generate_request("DescribeKeyPairs", amazonize_list('KeyName',list.to_a))
  request_cache_or_info :describe_key_pairs, link,  QEc2DescribeKeyPairParser, @@bench, list.blank?
rescue Exception
  on_exception
end

#describe_regions(list = []) ⇒ Object

Describe regions.

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


434
435
436
437
438
439
440
# File 'lib/ec2/right_ec2.rb', line 434

def describe_regions(list=[])
  link = generate_request("DescribeRegions",
                          amazonize_list('RegionName',list.to_a))
  request_cache_or_info :describe_regions, link,  QEc2DescribeRegionsParser, @@bench, list.blank?
rescue Exception
  on_exception
end

#describe_security_groups(list = []) ⇒ Object

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"}]},
  ..., {...}]


157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/ec2/right_ec2.rb', line 157

def describe_security_groups(list=[])
  link = generate_request("DescribeSecurityGroups", amazonize_list('GroupName',list.to_a))
  request_cache_or_info( :describe_security_groups, link,  QEc2DescribeSecurityGroupsParser, @@bench, list.blank?) do |parser|
    result = []     
    parser.result.each do |item|
      perms = []
      item.ipPermissions.each do |perm|
        perm.groups.each do |ngroup|
          perms << {:group => ngroup.groupName,
                    :owner => ngroup.userId}
        end
        perm.ipRanges.each do |cidr_ip|
          perms << {:from_port => perm.fromPort, 
                    :to_port   => perm.toPort, 
                    :protocol  => perm.ipProtocol,
                    :cidr_ips  => cidr_ip}
        end
      end

         # delete duplication
      perms.each_index do |i|
        (0...i).each do |j|
          if perms[i] == perms[j] then perms[i] = nil; break; end
        end
      end
      perms.compact!

      result << {:aws_owner       => item.ownerId, 
                 :aws_group_name  => item.groupName, 
                 :aws_description => item.groupDescription,
                 :aws_perms       => perms}
    
    end
    result
  end
rescue Exception
  on_exception
end

#disassociate_address(public_ip) ⇒ Object

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


382
383
384
385
386
387
388
# File 'lib/ec2/right_ec2.rb', line 382

def disassociate_address(public_ip)
  link = generate_request("DisassociateAddress", 
                          "PublicIp" => public_ip.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#generate_request(action, params = {}) ⇒ Object

:nodoc:



128
129
130
# File 'lib/ec2/right_ec2.rb', line 128

def generate_request(action, params={}) #:nodoc:
  generate_request_impl(:get, action, params )
end

#release_address(public_ip) ⇒ Object

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

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


395
396
397
398
399
400
401
# File 'lib/ec2/right_ec2.rb', line 395

def release_address(public_ip)
  link = generate_request("ReleaseAddress", 
                          "PublicIp" => public_ip.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#request_info(request, parser) ⇒ Object

Sends request to Amazon and parses the response Raises AwsError if any banana happened



134
135
136
# File 'lib/ec2/right_ec2.rb', line 134

def request_info(request, parser)  #:nodoc:
  request_info_impl(:ec2_connection, @@bench, request, parser)
end

#revoke_security_group_IP_ingress(name, from_port, to_port, protocol = 'tcp', cidr_ip = '0.0.0.0/0') ⇒ Object

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


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

def revoke_security_group_IP_ingress(name, from_port, to_port, protocol='tcp', cidr_ip='0.0.0.0/0')
  link = generate_request("RevokeSecurityGroupIngress", 
                          'GroupName'  => name.to_s,
                          'IpProtocol' => protocol.to_s,
                          'FromPort'   => from_port.to_s,
                          'ToPort'     => to_port.to_s,
                          'CidrIp'     => cidr_ip.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#revoke_security_group_named_ingress(name, owner, group) ⇒ Object

Revoke named ingress for security group.

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


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

def revoke_security_group_named_ingress(name, owner, group)
  link = generate_request("RevokeSecurityGroupIngress", 
                          'GroupName'                  => name.to_s,
                          'SourceSecurityGroupName'    => group.to_s,
                          'SourceSecurityGroupOwnerId' => owner.to_s.gsub(/-/,''))
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end