Class: RightAws::Ec2

Inherits:
RightAwsBase show all
Includes:
RightAwsBaseInterface
Defined in:
lib/ec2/right_ec2.rb,
lib/ec2/right_ec2_ebs.rb,
lib/ec2/right_ec2_vpc.rb,
lib/ec2/right_ec2_tags.rb,
lib/ec2/right_ec2_images.rb,
lib/ec2/right_ec2_instances.rb,
lib/ec2/right_ec2_monitoring.rb,
lib/ec2/right_ec2_spot_instances.rb,
lib/ec2/right_ec2_security_groups.rb,
lib/ec2/right_ec2_placement_groups.rb,
lib/ec2/right_ec2_windows_mobility.rb,
lib/ec2/right_ec2_reserved_instances.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, QEc2AttachAndDetachVolumeParser, QEc2AttachVpnGatewayParser, QEc2BundleInstanceParser, QEc2CancelSpotInstanceParser, QEc2ConfirmProductInstanceParser, QEc2CreateKeyPairParser, QEc2CreateVolumeParser, QEc2DescribeAddressesParser, QEc2DescribeAvailabilityZonesParser, QEc2DescribeBundleTasksParser, QEc2DescribeCustomerGatewaysParser, QEc2DescribeDhcpOptionsParser, QEc2DescribeImageAttributeParser, QEc2DescribeImagesParser, QEc2DescribeInstanceAttributeParser, QEc2DescribeInstancesParser, QEc2DescribeKeyPairParser, QEc2DescribeLicensesParser, QEc2DescribePlacementGroupsParser, QEc2DescribeRegionsParser, QEc2DescribeReservedInstancesOfferingsParser, QEc2DescribeReservedInstancesParser, QEc2DescribeSecurityGroupsParser, QEc2DescribeSnapshotAttributeParser, QEc2DescribeSnapshotsParser, QEc2DescribeSpotDatafeedSubscriptionParser, QEc2DescribeSpotInstanceParser, QEc2DescribeSpotPriceHistoryParser, QEc2DescribeSubnetsParser, QEc2DescribeTagsParser, QEc2DescribeVolumesParser, QEc2DescribeVpcsParser, QEc2DescribeVpnConnectionsParser, QEc2DescribeVpnGatewaysParser, QEc2GetConsoleOutputParser, QEc2GetPasswordDataParser, QEc2ImportKeyPairParser, QEc2MonitorInstancesParser, QEc2PurchaseReservedInstancesOfferingParser, QEc2RegisterImageParser, QEc2TerminateInstancesParser

Constant Summary collapse

API_VERSION =

Amazon EC2 API version being used

"2010-08-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 =
['t1.micro','m1.small','c1.medium','m1.large','m1.xlarge',
'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge',
'cc1.4xlarge', 'cg1.4xlarge']
INSTANCE_ATTRIBUTE_MAPPING =
{
  "instance_type"                        => "instanceType",
  "kernel"                               => "kernel",
  "ramdisk"                              => "ramdisk",
  "user_data"                            => "userData",
  "disable_api_termination"              => "disableApiTermination",
  "instance_initiated_shutdown_behavior" => "instanceInitiatedShutdownBehavior",
  "root_device_name"                     => "rootDeviceName",
  "block_device_mapping"                 => "blockDeviceMapping"
}
@@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::BLOCK_DEVICE_KEY_MAPPING, RightAwsBaseInterface::DEFAULT_SIGNATURE_VERSION

Constants inherited from RightAwsBase

RightAwsBase::AMAZON_PROBLEMS, RightAwsBase::RAISE_ON_TIMEOUT_ON_ACTIONS

Instance Attribute Summary

Attributes included from RightAwsBaseInterface

#aws_access_key_id, #aws_secret_access_key, #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_block_device_mappings, #amazonize_list, #cache_hits?, caching, caching=, #caching?, #destroy_connection, #generate_request_impl, #get_connection, #get_connections_storage, #get_server_url, #incrementally_list_items, #init, #on_exception, #request_cache_or_info, #request_info_impl, #signed_service_params, #update_cache, #with_connection_options

Methods inherited from RightAwsBase

amazon_problems, amazon_problems=, raise_on_timeout_on_actions, raise_on_timeout_on_actions=

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

  • :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.



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/ec2/right_ec2.rb', line 117

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)
  # Eucalyptus supports some yummy features but Amazon does not
  #if @params[:eucalyptus]
  #  @params[:port_based_group_ingress] = true unless @params.has_key?(:port_based_group_ingress)
  #end
end

Class Method Details

.apiObject



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

def self.api 
  @@api
end

.bench_ec2Object



92
93
94
# File 'lib/ec2/right_ec2.rb', line 92

def self.bench_ec2
  @@bench.service
end

.bench_xmlObject



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

def self.bench_xml
  @@bench.xml
end

Instance Method Details

#activate_license(license_id, capacity) ⇒ Object



33
34
35
36
37
# File 'lib/ec2/right_ec2_windows_mobility.rb', line 33

def activate_license(license_id, capacity)
  link = generate_request("ActivateLicense", 'LicenseId' => license_id,
                                             'Capacity'  => capacity)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
end

#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'


233
234
235
236
237
238
# File 'lib/ec2/right_ec2.rb', line 233

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


245
246
247
248
249
250
251
252
# File 'lib/ec2/right_ec2.rb', line 245

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

#associate_dhcp_options(dhcp_options_id, vpc_id) ⇒ Object

Associate DHCP options

ec2.associate_dhcp_options(“dopt-cb0de3a2”, “vpc-890ce2e0” ) #=> true ec2.describe_vpcs #=>

[{:vpc_id=>"vpc-890ce2e0",
  :dhcp_options_id=>"dopt-cb0de3a2",
  :cidr_block=>"10.0.0.0/23",
  :state=>"available"}]


190
191
192
193
194
195
196
# File 'lib/ec2/right_ec2_vpc.rb', line 190

def associate_dhcp_options(dhcp_options_id, vpc_id)
  link = generate_request("AssociateDhcpOptions", 'DhcpOptionsId' => dhcp_options_id,
                                                  'VpcId'         => vpc_id)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#attach_volume(volume_id, instance_id, device) ⇒ Object

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


110
111
112
113
114
115
116
117
118
# File 'lib/ec2/right_ec2_ebs.rb', line 110

def attach_volume(volume_id, instance_id, device)
  link = generate_request("AttachVolume",
                          "VolumeId"   => volume_id.to_s,
                          "InstanceId" => instance_id.to_s,
                          "Device"     => device.to_s)
  request_info(link, QEc2AttachAndDetachVolumeParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#attach_vpn_gateway(vpn_gateway_id, vpc_id) ⇒ Object

Attach VPN gateway.

ec2.attach_vpn_gateway('vgw-dfa144b6','vpc-890ce2e0') #=>
   {:vpc_id=>"vpc-890ce2e0", :state=>"attaching"}


309
310
311
312
313
314
315
# File 'lib/ec2/right_ec2_vpc.rb', line 309

def attach_vpn_gateway(vpn_gateway_id, vpc_id)
  link = generate_request("AttachVpnGateway", 'VpnGatewayId' => vpn_gateway_id,
                                              'VpcId'        => vpc_id )
  request_info(link, QEc2AttachVpnGatewayParser.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


342
343
344
# File 'lib/ec2/right_ec2_security_groups.rb', line 342

def authorize_security_group_IP_ingress(name, from_port, to_port, protocol='tcp', cidr_ip='0.0.0.0/0')
  edit_security_group( :authorize, name, :from_port => from_port, :to_port => to_port, :protocol => protocol, :cidr_ip => cidr_ip )
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


325
326
327
# File 'lib/ec2/right_ec2_security_groups.rb', line 325

def authorize_security_group_named_ingress(name, owner, group)
  edit_security_group( :authorize, name, :source_group_owner => owner, :source_group => group)
end

#bundle_instance(instance_id, s3_bucket, s3_prefix, s3_owner_aws_access_key_id = nil, s3_owner_aws_secret_access_key = nil, s3_expires = S3Interface::DEFAULT_EXPIRES_AFTER, s3_upload_policy = 'ec2-bundle-read') ⇒ Object

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


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/ec2/right_ec2_instances.rb', line 472

def bundle_instance(instance_id, s3_bucket, s3_prefix,
                    s3_owner_aws_access_key_id=nil, s3_owner_aws_secret_access_key=nil,
                    s3_expires = S3Interface::DEFAULT_EXPIRES_AFTER,
                    s3_upload_policy='ec2-bundle-read')
  # S3 access and signatures
  s3_owner_aws_access_key_id     ||= @aws_access_key_id
  s3_owner_aws_secret_access_key ||= @aws_secret_access_key
  s3_expires = Time.now.utc + s3_expires if s3_expires.is_a?(Fixnum) && (s3_expires < S3Interface::ONE_YEAR_IN_SECONDS)
  # policy
  policy = { 'expiration' => AwsUtils::utc_iso8601(s3_expires),
             'conditions' => [ { 'bucket' => s3_bucket },
                               { 'acl'    => s3_upload_policy },
                               [ 'starts-with', '$key', s3_prefix ] ] }.to_json
  policy64        = Base64.encode64(policy).gsub("\n","")
  signed_policy64 = AwsUtils.sign(s3_owner_aws_secret_access_key, policy64)
  # fill request params
  params = { 'InstanceId'                       => instance_id,
             'Storage.S3.AWSAccessKeyId'        => s3_owner_aws_access_key_id,
             'Storage.S3.UploadPolicy'          => policy64,
             'Storage.S3.UploadPolicySignature' => signed_policy64,
             'Storage.S3.Bucket'                => s3_bucket,
             'Storage.S3.Prefix'                => s3_prefix,
             }
  link = generate_request("BundleInstance", params)
  request_info(link, QEc2BundleInstanceParser.new)
rescue Exception
  on_exception
end

#cancel_bundle_task(bundle_id) ⇒ Object

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


541
542
543
544
545
546
# File 'lib/ec2/right_ec2_instances.rb', line 541

def cancel_bundle_task(bundle_id)
  link = generate_request("CancelBundleTask", { 'BundleId' => bundle_id })
  request_info(link, QEc2BundleInstanceParser.new)
rescue Exception
  on_exception
end

#cancel_spot_instance_requests(*spot_instance_request_ids) ⇒ Object

Cancel one or more Spot Instance requests.

ec2.cancel_spot_instance_requests('sir-60662c03',"sir-d3c96e04", "sir-4fa8d804","sir-6992ce04") #=>
  [{:state=>"cancelled", :spot_instance_request_id=>"sir-60662c03"},
   {:state=>"cancelled", :spot_instance_request_id=>"sir-6992ce04"},
   {:state=>"cancelled", :spot_instance_request_id=>"sir-4fa8d804"},
   {:state=>"cancelled", :spot_instance_request_id=>"sir-d3c96e04"}]


262
263
264
265
# File 'lib/ec2/right_ec2_spot_instances.rb', line 262

def cancel_spot_instance_requests(*spot_instance_request_ids)
  link = generate_request("CancelSpotInstanceRequests", amazonize_list('SpotInstanceRequestId', spot_instance_request_ids.flatten))
  request_info(link, QEc2CancelSpotInstanceParser.new(:logger => @logger))
end

#confirm_product_instance(instance, product_code) ⇒ Object

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"


113
114
115
116
117
# File 'lib/ec2/right_ec2_instances.rb', line 113

def confirm_product_instance(instance, product_code)
  link = generate_request("ConfirmProductInstance", { 'ProductCode' => product_code,
                            'InstanceId'  => instance })
  request_info(link, QEc2ConfirmProductInstanceParser.new(:logger => @logger))
end

#create_customer_gateway(type, ip_address, bgp_asn) ⇒ Object

Create customer gateway.

ec2.create_customer_gateway('ipsec.1', '12.1.2.3', 65534) #=>
  {:type=>"ipsec.1",
   :bgp_asn=>"65534",
   :ip_address=>"12.1.2.3",
   :state=>"pending",
   :customer_gateway_id=>"cgw-d5a643bc"}


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

def create_customer_gateway(type, ip_address, bgp_asn)
  link = generate_request("CreateCustomerGateway", 'Type'      => type,
                                                   'IpAddress' => ip_address,
                                                   'BgpAsn'    => bgp_asn )
  request_info(link, QEc2DescribeCustomerGatewaysParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_dhcp_options(dhcp_configuration) ⇒ Object

Create DHCP options.

ec2.create_dhcp_options('domain-name' => 'my.awesomesite.ru',
                        'netbios-node-type' => 1) #=>
  {:dhcp_options_id=>"dopt-cb0de3a2",
   :dhcp_configuration_set=>
    {"netbios-node-type"=>["1"], "domain-name"=>["my.awesomesite.ru"]}}


172
173
174
175
176
177
178
179
# File 'lib/ec2/right_ec2_vpc.rb', line 172

def create_dhcp_options(dhcp_configuration)
  dhcp_configuration.each{ |key, values| dhcp_configuration[key] = Array(values) }
  request_hash = amazonize_list(['DhcpConfiguration.?.Key','DhcpConfiguration.?.Value.?'], dhcp_configuration)
  link = generate_request("CreateDhcpOptions", request_hash)
  request_info(link, QEc2DescribeDhcpOptionsParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_image(instance_aws_id, options = {}) ⇒ Object

Create a new image. Options: :name, :description, :no_reboot(bool)

ec2.create_image(instance, :description => 'KD: test#1',
                           :no_reboot => true,
                           :name => 'kd-1' ) #=> "ami-84a1f792"


303
304
305
306
307
308
309
310
# File 'lib/ec2/right_ec2_images.rb', line 303

def create_image(instance_aws_id, options={})
  params = { 'InstanceId' => instance_aws_id }
  params['Name']        = options[:name]            unless options[:name].right_blank?
  params['Description'] = options[:description]     unless options[:description].right_blank?
  params['NoReboot']    = options[:no_reboot].to_s  unless options[:no_reboot].nil?
  link = generate_request("CreateImage", params)
  request_info(link, QEc2RegisterImageParser.new(:logger => @logger))
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-----"}


204
205
206
207
208
209
210
# File 'lib/ec2/right_ec2.rb', line 204

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_placement_group(placement_group_name, strategy = 'cluster') ⇒ Object

Create placement group creates a placement group (i.e. logical cluster group) into which you can then launch instances. You must provide a name for the group that is unique within the scope of your account. You must also provide a strategy value. Currently the only value accepted is cluster.

ec2.create_placement_group('kd_second') #=> true


62
63
64
65
66
67
68
69
# File 'lib/ec2/right_ec2_placement_groups.rb', line 62

def create_placement_group(placement_group_name, strategy = 'cluster')
  link = generate_request('CreatePlacementGroup',
                          'GroupName' => placement_group_name.to_s,
                          'Strategy'  => strategy.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_security_group(name, description = nil) ⇒ Object

Create new Security Group. Returns true or an exception.

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


129
130
131
132
133
134
135
136
137
138
# File 'lib/ec2/right_ec2_security_groups.rb', line 129

def create_security_group(name, description=nil)
  # EC2 doesn't like an empty description...
  description = "-" if description.right_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

#create_snapshot(volume_id, description = '') ⇒ Object

Create a snapshot of specified volume.

ec2.create_snapshot('vol-898a6fe0', 'KD: WooHoo!!') #=>
  {:aws_volume_id=>"vol-e429db8d",
   :aws_started_at=>"2009-10-01T09:23:38.000Z",
   :aws_description=>"KD: WooHoo!!",
   :aws_owner=>"648770000000",
   :aws_progress=>"",
   :aws_status=>"pending",
   :aws_volume_size=>1,
   :aws_id=>"snap-3df54854"}


191
192
193
194
195
196
197
198
# File 'lib/ec2/right_ec2_ebs.rb', line 191

def create_snapshot(volume_id, description='')
  link = generate_request("CreateSnapshot",
                          "VolumeId" => volume_id.to_s,
                          "Description" => description)
  request_info(link, QEc2DescribeSnapshotsParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_spot_datafeed_subscription(bucket, prefix = nil) ⇒ Object

Create the data feed for Spot Instances (Enables to view Spot Instance usage logs)

ec2.create_spot_datafeed_subscription('bucket-for-konstantin-eu', 'splogs/') #=>
  { :owner_id=>"826693181925",
    :bucket=>"bucket-for-konstantin-eu",
    :prefix=>"splogs/",
    :state=>"Active"}


276
277
278
279
280
281
# File 'lib/ec2/right_ec2_spot_instances.rb', line 276

def create_spot_datafeed_subscription(bucket, prefix=nil)
  request_hash = { 'Bucket' => bucket }
  request_hash['Prefix'] = prefix unless prefix.right_blank?
  link = generate_request("CreateSpotDatafeedSubscription", request_hash)
  request_info(link, QEc2DescribeSpotDatafeedSubscriptionParser.new(:logger => @logger))
end

#create_subnet(vpc_id, cidr_block, availability_zone = nil) ⇒ Object

Create Subnet.

ec2.create_subnet("vpc-890ce2e0",'10.0.1.0/24') #=>
  {:available_ip_address_count=>"251",
   :vpc_id=>"vpc-890ce2e0",
   :availability_zone=>"us-east-1a",
   :subnet_id=>"subnet-770de31e",
   :cidr_block=>"10.0.1.0/24",
   :state=>"pending"}


120
121
122
123
124
125
126
127
128
# File 'lib/ec2/right_ec2_vpc.rb', line 120

def create_subnet(vpc_id, cidr_block, availability_zone = nil)
  request_hash = { 'VpcId'     => vpc_id,
                   'CidrBlock' => cidr_block }
  request_hash['AvailabilityZone'] = availability_zone unless availability_zone.right_blank?
  link = generate_request("CreateSubnet", request_hash)
  request_info(link, QEc2DescribeSubnetsParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_tags(resources, tags, options = {}) ⇒ Object

Create tags. Options:

:default => 'something' : a default value for keys without (or with nil) values.

Add a single tag with no value to a resource: ec2.create_tags(“i-12345678”, “myKey”) => true

Add multiple tags with no values (actually Amazon sets the values to ”) ec2.create_tags(“i-12345678”, [“myKey1”, “myKey2”, “myKey3”]) => true

Add multiple tags with ‘true’ ec2.create_tags(“i-12345678”, [“myKey1”, “myKey2”, “myKey3”], :default => true ) => true

Add multiple keys and values to a resource: ec2.create_tags(“i-12345678”, {“myKey1” => “foo”, “myKey2” => “bar”, “myKeyWithoutVal” => nil }) #=> true

Add a key and value to multiple resources: ec2.create_tags(, => “foo”) #=> true



74
75
76
77
78
79
80
81
82
# File 'lib/ec2/right_ec2_tags.rb', line 74

def create_tags(resources, tags, options={})
  default = options[:default].nil? ? '' : options[:default]
  params = amazonize_list("ResourceId", resources)
  params.merge! amazonize_list(['Tag.?.Key', 'Tag.?.Value'], tags, :default => default)
  link = generate_request("CreateTags", params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_volume(snapshot_id, size, zone) ⇒ Object

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 => "2008-06-24T18:13:32.000Z",
     :aws_size       => 94}


76
77
78
79
80
81
82
83
84
85
# File 'lib/ec2/right_ec2_ebs.rb', line 76

def create_volume(snapshot_id, size, zone)
  hash = { "Size"              => size.to_s,
           "AvailabilityZone"  => zone.to_s }
  # Get rig of empty snapshot: e8s guys do not like it
  hash["SnapshotId"] = snapshot_id.to_s unless snapshot_id.right_blank?
  link = generate_request("CreateVolume", hash )
  request_info(link, QEc2CreateVolumeParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_vpc(cidr_block) ⇒ Object

Create VPC.

ec2.create_vpc('10.0.0.0/23') #=>
  {:vpc_id=>"vpc-890ce2e0",
   :dhcp_options_id=>"default",
   :cidr_block=>"10.0.0.0/23",
   :state=>"pending"}


66
67
68
69
70
71
# File 'lib/ec2/right_ec2_vpc.rb', line 66

def create_vpc(cidr_block)
  link = generate_request("CreateVpc",'CidrBlock' => cidr_block )
  request_info(link, QEc2DescribeVpcsParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_vpn_connection(type, customer_gateway_id, vpn_gateway_id) ⇒ Object

Create VPN connection.

ec2.create_vpn_connection('ipsec.1', 'cgw-81a643e8' ,'vgw-dfa144b6')
  {:customer_gateway_id=>"cgw-81a643e8",
   :vpn_connection_id=>"vpn-a9a643c0",
   :customer_gateway_configuration=>
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<vpn_connection id=\"vpn-a9a643c0\">\n...</vpn_connection>\n",
   :state=>"pending",
   :vpn_gateway_id=>"vgw-dfa144b6"}


378
379
380
381
382
383
384
385
# File 'lib/ec2/right_ec2_vpc.rb', line 378

def create_vpn_connection(type, customer_gateway_id, vpn_gateway_id)
  link = generate_request("CreateVpnConnection", 'Type'              => type,
                                                 'CustomerGatewayId' => customer_gateway_id,
                                                 'VpnGatewayId'      => vpn_gateway_id )
  request_info(link, QEc2DescribeVpnConnectionsParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_vpn_gateway(type, availability_zone = nil) ⇒ Object

Create VPN gateway.

ec2.create_vpn_gateway('ipsec.1') #=>
  {:type=>"ipsec.1",
   :availability_zone=>"us-east-1a",
   :attachments=>[nil],
   :vpn_gateway_id=>"vgw-dfa144b6"}


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

def create_vpn_gateway(type, availability_zone=nil)
  request_hash = { 'Type' => type }
  request_hash['AvailabilityZone'] = availability_zone unless availability_zone.right_blank?
  link = generate_request("CreateVpnGateway", request_hash )
  request_info(link, QEc2DescribeVpnGatewaysParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#deactivate_license(license_id, capacity) ⇒ Object

def get_license_capacity(license_id)

  link = generate_request("GetLicenseCapacity", 'LicenseId' => license_id)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
end


44
45
46
47
48
# File 'lib/ec2/right_ec2_windows_mobility.rb', line 44

def deactivate_license(license_id, capacity)
  link = generate_request("DeactivateLicense", 'LicenseId' => license_id,
                                               'Capacity'  => capacity)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
end

#delete_customer_gateway(customer_gateway_id) ⇒ Object

Delete customer gateway.

ec2.delete_customer_gateway("cgw-d5a643bc") #=> true


256
257
258
259
260
261
# File 'lib/ec2/right_ec2_vpc.rb', line 256

def delete_customer_gateway(customer_gateway_id)
  link = generate_request("DeleteCustomerGateway", 'CustomerGatewayId' => customer_gateway_id )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_dhcp_options(dhcp_options_id) ⇒ Object

Delete DHCP Options.

ec2.delete_dhcp_options("dopt-cb0de3a2") #=> true


202
203
204
205
206
207
# File 'lib/ec2/right_ec2_vpc.rb', line 202

def delete_dhcp_options(dhcp_options_id)
  link = generate_request("DeleteDhcpOptions", 'DhcpOptionsId' => dhcp_options_id )
  request_info(link, RightHttp2xxParser.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


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

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_placement_group(placement_group_name) ⇒ Object

Delete placement group deletes a placement group that you own. The group must not contain any instances.

ec2.delete_placement_group('kd_second') #=> true


76
77
78
79
80
81
82
# File 'lib/ec2/right_ec2_placement_groups.rb', line 76

def delete_placement_group(placement_group_name)
  link = generate_request('DeletePlacementGroup',
                          'GroupName' => placement_group_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


144
145
146
147
148
149
150
# File 'lib/ec2/right_ec2_security_groups.rb', line 144

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

#delete_snapshot(snapshot_id) ⇒ Object

Delete the specified snapshot.

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


331
332
333
334
335
336
337
# File 'lib/ec2/right_ec2_ebs.rb', line 331

def delete_snapshot(snapshot_id)
  link = generate_request("DeleteSnapshot",
                          "SnapshotId" => snapshot_id.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_spot_datafeed_subscriptionObject

Delete the data feed for Spot Instances.

ec2.delete_spot_datafeed_subscription #=> true


300
301
302
303
# File 'lib/ec2/right_ec2_spot_instances.rb', line 300

def delete_spot_datafeed_subscription()
  link = generate_request("DeleteSpotDatafeedSubscription")
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
end

#delete_subnet(subnet_id) ⇒ Object

Delete Subnet.

ec2.delete_subnet("subnet-770de31e") #=> true


134
135
136
137
138
139
# File 'lib/ec2/right_ec2_vpc.rb', line 134

def delete_subnet(subnet_id)
  link = generate_request("DeleteSubnet", 'SubnetId' => subnet_id )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_tags(resources, tags, options = {}) ⇒ Object

Delete tags. Options:

:default => 'something' : a default value for keys without (or with nil) values.

Delete a tag from a resource regardless of value: ec2.delete_tags(“i-12345678”, “myKey”) => true

Delete multiple tags (regardless of their values) ec2.delete_tags(“i-12345678”, [“myKey1”, “myKey2”, “myKey3”]) => true

Add multiple tags with value ‘true’ ec2.delete_tags(“i-12345678”, [“myKey1”, “myKey2”, “myKey3”], :default => true) => true

Delete multiple keys and values to a resource: ec2.delete_tags(“i-12345678”, [{“myKey1” => “foo”, “myKey2” => “bar”,“myKeyForAnyVal” => nil }]) #=> true

Delete a key and value on multiple resources: ec2.delete_tags([“i-12345678”, “i-a1234567”, “i-b1234567”], => “foo”) #=> true



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

def delete_tags(resources, tags, options={})
  default = options[:default].nil? ? :skip_nils : options[:default]
  params = amazonize_list("ResourceId", resources)
  params.merge! amazonize_list(['Tag.?.Key', 'Tag.?.Value'], tags, :default => default)
  link = generate_request("DeleteTags", params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_volume(volume_id) ⇒ Object

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

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


92
93
94
95
96
97
98
# File 'lib/ec2/right_ec2_ebs.rb', line 92

def delete_volume(volume_id)
  link = generate_request("DeleteVolume",
                          "VolumeId" => volume_id.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_vpc(vpc_id) ⇒ Object

Delete VPC.

ec2.delete_vpc("vpc-890ce2e0") #=> true


77
78
79
80
81
82
# File 'lib/ec2/right_ec2_vpc.rb', line 77

def delete_vpc(vpc_id)
  link = generate_request("DeleteVpc", 'VpcId' => vpc_id )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_vpn_connection(vpn_connection_id) ⇒ Object

Delete VPN connection.

ec2.delete_vpn_connection("vpn-a9a643c0") #=> true


391
392
393
394
395
396
# File 'lib/ec2/right_ec2_vpc.rb', line 391

def delete_vpn_connection(vpn_connection_id)
  link = generate_request("DeleteVpnConnection", 'VpnConnectionId' => vpn_connection_id )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_vpn_gateway(vpn_gateway_id) ⇒ Object

Delete vpn gateway.

ec2.delete_vpn_gateway("vgw-dfa144b6") #=> true


333
334
335
336
337
338
# File 'lib/ec2/right_ec2_vpc.rb', line 333

def delete_vpn_gateway(vpn_gateway_id)
  link = generate_request("DeleteVpnGateway", 'VpnGatewayId' => vpn_gateway_id )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#deregister_image(image_id) ⇒ Object

Deregister image at Amazon. Returns true or an exception.

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


196
197
198
199
200
201
202
# File 'lib/ec2/right_ec2_images.rb', line 196

def deregister_image(image_id)
  link = generate_request("DeregisterImage",
                          'ImageId' => image_id.to_s)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#describe_addresses(*list_and_options) ⇒ Object

List elastic IP addresses assigned to your account.

Accepts a list of addresses and/or a set of filters as the last parameter.

Filters: instance-id, public-ip

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

ec2.describe_addresses(:filters => { 'public-ip' => "75.101.154.140" })

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeAddresses.html



271
272
273
# File 'lib/ec2/right_ec2.rb', line 271

def describe_addresses(*list_and_options)
  describe_resources_with_list_and_options('DescribeAddresses', 'PublicIp', QEc2DescribeAddressesParser, list_and_options)
end

#describe_availability_zones(*list_and_options) ⇒ Object

Describes availability zones that are currently available to the account and their states.

Accepts a list of availability zones and/or a set of filters as the last parameter.

Filters: message, region-name, state, zone-name

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

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeAvailabilityZones.html



323
324
325
# File 'lib/ec2/right_ec2.rb', line 323

def describe_availability_zones(*list_and_options)
  describe_resources_with_list_and_options('DescribeAvailabilityZones', 'ZoneName', QEc2DescribeAvailabilityZonesParser, list_and_options)
end

#describe_bundle_tasks(*list_and_options) ⇒ Object

Describe the status of the Windows AMI bundlings.

Accepts a list of tasks and/or a set of filters as the last parameter.

Filters“ bundle-id, error-code, error-message, instance-id, progress, s3-aws-access-key-id, s3-bucket, s3-prefix, start-time, state, update-time

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

 ec2.describe_bundle_tasks(:filters => { 'state' => 'pending' })

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeBundleTasks.html



524
525
526
# File 'lib/ec2/right_ec2_instances.rb', line 524

def describe_bundle_tasks(*list_and_options)
  describe_resources_with_list_and_options('DescribeBundleTasks', 'BundleId', QEc2DescribeBundleTasksParser, list_and_options)
end

#describe_customer_gateways(*list_and_options) ⇒ Object

Describe customer gateways.

Accepts a list of gateways and/or a set of filters as the last parameter.

Filters: bgp-asn, customer-gateway-id, state, type, tag-key, tag-value, tag:key

ec2.describe_customer_gateways #=>
  [{:type=>"ipsec.1",
    :ip_address=>"12.1.2.3",
    :bgp_asn=>"65534",
    :state=>"available",
    :customer_gateway_id=>"cgw-d5a643bc"}]

ec2.describe_customer_gateways(:filters => {'tag:MyTag' => 'MyValue'})

P.S. filters: docs.amazonwebservices.com/AmazonVPC/latest/APIReference/index.html?ApiReference-query-DescribeCustomerGateways.html



230
231
232
# File 'lib/ec2/right_ec2_vpc.rb', line 230

def describe_customer_gateways(*list_and_options)
  describe_resources_with_list_and_options('DescribeCustomerGateways', 'CustomerGatewayId', QEc2DescribeCustomerGatewaysParser, list_and_options)
end

#describe_dhcp_options(*list_and_options) ⇒ Object

Describe DHCP options.

Accepts a list of DHCP options and/or a set of filters as the last parameter.

Filters: dchp-options-id, key, value, tag-key, tag-value, tag:key

ec2.describe_dhcp_options #=>
  [{:dhcp_options_id=>"dopt-cb0de3a2",
  :dhcp_configuration_set=>
   {"netbios-node-type"=>["1"], "domain-name"=>["my.awesomesite.ru"]}}]

ec2.describe_dhcp_options(:filters => {'tag:MyTag' => 'MyValue'})

P.S. filters: docs.amazonwebservices.com/AmazonVPC/latest/APIReference/index.html?ApiReference-query-DescribeDhcpOptions.html



160
161
162
# File 'lib/ec2/right_ec2_vpc.rb', line 160

def describe_dhcp_options(*list_and_options)
  describe_resources_with_list_and_options('DescribeDhcpOptions', 'DhcpOptionsId', QEc2DescribeDhcpOptionsParser, list_and_options)
end

#describe_image_attribute(image_id, attribute = 'launchPermission') ⇒ Object

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

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


208
209
210
211
212
213
214
215
# File 'lib/ec2/right_ec2_images.rb', line 208

def describe_image_attribute(image_id, attribute='launchPermission')
  link = generate_request("DescribeImageAttribute",
                          'ImageId'   => image_id,
                          'Attribute' => attribute)
  request_info(link, QEc2DescribeImageAttributeParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#describe_images(*list_and_options) ⇒ Object

Retrieve a list of images.

Accepts a list of images and/or a set of filters as the last parameter.

Filters: architecture, block-device-mapping.delete-on-termination block-device-mapping.device-name, block-device-mapping.snapshot-id, block-device-mapping.volume-size, description, image-id, image-type, is-public, kernel-id, manifest-location, name, owner-alias, owner-id, platform, product-code, ramdisk-id, root-device-name, root-device-type, state, state-reason-code, state-reason-message, tag-key, tag-value, tag:key, virtualization-type

ec2.describe_images #=>
  [{:description=>"EBS backed Fedora core 8 i386",
    :aws_architecture=>"i386",
    :aws_id=>"ami-c2a3f5d4",
    :aws_image_type=>"machine",
    :root_device_name=>"/dev/sda1",
    :image_class=>"elastic",
    :aws_owner=>"937766719418",
    :aws_location=>"937766719418/EBS backed FC8 i386",
    :aws_state=>"available",
    :block_device_mappings=>
     [{:ebs_snapshot_id=>"snap-829a20eb",
       :ebs_delete_on_termination=>true,
       :device_name=>"/dev/sda1"}],
    :name=>"EBS backed FC8 i386",
    :aws_is_public=>true}, ... ]

ec2.describe_images(:filters => { 'image-type' => 'kernel', 'state' => 'available', 'tag:MyTag' => 'MyValue'})

ec2.describe_images("ari-fda54b94", "ami-2ee80247", "aki-00896a69",
                    :filters => { 'image-type' => 'kernel', 'state' => 'available' }) #=>
  [{:root_device_type=>"instance-store",
    :aws_id=>"aki-00896a69",
    :aws_image_type=>"kernel",
    :aws_location=>
     "karmic-kernel-zul/ubuntu-kernel-2.6.31-300-ec2-i386-20091002-test-04.manifest.xml",
    :virtualization_type=>"paravirtual",
    :aws_state=>"available",
    :aws_owner=>"099720109477",
    :tags=>{},
    :aws_is_public=>true,
    :aws_architecture=>"i386"}]

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeImages.html



93
94
95
96
97
# File 'lib/ec2/right_ec2_images.rb', line 93

def describe_images(*list_and_options)
  list, options = AwsUtils::split_items_and_params(list_and_options)
  cache_for     = (list.right_blank? && options[:filters].right_blank?) ? :describe_images : nil
  ec2_describe_images( {'ImageId'=>list}, options, cache_for)
end

#describe_images_by_executable_by(*list_and_options) ⇒ Object

Retrieve a list of images by image executable by.

Accepts a list of images and/or a set of filters as the last parameter.

Filters: architecture, block-device-mapping.delete-on-termination block-device-mapping.device-name, block-device-mapping.snapshot-id, block-device-mapping.volume-size, description, image-id, image-type, is-public, kernel-id, manifest-location, name, owner-alias, owner-id, platform, product-code, ramdisk-id, root-device-name, root-device-type, state, state-reason-code, state-reason-message, tag-key, tag-value, tag:key, virtualization-type

ec2.describe_images_by_executable_by('522821470517')
ec2.describe_images_by_executable_by('self')
ec2.describe_images_by_executable_by('all', :filters => { 'architecture' => 'i386' })

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeImages.html



137
138
139
140
141
142
# File 'lib/ec2/right_ec2_images.rb', line 137

def describe_images_by_executable_by(*list_and_options)
  list, options = AwsUtils::split_items_and_params(list_and_options)
  list          = ['self'] if list.right_blank?
  cache_for     = (list==['self'] && options[:filters].right_blank?) ? :describe_images_by_executable_by : nil
  ec2_describe_images( {'ExecutableBy'=>list}, options, cache_for)
end

#describe_images_by_owner(*list_and_options) ⇒ Object

Retrieve a list of images by image owner.

Accepts a list of images and/or a set of filters as the last parameter.

Filters: architecture, block-device-mapping.delete-on-termination block-device-mapping.device-name, block-device-mapping.snapshot-id, block-device-mapping.volume-size, description, image-id, image-type, is-public, kernel-id, manifest-location, name, owner-alias, owner-id, platform, product-code, ramdisk-id, root-device-name, root-device-type, state, state-reason-code, state-reason-message, tag-key, tag-value, tag:key, virtualization-type

ec2.describe_images_by_owner('522821470517')
ec2.describe_images_by_owner('self', :filters => { 'block-device-mapping.delete-on-termination' => 'false' })

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeImages.html



114
115
116
117
118
119
# File 'lib/ec2/right_ec2_images.rb', line 114

def describe_images_by_owner(*list_and_options)
  list, options = AwsUtils::split_items_and_params(list_and_options)
  list          = ['self'] if list.right_blank?
  cache_for     = (list==['self'] && options[:filters].right_blank?) ? :describe_images_by_owner : nil
  ec2_describe_images( {'Owner'=>list}, options, cache_for)
end

#describe_instance_attribute(instance_id, attribute) ⇒ Object

Describe instance attribute. Attributes: :instance_type, :kernel, :ramdisk, :user_data, :disable_api_termination, :instance_initiated_shutdown_behavior, :root_device_name, :block_device_mapping

ec2.describe_instance_attribute(instance, "BlockDeviceMapping") #=>
   [{:ebs_delete_on_termination=>true,
     :ebs_volume_id=>"vol-683dc401",
     :device_name=>"/dev/sda1"}]

ec2.describe_instance_attribute(instance, "InstanceType") #=> "m1.small"

ec2.describe_instance_attribute(instance, "InstanceInitiatedShutdownBehavior") #=> "stop"


350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/ec2/right_ec2_instances.rb', line 350

def describe_instance_attribute(instance_id, attribute)
  attribute = INSTANCE_ATTRIBUTE_MAPPING[attribute.to_s] || attribute.to_s
  link = generate_request('DescribeInstanceAttribute',
                          'InstanceId' => instance_id,
                          'Attribute'  => attribute)
  value = request_info(link, QEc2DescribeInstanceAttributeParser.new(:logger => @logger))
  case attribute
  when "userData"
    Base64.decode64(value)
  else
    value
  end
rescue Exception
  on_exception
end

#describe_instances(*list_and_options) ⇒ Object

Retrieve information about EC2 instances.

Accepts a list of instances and/or a set of filters as the last parameter.

Filters: architecture, availability-zone, block-device-mapping.attach-time, block-device-mapping.delete-on-termination, block-device-mapping.device-name, block-device-mapping.status, block-device-mapping.volume-id, client-token, dns-name, group-id, image-id, instance-id, instance-lifecycle, instance-state-code, instance-state-name, instance-type, ip-address, kernel-id, key-name, launch-index, launch-time, monitoring-state, owner-id, placement-group-name, platform, private-dns-name, private-ip-address, product-code, ramdisk-id, reason, requester-id, reservation-id, root-device-name, root-device-type, spot-instance-request-id, state-reason-code, state-reason-message, subnet-id, tag-key, tag-value, tag:key, virtualization-type, vpc-id,

ec2.describe_instances #=>
  [{:private_ip_address=>"10.240.7.99",
    :aws_image_id=>"ami-c2a3f5d4",
    :ip_address=>"174.129.134.109",
    :dns_name=>"ec2-174-129-134-109.compute-1.amazonaws.com",
    :aws_instance_type=>"m1.small",
    :aws_owner=>"826693181925",
    :root_device_name=>"/dev/sda1",
    :instance_class=>"elastic",
    :aws_state=>"running",
    :private_dns_name=>"domU-12-31-39-04-00-95.compute-1.internal",
    :aws_reason=>"",
    :aws_launch_time=>"2009-11-18T14:03:25.000Z",
    :aws_reservation_id=>"r-54d38542",
    :aws_state_code=>16,
    :ami_launch_index=>"0",
    :aws_availability_zone=>"us-east-1a",
    :aws_groups=>["default"],
    :monitoring_state=>"disabled",
    :aws_product_codes=>[],
    :ssh_key_name=>"",
    :block_device_mappings=>
     [{:ebs_status=>"attached",
       :ebs_delete_on_termination=>true,
       :ebs_attach_time=>"2009-11-18T14:03:34.000Z",
       :device_name=>"/dev/sda1",
       :ebs_volume_id=>"vol-e600f98f"},
      {:ebs_status=>"attached",
       :ebs_delete_on_termination=>true,
       :ebs_attach_time=>"2009-11-18T14:03:34.000Z",
       :device_name=>"/dev/sdk",
       :ebs_volume_id=>"vol-f900f990"}],
    :aws_instance_id=>"i-8ce84ae4"} , ... ]

 ec2.describe_instances("i-8ce84ae6", "i-8ce84ae8", "i-8ce84ae0")
 ec2.describe_instances(:filters => { 'availability-zone' => 'us-east-1a', 'instance-type' => 'c1.medium' })

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeInstances.html



102
103
104
105
106
# File 'lib/ec2/right_ec2_instances.rb', line 102

def describe_instances(*list_and_options)
  describe_resources_with_list_and_options('DescribeInstances', 'InstanceId', QEc2DescribeInstancesParser, list_and_options) do |parser|
    get_desc_instances(parser.result)
  end
end

#describe_key_pairs(*list_and_options) ⇒ Object

Retrieve a list of SSH keys.

Accepts a list of ssh keys and/or a set of filters as the last parameter.

Filters: fingerprint, key-name

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

ec2.describe_key_pairs(:filters => {'fingerprint' => ["53:0b:73:c9:c8:18:98:6e:bc:98:9e:51:97:04:74:4b:07:f9:00:00",
                                                      "9f:57:a5:bb:4b:e8:a7:f8:3c:fe:d6:db:41:f5:7e:97:b5:b2:00:00"]})

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html



178
179
180
# File 'lib/ec2/right_ec2.rb', line 178

def describe_key_pairs(*list_and_options)
  describe_resources_with_list_and_options('DescribeKeyPairs', 'KeyName', QEc2DescribeKeyPairParser, list_and_options)
end

#describe_licenses(*license_ids) ⇒ Object



28
29
30
31
# File 'lib/ec2/right_ec2_windows_mobility.rb', line 28

def describe_licenses(*license_ids)
  link = generate_request("DescribeLicenses", amazonize_list('LicenseId', license_ids))
  request_info(link, QEc2DescribeLicensesParser.new(:logger => @logger))
end

#describe_placement_groups(*list_and_options) ⇒ Object

Describe placement groups.

Accepts a list of placement groups and/or a set of filters as the last parameter.

Filters: group-name, state, strategy

If you don’t specify a particular placement group, the response includes information about all of them. The information includes the group name, the strategy, and the group state (e.g., pending, available, etc.).

ec2.describe_placement_groups #=>
  [{:state=>"available", :strategy=>"cluster", :group_name=>"kd_first"},
   {:state=>"available", :strategy=>"cluster", :group_name=>"kd_second"}]

ec2.describe_placement_groups('kd_second') #=>
  [{:strategy=>"cluster", :group_name=>"kd_second", :state=>"available"}]

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference_query_DescribePlacementGroups.html



51
52
53
# File 'lib/ec2/right_ec2_placement_groups.rb', line 51

def describe_placement_groups(*list_and_options)
  describe_resources_with_list_and_options('DescribePlacementGroups', 'GroupName', QEc2DescribePlacementGroupsParser, list_and_options)
end

#describe_regions(*list_and_options) ⇒ Object

Describe regions.

Accepts a list of regions and/or a set of filters as the last parameter.

Filters: endpoint, region-name

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

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRegions.html



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

def describe_regions(*list_and_options)
  describe_resources_with_list_and_options('DescribeRegions', 'RegionName', QEc2DescribeRegionsParser, list_and_options)
end

#describe_reserved_instances(*list_and_options) ⇒ Object

Retrieve reserved instances list.

Accepts a list of reserved instances and/or a set of filters as the last parameter.

Filters: availability-zone, duration, fixed-price, instance-type, product-description, reserved-instances-id, start, state, tag-key, tag-value, tag:key, usage-price

ec2.describe_reserved_instances #=>

  [{:aws_id=>"1ba8e2e3-1c40-434c-a741-5ff16a4c542e",
    :aws_duration=>31536000,
    :aws_instance_type=>"m1.small",
    :aws_usage_price=>0.03,
    :aws_availability_zone=>"us-east-1b",
    :aws_state=>"payment-pending",
    :aws_product_description=>"Test",
    :aws_fixed_price=>325.0,
    :aws_start=>"2009-12-18T20:39:39.569Z"
    :aws_instance_count=>1}]

ec2.describe_reserved_instances(:filters => {'availability-zone' => 'us-east-1a'})

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeReservedInstances.html



55
56
57
# File 'lib/ec2/right_ec2_reserved_instances.rb', line 55

def describe_reserved_instances(*list_and_options)
  describe_resources_with_list_and_options('DescribeReservedInstances', 'ReservedInstancesId', QEc2DescribeReservedInstancesParser, list_and_options)
end

#describe_reserved_instances_offerings(*list_and_options) ⇒ Object

Retrieve reserved instances offerings.

Accepts a list of reserved instances offerings and/or a set of filters as the last parameter.

Filters: availability-zone, duration, fixed-price, instance-type, product-description, reserved-instances-offering-id, usage-price

ec2.describe_reserved_instances_offerings #=>
  [{:aws_instance_type=>"c1.medium",
    :aws_availability_zone=>"us-east-1c",
    :aws_duration=>94608000,
    :aws_product_description=>"Linux/UNIX",
    :aws_id=>"e5a2ff3b-f6eb-4b4e-83f8-b879d7060257",
    :aws_usage_price=>0.06,
    :aws_fixed_price=>1000.0},
    ...
   {:aws_instance_type=>"m1.xlarge",
    :aws_availability_zone=>"us-east-1a",
    :aws_duration=>31536000,
    :aws_product_description=>"Linux/UNIX",
    :aws_id=>"c48ab04c-63ab-4cd6-b8f5-978a29eb9bcc",
    :aws_usage_price=>0.24,
    :aws_fixed_price=>2600.0}]

ec2.describe_reserved_instances_offerings(:filters => {'availability-zone' => 'us-east-1c'})

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeReservedInstancesOfferings.html



86
87
88
# File 'lib/ec2/right_ec2_reserved_instances.rb', line 86

def describe_reserved_instances_offerings(*list_and_options)
  describe_resources_with_list_and_options('DescribeReservedInstancesOfferings', 'ReservedInstancesOfferingId', QEc2DescribeReservedInstancesOfferingsParser, list_and_options)
end

#describe_resources_with_list_and_options(remote_function_name, remote_item_name, parser_class, list_and_options, &block) ⇒ Object

:nodoc:



143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/ec2/right_ec2.rb', line 143

def describe_resources_with_list_and_options(remote_function_name, remote_item_name, parser_class, list_and_options, &block) # :nodoc:
  # 'RemoteFunctionName' -> :remote_funtion_name
  cache_name = remote_function_name.right_underscore.to_sym
  list, options = AwsUtils::split_items_and_params(list_and_options)
  request_hash  = amazonize_list(remote_item_name, list)
  request_hash.merge!(amazonize_list(['Filter.?.Name', 'Filter.?.Value.?'], options[:filters])) unless options[:filters].right_blank?
  cache_for     = (list.right_blank? && options[:filters].right_blank?) ? cache_name : nil
  link = generate_request(remote_function_name, request_hash)
  request_cache_or_info(cache_for, link,  parser_class, @@bench, cache_for, &block)
rescue Exception
  on_exception
end

#describe_security_groups(*list_and_options) ⇒ Object

Retrieve Security Groups information.

Accepts a list of security groups and/or a set of filters as the last parameter.

Filters: description, group-name, ip-permission.cidr, ip-permission.from-port, ip-permission.group-name, ip-permission.protocol, ip-permission.to-port, ip-permission.user-id, owner-id

# Amazon cloud:
ec2 = Rightscale::Ec2.new(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
ec2.describe_security_groups #=>
  [{:aws_perms=>
     [{:group=>"default", :owner=>"048291609141"},
      {:to_port=>"22",
       :protocol=>"tcp",
       :from_port=>"22",
       :cidr_ips=>"0.0.0.0/0"},
      {:to_port=>"9997",
       :protocol=>"tcp",
       :from_port=>"9997",
       :cidr_ips=>"0.0.0.0/0"}],
    :aws_group_name=>"photo_us",
    :aws_description=>"default group",
    :aws_owner=>"826693181925"}]

# Eucalyptus cloud:
ec2 = Rightscale::Ec2.new(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, :eucalyptus => true)
ec2.describe_security_groups #=>
  [{:aws_perms=>
     [{:to_port=>"65535",
       :group=>"default",
       :protocol=>"tcp",
       :owner=>"048291609141",
       :from_port=>"1"},
      {:to_port=>"65535",
       :group=>"default",
       :protocol=>"udp",
       :owner=>"048291609141",
       :from_port=>"1"},
      {:to_port=>"-1",
       :group=>"default",
       :protocol=>"icmp",
       :owner=>"048291609141",
       :from_port=>"-1"},
      {:to_port=>"22",
       :protocol=>"tcp",
       :from_port=>"22",
       :cidr_ip=>"0.0.0.0/0"},
      {:to_port=>"9997",
       :protocol=>"tcp",
       :from_port=>"9997",
       :cidr_ip=>"0.0.0.0/0"}],
    :aws_group_name=>"photo_us",
    :aws_description=>"default group",
    :aws_owner=>"826693181925"}]

ec2.describe_security_groups(:filters => {'ip-permission.from-port' => '22'})

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSecurityGroups.html



91
92
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
# File 'lib/ec2/right_ec2_security_groups.rb', line 91

def describe_security_groups(*list_and_options)
  describe_resources_with_list_and_options('DescribeSecurityGroups', 'GroupName', QEc2DescribeSecurityGroupsParser, list_and_options) do |parser|
    result = []
    parser.result.each do |item|
      result_item = { :aws_owner       => item[:owner_id],
                      :aws_group_name  => item[:group_name],
                      :aws_description => item[:group_description] }
      aws_perms = []
      item[:ip_permissions].each do |permission|
        result_perm = {}
        result_perm[:from_port] = permission[:from_port]
        result_perm[:to_port]   = permission[:to_port]
        result_perm[:protocol]  = permission[:ip_protocol]
        # IP permissions
        Array(permission[:ip_ranges]).each do |ip_range|
          perm = result_perm.dup
          perm[:cidr_ips] = ip_range
          aws_perms << perm
        end
        # Group permissions
        Array(permission[:groups]).each do |group|
          perm = result_perm.dup
          perm[:group] = group[:group_name]
          perm[:owner] = group[:user_id]
          aws_perms << perm
        end
      end
      result_item[:aws_perms] = aws_perms.uniq
      result << result_item
    end
    result
  end
end

#describe_snapshot_attribute(snapshot_id, attribute = 'createVolumePermission') ⇒ Object

Describe snapshot attribute.

ec2.describe_snapshot_attribute('snap-36fe435f') #=>
  {:create_volume_permission=>
     {:users=>["826690000000", "826690000001"], :groups=>['all']}}


249
250
251
252
253
254
255
256
# File 'lib/ec2/right_ec2_ebs.rb', line 249

def describe_snapshot_attribute(snapshot_id, attribute='createVolumePermission')
  link = generate_request("DescribeSnapshotAttribute",
                          'SnapshotId'=> snapshot_id,
                          'Attribute' => attribute)
  request_info(link, QEc2DescribeSnapshotAttributeParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#describe_snapshots(*list_and_options) ⇒ Object

Describe EBS snapshots.

Accepts a list of snapshots and/or a set of filters as the last parameter.

Filters: description, owner-alias, owner-id, progress, snapshot-id, start-time, status, tag-key, tag-value, tag:key, volume-id, volume-size

ec2.describe_snapshots #=>
 [ {:aws_volume_id=>"vol-545fac3d",
    :aws_description=>"Wikipedia XML Backups (Linux)",
    :aws_progress=>"100%",
    :aws_started_at=>"2009-09-28T23:49:50.000Z",
    :aws_owner=>"amazon",
    :aws_id=>"snap-8041f2e9",
    :aws_volume_size=>500,
    :aws_status=>"completed"},
   {:aws_volume_id=>"vol-185fac71",
    :aws_description=>"Sloan Digital Sky Survey DR6 Subset (Linux)",
    :aws_progress=>"100%",
    :aws_started_at=>"2009-09-28T23:56:10.000Z",
    :aws_owner=>"amazon",
    :aws_id=>"snap-3740f35e",
    :aws_volume_size=>180,
    :aws_status=>"completed"}, ...]

ec2.describe_snapshots(:filters => {'tag:MyTag' => 'MyValue'))

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeSnapshots.html



175
176
177
# File 'lib/ec2/right_ec2_ebs.rb', line 175

def describe_snapshots(*list_and_options)
  describe_resources_with_list_and_options('DescribeSnapshots', 'SnapshotId', QEc2DescribeSnapshotsParser, list_and_options)
end

#describe_spot_datafeed_subscriptionObject

Describe the data feed for Spot Instances.

ec2.describe_spot_datafeed_subscription #=>
  { :owner_id=>"826693181925",
    :bucket=>"bucket-for-konstantin-eu",
    :prefix=>"splogs/",
    :state=>"Active"}


291
292
293
294
# File 'lib/ec2/right_ec2_spot_instances.rb', line 291

def describe_spot_datafeed_subscription
  link = generate_request("DescribeSpotDatafeedSubscription")
  request_info(link, QEc2DescribeSpotDatafeedSubscriptionParser.new(:logger => @logger))
end

#describe_spot_instance_requests(*list_and_options) ⇒ Object

Describe Spot Instance requests.

Accepts a list of requests and/or a set of filters as the last parameter.

Filters: availability-zone-group, create-time, fault-code, fault-message, instance-id, launch-group, launch.block-device-mapping.delete-on-termination, launch.block-device-mapping.device-name, launch.block-device-mapping.snapshot-id, launch.group-id, launch.image-id, launch.instance-type, launch.kernel-id, launch.key-name, launch.monitoring-enabled, launch.ramdisk-id, product-description, spot-instance-request-id, spot-price, state, tag-key, tag-value, tag:key, type, valid-from, valid-until

ec2.describe_spot_instance_requests #=>
  [{:type=>"one-time",
    :create_time=>"2010-03-10T10:30:32.000Z",
    :instance_type=>"c1.medium",
    :state=>"cancelled",
    :groups=>["default"],
    :product_description=>"Linux/UNIX",
    :spot_instance_request_id=>"sir-bfa06804",
    :image_id=>"ami-08f41161",
    :spot_price=>0.01,
    :monitoring_enabled=>false},
   {:type=>"one-time",
    :create_time=>"2010-03-10T10:33:29.000Z",
    :instance_type=>"c1.medium",
    :state=>"open",
    :groups=>["default", "33"],
    :product_description=>"Linux/UNIX",
    :spot_instance_request_id=>"sir-b1713a03",
    :image_id=>"ami-08f41161",
    :spot_price=>0.01,
    :monitoring_enabled=>false,
    :key_name=>"tim"},
   {:type=>"one-time",
    :instance_id=>"i-c516ceae",
    :create_time=>"2010-03-10T10:43:48.000Z",
    :instance_type=>"c1.medium",
    :state=>"active",
    :groups=>["default", "33"],
    :product_description=>"Linux/UNIX",
    :spot_instance_request_id=>"sir-5eb6c604",
    :image_id=>"ami-08f41161",
    :spot_price=>0.2,
    :monitoring_enabled=>false,
    :key_name=>"tim"}]

ec2.describe_spot_instance_requests(:filters => {'type'=>"one-time", 'state'=>"open"})

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeSpotInstanceRequests.html



139
140
141
# File 'lib/ec2/right_ec2_spot_instances.rb', line 139

def describe_spot_instance_requests(*list_and_options)
  describe_resources_with_list_and_options('DescribeSpotInstanceRequests', 'SpotInstanceRequestId', QEc2DescribeSpotInstanceParser, list_and_options)
end

#describe_spot_price_history(options = {}) ⇒ Object

Describe Spot Price history.

Options: :start_time, :end_time, instance_types, product_description

Filters: instance-type, product-description, spot-price, timestamp

ec2.describe_spot_price_history #=>
  [{:spot_price=>0.054,
    :timestamp=>"2009-12-07T12:12:58.000Z",
    :product_description=>"Windows",
    :instance_type=>"m1.small"},
   {:spot_price=>0.06,
    :timestamp=>"2009-12-07T12:18:32.000Z",
    :product_description=>"Linux/UNIX",
    :instance_type=>"c1.medium"},
   {:spot_price=>0.198,
    :timestamp=>"2009-12-07T12:58:00.000Z",
    :product_description=>"Windows",
    :instance_type=>"m1.large"},
   {:spot_price=>0.028,
    :timestamp=>"2009-12-07T13:48:50.000Z",
    :product_description=>"Linux/UNIX",
    :instance_type=>"m1.small"}, ... ]

ec2.describe_spot_price_history(:start_time => 1.day.ago,
                                :end_time => 10.minutes.ago,
                                :instance_types => ["c1.medium", "m1.small"],
                                :product_description => "Linux/UNIX" ) #=>
  [{:product_description=>"Linux/UNIX",
    :timestamp=>"2010-02-04T05:44:36.000Z",
    :spot_price=>0.031,
    :instance_type=>"m1.small"},
   {:product_description=>"Linux/UNIX",
    :timestamp=>"2010-02-04T17:56:25.000Z",
    :spot_price=>0.058,
    :instance_type=>"c1.medium"}, ... ]

ec2.describe_spot_price_history(:filters => {'spot-price' => '0.2' })

ec2.describe_spot_price_history(:instance_types => ["c1.medium"], :filters => {'spot-price' => '0.2' })

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeSpotPriceHistory.html



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

def describe_spot_price_history(options={})
  options = options.dup
  request_hash = {}
  request_hash.merge!(amazonize_list(['Filter.?.Name', 'Filter.?.Value.?'], options[:filters])) unless options[:filters].right_blank?
  request_hash['StartTime']          = AwsUtils::utc_iso8601(options[:start_time])      unless options[:start_time].right_blank?
  request_hash['EndTime']            = AwsUtils::utc_iso8601(options[:end_time])        unless options[:end_time].right_blank?
  request_hash['ProductDescription'] = options[:product_description]                   unless options[:product_description].right_blank?
  request_hash.merge!(amazonize_list('InstanceType', Array(options[:instance_types]))) unless options[:instance_types].right_blank?
  link = generate_request("DescribeSpotPriceHistory", request_hash)
  request_info(link, QEc2DescribeSpotPriceHistoryParser.new)
rescue Exception
  on_exception
end

#describe_subnets(*list_and_options) ⇒ Object

Describe Subnet.

Accepts a list of subnets and/or a set of filters as the last parameter.

Filters: availability-zone, available-ip-address-count, cidr, state, subnet-id, tag-key, tag-value, tag:key, vpc-id

ec2.describe_subnets #=>
  [{:available_ip_address_count=>"251",
    :vpc_id=>"vpc-890ce2e0",
    :availability_zone=>"us-east-1a",
    :subnet_id=>"subnet-770de31e",
    :cidr_block=>"10.0.1.0/24",
    :state=>"available"}]

ec2.describe_subnets(:filters => {'cidr' => "192.168.1.128/25"})

P.S. filters: docs.amazonwebservices.com/AmazonVPC/latest/APIReference/index.html?ApiReference-query-DescribeSubnets.html



106
107
108
# File 'lib/ec2/right_ec2_vpc.rb', line 106

def describe_subnets(*list_and_options)
  describe_resources_with_list_and_options('DescribeSubnets', 'SubnetId', QEc2DescribeSubnetsParser, list_and_options)
end

#describe_tags(options = {}) ⇒ Object

Describe tags.

Accepts set of filters.

Filters: key, resource-id, resource-type, value

ec2.describe_tags  #=> [{:resource_id   => "i-12345678",
                         :value         => "foo",
                         :resource_type => "instance",
                         :key           => "myKey"}]

ec2.describe_tags(:filters => { 'resource-id' => "i-12345678"})

P.S. filters: docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference_query_DescribeTags.html



45
46
47
48
49
50
51
52
53
# File 'lib/ec2/right_ec2_tags.rb', line 45

def describe_tags(options={})
  request_hash = {}
  request_hash.merge!(amazonize_list(['Filter.?.Name', 'Filter.?.Value.?'], options[:filters])) unless options[:filters].right_blank?
  cache_for = (options[:filters].right_blank?) ? :describe_tags : nil
  link = generate_request("DescribeTags", request_hash)
  request_cache_or_info cache_for, link,  QEc2DescribeTagsParser, @@bench, cache_for
rescue Exception
  on_exception
end

#describe_volumes(*list_and_options) ⇒ Object

Describe EBS volumes.

Accepts a list of volumes and/or a set of filters as the last parameter.

Filters: attachement.attach-time, attachment.delete-on-termination, attachement.device, attachment.instance-id, attachment.status, availability-zone, create-time, size, snapshot-id, status, tag-key, tag-value, tag:key, volume-id

ec2.describe_volumes #=>
    [{:aws_size              => 94,
      :aws_device            => "/dev/sdc",
      :aws_attachment_status => "attached",
      :zone                  => "merlot",
      :snapshot_id           => nil,
      :aws_attached_at       => "2008-06-18T08:19:28.000Z",
      :aws_status            => "in-use",
      :aws_id                => "vol-60957009",
      :aws_created_at        => "2008-06-18T08:19:20.000Z",
      :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,}, ... ]

ec2.describe_volumes(:filters => { 'availability-zone' => 'us-east-1a', 'size' => '10' })

P.S. filters: http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeVolumes.html


61
62
63
# File 'lib/ec2/right_ec2_ebs.rb', line 61

def describe_volumes(*list_and_options)
  describe_resources_with_list_and_options('DescribeVolumes', 'VolumeId', QEc2DescribeVolumesParser, list_and_options)
end

#describe_vpcs(*list_and_options) ⇒ Object

Describe VPCs.

Accepts a list of vpcs and/or a set of filters as the last parameter.

Filters: cidr, dchp-options-id, state, tag-key, tag-value, tag:key, vpc-id

ec2.describe_vpcs #=>
  [{:vpc_id=>"vpc-890ce2e0",
    :dhcp_options_id=>"default",
    :cidr_block=>"10.0.0.0/23",
    :state=>"available"}]

ec2.describe_vpcs("vpc-890ce2e0")

ec2.describe_vpcs( :filters => {'tag:MyTag' => 'MyValue'} )

ec2.describe_vpcs( :filters => {'cidr' => "192.168.1.0/24"} )

P.S. filters: docs.amazonwebservices.com/AmazonVPC/latest/APIReference/index.html?ApiReference-query-DescribeVpcs.html



54
55
56
# File 'lib/ec2/right_ec2_vpc.rb', line 54

def describe_vpcs(*list_and_options)
  describe_resources_with_list_and_options('DescribeVpcs', 'VpcId', QEc2DescribeVpcsParser, list_and_options)
end

#describe_vpn_connections(*list_and_options) ⇒ Object

Describe VPN connections.

Accepts a list of VPN gateways and/or a set of filters as the last parameter.

Filters: customer-gateway-configuration, customer-gateway-id, state, tag-key, tag-value, tag:key, type, vpn-connection-id, vpn-gateway-id

ec2.describe_vpn_connections #=>
  [{:type=>"ipsec.1",
    :vpn_connection_id=>"vpn-a9a643c0",
    :customer_gateway_configuration=>
     "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<vpn_connection id=\"vpn-a9a643c0\">\n...</vpn_connection>\n",
    :state=>"available",
    :vpn_gateway_id=>"vgw-dfa144b6",
    :customer_gateway_id=>"cgw-81a643e8"}]

ec2.describe_vpn_gateways(:filters => {'tag:MyTag' => 'MyValue'})

P.S. filters: docs.amazonwebservices.com/AmazonVPC/latest/APIReference/index.html?ApiReference-query-DescribeVpnConnections.html



364
365
366
# File 'lib/ec2/right_ec2_vpc.rb', line 364

def describe_vpn_connections(*list_and_options)
  describe_resources_with_list_and_options('DescribeVpnConnections', 'VpnConnectionId', QEc2DescribeVpnConnectionsParser, list_and_options)
end

#describe_vpn_gateways(*list_and_options) ⇒ Object

Describe VPN gateways.

Accepts a list of VPN gateways and/or a set of filters as the last parameter.

Filters: attachment.state, attachment.vpc-id, availability-zone, state, tag-key, tag-value, tag:key, type, vpn-gateway-id

ec2.describe_vpn_gateways #=>
  [{:type=>"ipsec.1",
    :availability_zone=>"us-east-1a",
    :attachments=>[{:vpc_id=>"vpc-890ce2e0", :state=>"attached"}],
    :vpn_gateway_id=>"vgw-dfa144b6"}]

ec2.describe_vpn_gateways(:filters => {'tag:MyTag' => 'MyValue'})

P.S. filters: docs.amazonwebservices.com/AmazonVPC/latest/APIReference/index.html?ApiReference-query-DescribeVpnGateways.html



283
284
285
# File 'lib/ec2/right_ec2_vpc.rb', line 283

def describe_vpn_gateways(*list_and_options)
  describe_resources_with_list_and_options('DescribeVpnGateways', 'VpnGatewayId', QEc2DescribeVpnGatewaysParser, list_and_options)
end

#detach_volume(volume_id, instance_id = nil, device = nil, force = nil) ⇒ Object

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


129
130
131
132
133
134
135
136
137
138
139
# File 'lib/ec2/right_ec2_ebs.rb', line 129

def detach_volume(volume_id, instance_id=nil, device=nil, force=nil)
  hash = { "VolumeId" => volume_id.to_s }
  hash["InstanceId"] = instance_id.to_s unless instance_id.right_blank?
  hash["Device"]     = device.to_s      unless device.right_blank?
  hash["Force"]      = 'true'           if     force
  #
  link = generate_request("DetachVolume", hash)
  request_info(link, QEc2AttachAndDetachVolumeParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#detach_vpn_gateway(vpn_gateway_id, vpc_id) ⇒ Object

Detach VPN gateway.

ec2.detach_vpn_gateway('vgw-dfa144b6','vpc-890ce2e0') #=> true


321
322
323
324
325
326
327
# File 'lib/ec2/right_ec2_vpc.rb', line 321

def detach_vpn_gateway(vpn_gateway_id, vpc_id)
  link = generate_request("DetachVpnGateway", 'VpnGatewayId' => vpn_gateway_id,
                                              'VpcId'        => vpc_id )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
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


280
281
282
283
284
285
286
# File 'lib/ec2/right_ec2.rb', line 280

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

#ec2_describe_images(params = {}, options = {}, cache_for = nil) ⇒ Object

Describe images helper params:

{ 'ImageId'      => ['id1', ..., 'idN'],
  'Owner'        => ['self', ..., 'userN'],
  'ExecutableBy' => ['self', 'all', ..., 'userN']
}


38
39
40
41
42
43
44
45
46
# File 'lib/ec2/right_ec2_images.rb', line 38

def ec2_describe_images(params={}, options={}, cache_for=nil) #:nodoc:
  request_hash = {}
  params.each { |list_by, list| request_hash.merge! amazonize_list(list_by, Array(list)) }
  request_hash.merge!(amazonize_list(['Filter.?.Name', 'Filter.?.Value.?'], options[:filters])) unless options[:filters].right_blank?
  link = generate_request("DescribeImages", request_hash)
  request_cache_or_info cache_for, link,  QEc2DescribeImagesParser, @@bench, cache_for
rescue Exception
  on_exception
end

#edit_security_group(action, group_name, params) ⇒ Object

Edit AWS/Eucaliptus security group permissions.

Options:
  action      - :authorize (or :grant) | :revoke (or :remove)
  group_name  - security group name
  permissions - a combination of options below:
    :source_group_owner => UserId
    :source_group       => GroupName
    :from_port          => from port
    :to_port            => to port
    :port               => set both :from_port and to_port with the same value
    :protocol           => :tcp | :udp | :icmp
    :cidr_ip            => '0.0.0.0/0'

ec2.edit_security_group( :grant,
                         'kd-sg-test',
                         :source_group       => "sketchy",
                         :source_group_owner => "600000000006",
                         :protocol           => 'tcp',
                         :port               => '80',
                         :cidr_ip            => '127.0.0.1/32') #=> true

P.S. This method is deprecated for AWS and but still good for Eucaliptus clouds. Use modify_security_group_ingress method for AWS clouds.



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/ec2/right_ec2_security_groups.rb', line 177

def edit_security_group(action, group_name, params)
  hash = {}
  case action
  when :authorize, :grant then action = "AuthorizeSecurityGroupIngress"
  when :revoke, :remove   then action = "RevokeSecurityGroupIngress"
  else raise "Unknown action #{action.inspect}!"
  end
  hash['GroupName']                  = group_name
  hash['SourceSecurityGroupName']    = params[:source_group]                         unless params[:source_group].right_blank?
  hash['SourceSecurityGroupOwnerId'] = params[:source_group_owner].to_s.gsub(/-/,'') unless params[:source_group_owner].right_blank?
  hash['IpProtocol']                 = params[:protocol]                             unless params[:protocol].right_blank?
  unless params[:port].right_blank?
    hash['FromPort'] = params[:port]
    hash['ToPort']   = params[:port]
  end
  hash['FromPort']   = params[:from_port] unless params[:from_port].right_blank?
  hash['ToPort']     = params[:to_port]   unless params[:to_port].right_blank?
  hash['CidrIp']     = params[:cidr_ip]   unless params[:cidr_ip].right_blank?
  #
  link = generate_request(action, hash)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

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

:nodoc:



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

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

#get_console_output(instance_id) ⇒ Object

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 ([email protected]) (gcc version 4.0.1 20050727 ..."


308
309
310
311
312
313
# File 'lib/ec2/right_ec2_instances.rb', line 308

def get_console_output(instance_id)
  link = generate_request("GetConsoleOutput", { 'InstanceId.1' => instance_id })
  request_info(link, QEc2GetConsoleOutputParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#get_desc_instances(instances) ⇒ Object


Instances



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ec2/right_ec2_instances.rb', line 32

def get_desc_instances(instances)  # :nodoc:
  result = []
  instances.each do |reservation|
    reservation[:instances_set].each do |instance|
      # Parse and remove timestamp from the reason string. The timestamp is of
      # the request, not when EC2 took action, thus confusing & useless...
      instance[:aws_reason]         = instance[:aws_reason].sub(/\(\d[^)]*GMT\) */, '')
      instance[:aws_owner]          = reservation[:aws_owner]
      instance[:aws_reservation_id] = reservation[:aws_reservation_id]
      instance[:aws_groups]         = reservation[:aws_groups]
      result << instance
    end
  end
  result
rescue Exception
  on_exception
end

#get_initial_password(instance_id, private_key) ⇒ Object

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"


426
427
428
429
430
431
432
433
434
435
436
# File 'lib/ec2/right_ec2_instances.rb', line 426

def get_initial_password(instance_id, private_key)
  console_output = get_console_output(instance_id)
  crypted_password = console_output[:aws_output][%r{<Password>(.+)</Password>}m] && $1
  unless crypted_password
    raise AwsError.new("Initial password was not found in console output for #{instance_id}")
  else
    OpenSSL::PKey::RSA.new(private_key).private_decrypt(Base64.decode64(crypted_password))
  end
rescue Exception
  on_exception
end

#get_initial_password_v2(instance_id, private_key) ⇒ Object

Get Initial windows instance password using Amazon API call GetPasswordData.

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

P.S. To say the truth there is absolutely no any speedup if to compare to the old get_initial_password method… ;(



444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/ec2/right_ec2_instances.rb', line 444

def get_initial_password_v2(instance_id, private_key)
  link = generate_request('GetPasswordData',
                          'InstanceId' => instance_id )
  response = request_info(link, QEc2GetPasswordDataParser.new(:logger => @logger))
  if response[:password_data].right_blank?
    raise AwsError.new("Initial password is not yet created for #{instance_id}")
  else
    OpenSSL::PKey::RSA.new(private_key).private_decrypt(Base64.decode64(response[:password_data]))
  end
rescue Exception
  on_exception
end

#import_key_pair(name, public_key_material) ⇒ Object

Import new SSH key. Returns a hash of the key’s data or an exception.

ec2.import_key_pair('my_awesome_key', 'C:\keys\myfavoritekeypair_public.ppk') #=>
  {: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"}


188
189
190
191
192
193
194
195
# File 'lib/ec2/right_ec2.rb', line 188

def import_key_pair(name, public_key_material)
  link = generate_request("ImportKeyPair",
                          'KeyName' => name.to_s,
                          'PublicKeyMaterial' => Base64.encode64(public_key_material.to_s))
  request_info(link, QEc2ImportKeyPairParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#launch_instances(image_id, options = {}) ⇒ Object

Launch new EC2 instances. Options: :image_id, :addressing_type, :min_count, max_count, :key_name, :kernel_id, :ramdisk_id, :availability_zone, :monitoring_enabled, :subnet_id, :disable_api_termination, :instance_initiated_shutdown_behavior, :block_device_mappings, :placement_group_name, :license_pool

Returns a list of launched instances or an exception.

ec2.launch_instances( 'ami-c2a3f5d4',
                      :min_count => 1,
                      :group_ids => 'default',
                      :user_data => 'Ohoho!',
                      :availability_zone => "us-east-1a",
                      :disable_api_termination => true,
                      :instance_initiated_shutdown_behavior => 'terminate',
                      :block_device_mappings => [ {:ebs_snapshot_id=>"snap-7360871a",
                                                   :ebs_delete_on_termination=>true,
                                                   :device_name => "/dev/sdk",
                                                   :virtual_name => "mystorage"} ] ) #=>
  [{:aws_image_id=>"ami-c2a3f5d4",
    :dns_name=>"",
    :aws_instance_type=>"m1.small",
    :aws_owner=>"826693181925",
    :root_device_name=>"/dev/sda1",
    :instance_class=>"elastic",
    :state_reason_code=>0,
    :aws_state=>"pending",
    :private_dns_name=>"",
    :aws_reason=>"",
    :aws_launch_time=>"2009-11-18T14:03:25.000Z",
    :aws_reservation_id=>"r-54d38542",
    :state_reason_message=>"pending",
    :aws_state_code=>0,
    :ami_launch_index=>"0",
    :aws_availability_zone=>"us-east-1a",
    :aws_groups=>["default"],
    :monitoring_state=>"disabled",
    :aws_product_codes=>[],
    :ssh_key_name=>"",
    :aws_instance_id=>"i-8ce84ae4"}]


207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/ec2/right_ec2_instances.rb', line 207

def launch_instances(image_id, options={})
  options[:image_id]    = image_id
  options[:min_count] ||= 1
  options[:max_count] ||= options[:min_count]
  params = prepare_instance_launch_params(options)
  # Log debug information
  @logger.info("Launching instance of image #{image_id}. Options: #{params.inspect}")
  link = generate_request("RunInstances", params)
  instances = request_info(link, QEc2DescribeInstancesParser.new(:logger => @logger))
  get_desc_instances(instances)
rescue Exception
  on_exception
end

#modify_image_attribute(image_id, attribute, operation_type = nil, vars = {}) ⇒ Object

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


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

def modify_image_attribute(image_id, attribute, operation_type = nil, vars = {})
  params =  {'ImageId'   => image_id,
             'Attribute' => attribute}
  params['OperationType'] = operation_type if operation_type
  params.update(amazonize_list('UserId',      vars[:user_id]))      if vars[:user_id]
  params.update(amazonize_list('UserGroup',   vars[:user_group]))   if vars[:user_group]
  params.update(amazonize_list('ProductCode', vars[:product_code])) if vars[:product_code]
  link = generate_request("ModifyImageAttribute", params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_image_launch_perm_add_groups(image_id, user_group = ['all']) ⇒ Object

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


276
277
278
# File 'lib/ec2/right_ec2_images.rb', line 276

def modify_image_launch_perm_add_groups(image_id, user_group=['all'])
  modify_image_attribute(image_id, 'launchPermission', 'add', :user_group => user_group)
end

#modify_image_launch_perm_add_users(image_id, user_id = []) ⇒ Object

Grant image launch permissions to users. Parameter user_id 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


259
260
261
# File 'lib/ec2/right_ec2_images.rb', line 259

def modify_image_launch_perm_add_users(image_id, user_id=[])
  modify_image_attribute(image_id, 'launchPermission', 'add', :user_id => user_id)
end

#modify_image_launch_perm_remove_groups(image_id, user_group = ['all']) ⇒ Object

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


284
285
286
# File 'lib/ec2/right_ec2_images.rb', line 284

def modify_image_launch_perm_remove_groups(image_id, user_group=['all'])
  modify_image_attribute(image_id, 'launchPermission', 'remove', :user_group => user_group)
end

#modify_image_launch_perm_remove_users(image_id, user_id = []) ⇒ Object

Revokes image launch permissions for users. user_id 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


267
268
269
# File 'lib/ec2/right_ec2_images.rb', line 267

def modify_image_launch_perm_remove_users(image_id, user_id=[])
  modify_image_attribute(image_id, 'launchPermission', 'remove', :user_id => user_id)
end

#modify_image_product_code(image_id, product_code = []) ⇒ Object

Add product code to image

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


292
293
294
# File 'lib/ec2/right_ec2_images.rb', line 292

def modify_image_product_code(image_id, product_code=[])
  modify_image_attribute(image_id, 'productCodes', nil, :product_code => product_code)
end

#modify_instance_attribute(instance_id, attribute, value) ⇒ Object

Modify instance attribute. Attributes: :instance_type, :kernel, :ramdisk, :user_data, :disable_api_termination, :instance_initiated_shutdown_behavior, :root_device_name, :block_device_mapping

ec2.modify_instance_attribute(instance, :instance_initiated_shutdown_behavior, "stop") #=> true


386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/ec2/right_ec2_instances.rb', line 386

def modify_instance_attribute(instance_id, attribute, value)
  attribute = INSTANCE_ATTRIBUTE_MAPPING[attribute.to_s] || attribute.to_s
  params = { 'InstanceId' => instance_id,
             'Attribute'  => attribute }
  case attribute
  when "blockDeviceMapping"
    params.merge!(amazonize_block_device_mappings(value))
  when "userData"
    params['Value'] = Base64.encode64(value).delete("\n")
  else
    params['Value'] = value
  end
  link = generate_request('ModifyInstanceAttribute', params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_security_group_ingress(action, group_name, permissions) ⇒ Object

Modify AWS security group permissions.

Options:
  action      - :authorize (or :grant) | :revoke (or :remove)
  group_name  - security group name
  permissions - a combination of options below:
    # Ports:
    :from_port          => from port
    :to_port            => to port
    :port               => set both :from_port and to_port with the same value
    # Protocol
    :protocol           => :tcp | :udp | :icmp
    # Group(s)
    :source_group_owner => UserId
    :source_group       => GroupName
    # or
    :source_groups      => { UserId1 => GroupName1, UserName2 => GroupName2 }
    :source_groups      => [ [ UserId1, GroupName1 ], [ UserName2 => GroupName2 ] ]
    # CidrIp(s)
    :cidr_ip            => '0.0.0.0/0'
    :cidr_ips           => ['1.1.1.1/1', '2.2.2.2/2']

# CidrIP based permissions:

ec2.modify_security_group_ingress(:authorize, 'my_cool_group',
                                  :cidr_ip  =>  "127.0.0.0/31",
                                  :port     => 811,
                                  :protocol => 'tcp' ) #=> true

ec2.modify_security_group_ingress(:revoke, 'my_cool_group',
                                  :cidr_ips =>  ["127.0.0.1/32", "127.0.0.2/32"],
                                  :port     => 812,
                                  :protocol => 'tcp' ) #=> true

# Group based permissions:

ec2.modify_security_group_ingress(:authorize, 'my_cool_group',
                                  :source_group_owner => "586789340000",
                                  :source_group =>  "sketchy-us",
                                  :port         => 800,
                                  :protocol     => 'tcp' ) #=> true

ec2.modify_security_group_ingress(:authorize, 'my_cool_group',
                                  :source_groups => { "586789340000" => "sketchy-us",
                                                      "635201710000" => "sketchy" },
                                  :port          => 801,
                                  :protocol      => 'tcp' ) #=> true

ec2.modify_security_group_ingress(:revoke, 'my_cool_group',
                                  :source_groups => [[ "586789340000", "sketchy-us" ],
                                                     [ "586789340000", "default" ]],
                                  :port          => 809,
                                  :protocol      => 'tcp' ) #=> true

# +Permissions+ can be an array of permission hashes:

ec2.modify_security_group_ingress(:authorize, 'my_cool_group',
                                  [{ :source_groups => { "586789340000" => "sketchy-us",
                                                         "635201710000" => "sketchy" },
                                     :port          => 803,
                                     :protocol      => 'tcp'},
                                   { :cidr_ips      =>  ["127.0.0.1/32", "127.0.0.2/32"],
                                     :port          => 812,
                                     :protocol      => 'tcp' }]) #=> true


267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/ec2/right_ec2_security_groups.rb', line 267

def modify_security_group_ingress(action, group_name, permissions)
  hash = {}
  case action
  when :authorize, :grant then action = "AuthorizeSecurityGroupIngress"
  when :revoke, :remove   then action = "RevokeSecurityGroupIngress"
  else                         raise "Unknown action #{action.inspect}!"
  end
  # Group Name
  hash["GroupName"] = group_name
  #
  permissions = [permissions] unless permissions.is_a?(Array)
  permissions.each_with_index do |permission, idx|
    pid = idx+1
    # Protocol
    hash["IpPermissions.#{pid}.IpProtocol"] = permission[:protocol]
    # Port
    unless permission[:port].right_blank?
      hash["IpPermissions.#{pid}.FromPort"] = permission[:port]
      hash["IpPermissions.#{pid}.ToPort"]   = permission[:port]
    else
      hash["IpPermissions.#{pid}.FromPort"] = permission[:from_port]
      hash["IpPermissions.#{pid}.ToPort"]   = permission[:to_port]
    end
    # Source Group(s)
    # Old way (if it is used):
    # :source_group_owner => UserId, :source_group => GroupName 
    if !permission[:source_group].right_blank? && !permission[:source_group_owner].right_blank?
      permission[:source_groups] = { permission[:source_group_owner] => permission[:source_group]} 
    end
#        # Fix UserId(s): '0000-0000-0000' => '000000000000'
#        permission[:source_groups] = Array(permission[:source_groups])
#        permission[:source_groups].each do |item|
#          item[0] = item[0].to_s.gsub(/-/,'')
#        end
    # New way:
    #  :source_groups => {UserId1 => GroupName1, ... UserIdN => GroupNameN}
    #  or (this allows using same UserId multiple times )
    #  :source_groups => [[UserId1, GroupName1], ... [UserIdN, GroupNameN]]  
    hash.merge!(amazonize_list( ["IpPermissions.#{pid}.Groups.?.UserId",
                                 "IpPermissions.#{pid}.Groups.?.GroupName"],
                                  permission[:source_groups] ))
    # CidrIp(s)
    cidr_ips   = permission[:cidr_ips] unless permission[:cidr_ips].right_blank?
    cidr_ips ||= permission[:cidr_ip]  unless permission[:cidr_ip].right_blank?
    hash.merge!(amazonize_list("IpPermissions.1.IpRanges.?.CidrIp", cidr_ips))
  end
  #
  link = generate_request(action, hash)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_snapshot_attribute(snapshot_id, attribute = 'createVolumePermission', operation_type = 'add', vars = {}) ⇒ Object

Modify snapshot attribute.

attribute      : currently, only 'createVolumePermission' is supported.
operation_type : currently, only 'add' & 'remove' are supported.
vars:
  :user_group  : currently, only 'all' is supported.
  :user_id     : an array of user ids


279
280
281
282
283
284
285
286
287
288
289
# File 'lib/ec2/right_ec2_ebs.rb', line 279

def modify_snapshot_attribute(snapshot_id, attribute='createVolumePermission', operation_type='add', vars = {})
  params =  {'SnapshotId'    => snapshot_id,
             'Attribute'     => attribute,
             'OperationType' => operation_type}
  params.update(amazonize_list('UserId',    Array(vars[:user_id])))    if vars[:user_id]
  params.update(amazonize_list('UserGroup', Array(vars[:user_group]))) if vars[:user_group]
  link = generate_request("ModifySnapshotAttribute", params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_snapshot_attribute_create_volume_permission_add_groups(snapshot_id, *user_group) ⇒ Object

Grant create volume permission for user groups (currently only ‘all’ is supported).

ec2.modify_snapshot_attribute_create_volume_permission_add_groups('snap-36fe435f') #=> true


311
312
313
314
315
# File 'lib/ec2/right_ec2_ebs.rb', line 311

def modify_snapshot_attribute_create_volume_permission_add_groups(snapshot_id, *user_group)
  user_group.flatten!
  user_group = ['all'] if user_group.right_blank?
  modify_snapshot_attribute(snapshot_id, 'createVolumePermission', 'add', :user_group => user_group )
end

#modify_snapshot_attribute_create_volume_permission_add_users(snapshot_id, *user_id) ⇒ Object

Grant create volume permission for a list of users.

ec2.modify_snapshot_attribute_create_volume_permission_add_users('snap-36fe435f', '000000000000', '000000000001') #=> true


295
296
297
# File 'lib/ec2/right_ec2_ebs.rb', line 295

def modify_snapshot_attribute_create_volume_permission_add_users(snapshot_id, *user_id)
  modify_snapshot_attribute(snapshot_id, 'createVolumePermission', 'add', :user_id => user_id.flatten )
end

#modify_snapshot_attribute_create_volume_permission_remove_groups(snapshot_id, *user_group) ⇒ Object

Remove create volume permission for user groups (currently only ‘all’ is supported).

ec2.modify_snapshot_attribute_create_volume_permission_remove_groups('snap-36fe435f') #=> true


321
322
323
324
325
# File 'lib/ec2/right_ec2_ebs.rb', line 321

def modify_snapshot_attribute_create_volume_permission_remove_groups(snapshot_id, *user_group)
  user_group.flatten!
  user_group = ['all'] if user_group.right_blank?
  modify_snapshot_attribute(snapshot_id, 'createVolumePermission', 'remove', :user_group => user_group )
end

#modify_snapshot_attribute_create_volume_permission_remove_users(snapshot_id, *user_id) ⇒ Object

Revoke create volume permission for a list of users.

ec2.modify_snapshot_attribute_create_volume_permission_remove_users('snap-36fe435f', '000000000000', '000000000001') #=> true


303
304
305
# File 'lib/ec2/right_ec2_ebs.rb', line 303

def modify_snapshot_attribute_create_volume_permission_remove_users(snapshot_id, *user_id)
  modify_snapshot_attribute(snapshot_id, 'createVolumePermission', 'remove', :user_id => user_id.flatten )
end

#monitor_instances(*list) ⇒ Object

Enables monitoring for a running instances. For more information, refer to the Amazon CloudWatch Developer Guide.

ec2.monitor_instances('i-8437ddec') #=>
  {:instance_id=>"i-8437ddec", :monitoring_state=>"pending"}


33
34
35
36
37
38
# File 'lib/ec2/right_ec2_monitoring.rb', line 33

def monitor_instances(*list)
  link = generate_request("MonitorInstances", amazonize_list('InstanceId', list.flatten) )
  request_info(link, QEc2MonitorInstancesParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#prepare_instance_launch_params(options = {}) ⇒ Object

:nodoc:



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
# File 'lib/ec2/right_ec2_instances.rb', line 221

def prepare_instance_launch_params(options={}) # :nodoc:
  params = amazonize_list('SecurityGroup', Array(options[:group_ids]))
  params['InstanceType']                      = options[:instance_type] || DEFAULT_INSTANCE_TYPE
  params['ImageId']                           = options[:image_id]                             unless options[:image_id].right_blank?
  params['AddressingType']                    = options[:addressing_type]                      unless options[:addressing_type].right_blank?
  params['MinCount']                          = options[:min_count]                            unless options[:min_count].right_blank?
  params['MaxCount']                          = options[:max_count]                            unless options[:max_count].right_blank?
  params['KeyName']                           = options[:key_name]                             unless options[:key_name].right_blank?
  params['KernelId']                          = options[:kernel_id]                            unless options[:kernel_id].right_blank?
  params['RamdiskId']                         = options[:ramdisk_id]                           unless options[:ramdisk_id].right_blank?
  params['Placement.AvailabilityZone']        = options[:availability_zone]                    unless options[:availability_zone].right_blank?
  params['Monitoring.Enabled']                = options[:monitoring_enabled].to_s              if     options[:monitoring_enabled]
  params['SubnetId']                          = options[:subnet_id]                            unless options[:subnet_id].right_blank?
  params['AdditionalInfo']                    = options[:additional_info]                      unless options[:additional_info].right_blank?
  params['DisableApiTermination']             = options[:disable_api_termination].to_s         unless options[:disable_api_termination].nil?
  params['InstanceInitiatedShutdownBehavior'] = options[:instance_initiated_shutdown_behavior] unless options[:instance_initiated_shutdown_behavior].right_blank?
  params['Placement.GroupName']               = options[:placement_group_name]                 unless options[:placement_group_name].right_blank?
  params['License.Pool']                      = options[:license_pool]                         unless options[:license_pool].right_blank?
  params['ClientToken']                       = options[:client_token] || AwsUtils::generate_unique_token
  params.merge!(amazonize_block_device_mappings(options[:block_device_mappings]))
  # KD: https://github.com/rightscale/right_aws/issues#issue/11
  # Do not modify user data and pass it as is: one may pass there a hex-binary data
  options[:user_data] = options[:user_data].to_s
  unless options[:user_data].empty?
    # Do not use CGI::escape(encode64(...)) as it is done in Amazons EC2 library.
    # Amazon 169.254.169.254 does not like escaped symbols!
    # And it doesn't like "\n" inside of encoded string! Grrr....
    # Otherwise, some of UserData symbols will be lost...
    params['UserData'] = Base64.encode64(options[:user_data]).delete("\n")
  end
  params
end

#purchase_reserved_instances_offering(reserved_instances_offering_id, instance_count = 1) ⇒ Object

Purchase a Reserved Instance. Returns ReservedInstancesId value.

ec2.purchase_reserved_instances_offering('e5a2ff3b-f6eb-4b4e-83f8-b879d7060257', 3) # => '4b2293b4-5813-4cc8-9ce3-1957fc1dcfc8'


95
96
97
98
99
100
101
# File 'lib/ec2/right_ec2_reserved_instances.rb', line 95

def purchase_reserved_instances_offering(reserved_instances_offering_id, instance_count=1)
  link = generate_request("PurchaseReservedInstancesOffering", { 'ReservedInstancesOfferingId' => reserved_instances_offering_id,
                                                                 'InstanceCount'               => instance_count  })
  request_info(link, QEc2PurchaseReservedInstancesOfferingParser.new)
rescue Exception
  on_exception
end

#reboot_instances(*instances) ⇒ Object

Reboot an EC2 instance. Returns true or an exception.

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


319
320
321
322
323
324
325
# File 'lib/ec2/right_ec2_instances.rb', line 319

def reboot_instances(*instances)
  instances = instances.flatten
  link = generate_request("RebootInstances", amazonize_list('InstanceId', instances))
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#register_image(options) ⇒ Object

Register new image at Amazon. Options: :image_location, :name, :description, :architecture, :kernel_id, :ramdisk_id,

:root_device_name, :block_device_mappings, :virtualizationt_type(hvm|paravirtual)

Returns new image id.

# Register S3 image
ec2.register_image('bucket_for_k_dzreyev/image_bundles/kd__CentOS_1_10_2009_10_21_13_30_43_MSD/image.manifest.xml') #=> 'ami-e444444d'

# or
image_reg_params = {  :image_location => 'bucket_for_k_dzreyev/image_bundles/kd__CentOS_1_10_2009_10_21_13_30_43_MSD/image.manifest.xml',
                      :name => 'my-test-one-1',
                      :description => 'My first test image' }
ec2.register_image(image_reg_params) #=> "ami-bca1f7aa"

# Register EBS image
image_reg_params = { :name        => 'my-test-image',
                     :description => 'My first test image',
                     :root_device_name => "/dev/sda1",
                     :block_device_mappings => [ { :ebs_snapshot_id=>"snap-7360871a",
                                                   :ebs_delete_on_termination=>true,
                                                   :device_name=>"/dev/sda1"} ] }
ec2.register_image(image_reg_params) #=> "ami-b2a1f7a4"


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/ec2/right_ec2_images.rb', line 168

def register_image(options)
  case
  when options.is_a?(String)
    options = { :image_location => options }
  when !options.is_a?(Hash)
    raise "Unsupported options type"
  end
  params = {}
  params['ImageLocation']  = options[:image_location]   if options[:image_location]
  params['Name']           = options[:name]             if options[:name]
  params['Description']    = options[:description]      if options[:description]
  params['Architecture']   = options[:architecture]     if options[:architecture]
  params['KernelId']       = options[:kernel_id]        if options[:kernel_id]
  params['RamdiskId']      = options[:ramdisk_id]       if options[:ramdisk_id]
  params['RootDeviceName'] = options[:root_device_name] if options[:root_device_name]
  params['VirtualizationType'] = options[:virtualization_type] if options[:virtualization_type] 
#      params['SnapshotId']     = options[:snapshot_id]      if options[:snapshot_id]
  params.merge!(amazonize_block_device_mappings(options[:block_device_mappings]))
  link = generate_request("RegisterImage", params)
  request_info(link, QEc2RegisterImageParser.new(:logger => @logger))
rescue Exception
  on_exception
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


293
294
295
296
297
298
299
# File 'lib/ec2/right_ec2.rb', line 293

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



139
140
141
# File 'lib/ec2/right_ec2.rb', line 139

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

#request_spot_instances(options) ⇒ Object

Create a Spot Instance request.

Mandatory params: :image_id, :spot_price, :instance_type Optional params: :valid_from, :valid_until, :instance_count, :type, :launch_group, :availability_zone_group, :key_name, :user_data, :addressing_type, :kernel_id, :ramdisk_id, :subnet_id, :availability_zone, :monitoring_enabled, :groups, :block_device_mappings

ec2.request_spot_instances(
  :image_id => 'ami-08f41161',
  :spot_price => 0.01,
  :key_name => 'tim',
  :instance_count => 2,
  :groups => ['33','default'],
  :instance_type => 'c1.medium') #=>

  [{:product_description=>"Linux/UNIX",
    :type=>"one-time",
    :spot_instance_requestId=>"sir-7a893003",
    :monitoring_enabled=>false,
    :image_id=>"ami-08f41161",
    :state=>"open",
    :spot_price=>0.01,
    :groups=>["default", "33"],
    :key_name=>"tim",
    :create_time=>"2010-03-10T10:33:09.000Z",
    :instance_type=>"c1.medium"},
   {:product_description=>"Linux/UNIX",
    :type=>"one-time",
    :spot_instance_requestId=>"sir-13dc9a03",
    :monitoring_enabled=>false,
    :image_id=>"ami-08f41161",
    :state=>"open",
    :spot_price=>0.01,
    :groups=>["default", "33"],
    :key_name=>"tim",
    :create_time=>"2010-03-10T10:33:09.000Z",
    :instance_type=>"c1.medium"}]

ec2.request_spot_instances(
  :image_id => 'ami-08f41161',
  :spot_price => 0.01,
  :instance_type => 'm1.small',
  :valid_from => 10.minutes.since,
  :valid_until => 1.hour.since,
  :instance_count => 1,
  :key_name => 'tim',
  :groups => ['33','default'],
  :availability_zone => 'us-east-1a',
  :monitoring_enabled => true,
  :launch_group => 'lg1',
  :availability_zone_group => 'azg1',
  :block_device_mappings => [ { :device_name => '/dev/sdk',
                                :ebs_snapshot_id => 'snap-145cbc7d',
                                :ebs_delete_on_termination => true,
                                :ebs_volume_size => 3,
                                :virtual_name => 'ephemeral2'
                               } ] ) #=>

  [{:monitoring_enabled=>true,
    :type=>"one-time",
    :image_id=>"ami-08f41161",
    :launch_group=>"lg1",
    :state=>"open",
    :valid_until=>"2010-02-05T19:13:44.000Z",
    :create_time=>"2010-02-05T18:13:46.000Z",
    :availability_zone_group=>"azg1",
    :spot_price=>0.01,
    :block_device_mappings=>
     [{:ebs_delete_on_termination=>true,
       :ebs_volume_size=>3,
       :virtual_name=>"ephemeral2",
       :device_name=>"/dev/sdk",
       :ebs_snapshot_id=>"snap-145cbc7d"}],
    :instance_type=>"m1.small",
    :groups=>["default", "33"],
    :product_description=>"Linux/UNIX",
    :key_name=>"tim",
    :valid_from=>"2010-02-05T18:23:44.000Z",
    :availability_zone=>"us-east-1a",
    :spot_instance_request_id=>"sir-32da8a03"}]


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
# File 'lib/ec2/right_ec2_spot_instances.rb', line 225

def request_spot_instances(options)
  options = options.dup
  request_hash = { 'SpotPrice'                        => options[:spot_price],
                   'LaunchSpecification.ImageId'      => options[:image_id],
                   'LaunchSpecification.InstanceType' => options[:instance_type]}
  request_hash['ValidFrom']                      = AwsUtils::utc_iso8601(options[:valid_from])  unless options[:valid_from].right_blank?
  request_hash['ValidUntil']                     = AwsUtils::utc_iso8601(options[:valid_until]) unless options[:valid_until].right_blank?
  request_hash['InstanceCount']                      = options[:instance_count]                 unless options[:instance_count].right_blank?
  request_hash['Type']                               = options[:type]                           unless options[:type].right_blank?
  request_hash['LaunchGroup']                        = options[:launch_group]                   unless options[:launch_group].right_blank?
  request_hash['AvailabilityZoneGroup']              = options[:availability_zone_group]        unless options[:availability_zone_group].right_blank?
  request_hash['LaunchSpecification.KeyName']        = options[:key_name]                       unless options[:key_name].right_blank?
  request_hash['LaunchSpecification.AddressingType'] = options[:addressing_type]                unless options[:addressing_type].right_blank?
  request_hash['LaunchSpecification.KernelId']       = options[:kernel_id]                      unless options[:kernel_id].right_blank?
  request_hash['LaunchSpecification.RamdiskId']      = options[:ramdisk_id]                     unless options[:ramdisk_id].right_blank?
  request_hash['LaunchSpecification.SubnetId']       = options[:subnet_id]                      unless options[:subnet_id].right_blank?
  request_hash['LaunchSpecification.Placement.AvailabilityZone'] = options[:availability_zone]  unless options[:availability_zone].right_blank?
  request_hash['LaunchSpecification.Monitoring.Enabled']         = options[:monitoring_enabled] unless options[:monitoring_enabled].right_blank?
  request_hash.merge!(amazonize_list('LaunchSpecification.SecurityGroup', options[:groups]))    unless options[:groups].right_blank?
  request_hash.merge!(amazonize_block_device_mappings(options[:block_device_mappings], 'LaunchSpecification.BlockDeviceMapping'))
  unless options[:user_data].right_blank?
    # See RightAws::Ec2#run_instances
    options[:user_data].strip!
    request_hash['LaunchSpecification.UserData'] = Base64.encode64(options[:user_data]).delete("\n") unless options[:user_data].right_blank?
  end
  link = generate_request("RequestSpotInstances", request_hash)
  request_info(link, QEc2DescribeSpotInstanceParser.new(:logger => @logger))
end

#reset_image_attribute(image_id, attribute = 'launchPermission') ⇒ Object

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

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


221
222
223
224
225
226
227
228
# File 'lib/ec2/right_ec2_images.rb', line 221

def reset_image_attribute(image_id, attribute='launchPermission')
  link = generate_request("ResetImageAttribute",
                          'ImageId'   => image_id,
                          'Attribute' => attribute)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#reset_instance_attribute(instance_id, attribute) ⇒ Object

Describe instance attribute. Attributes: :kernel, :ramdisk

ec2.reset_instance_attribute(instance, :kernel) #=> true


371
372
373
374
375
376
377
378
379
# File 'lib/ec2/right_ec2_instances.rb', line 371

def reset_instance_attribute(instance_id, attribute)
  attribute = INSTANCE_ATTRIBUTE_MAPPING[attribute.to_s] || attribute.to_s
  link = generate_request('ResetInstanceAttribute',
                          'InstanceId' => instance_id,
                          'Attribute'  => attribute )
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#reset_snapshot_attribute(snapshot_id, attribute = 'createVolumePermission') ⇒ Object

Reset permission settings for the specified snapshot.

ec2.reset_snapshot_attribute('snap-cecd29a7') #=> true


262
263
264
265
266
267
268
269
# File 'lib/ec2/right_ec2_ebs.rb', line 262

def reset_snapshot_attribute(snapshot_id, attribute='createVolumePermission')
  link = generate_request("ResetSnapshotAttribute",
                          'SnapshotId' => snapshot_id,
                          'Attribute'  => attribute)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
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


350
351
352
# File 'lib/ec2/right_ec2_security_groups.rb', line 350

def revoke_security_group_IP_ingress(name, from_port, to_port, protocol='tcp', cidr_ip='0.0.0.0/0')
  edit_security_group( :revoke, name, :from_port => from_port, :to_port => to_port, :protocol => protocol, :cidr_ip => cidr_ip )
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


333
334
335
# File 'lib/ec2/right_ec2_security_groups.rb', line 333

def revoke_security_group_named_ingress(name, owner, group)
  edit_security_group( :revoke, name, :source_group_owner => owner, :source_group => group)
end

#run_instances(image_id, min_count, max_count, group_ids, key_name, user_data = '', addressing_type = nil, instance_type = nil, kernel_id = nil, ramdisk_id = nil, availability_zone = nil, monitoring_enabled = nil, subnet_id = nil, disable_api_termination = nil, instance_initiated_shutdown_behavior = nil, block_device_mappings = nil, placement_group_name = nil, client_token = nil) ⇒ Object

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


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
# File 'lib/ec2/right_ec2_instances.rb', line 141

def run_instances(image_id, min_count, max_count, group_ids, key_name, user_data='',
                  addressing_type = nil, instance_type = nil,
                  kernel_id = nil, ramdisk_id = nil, availability_zone = nil,
                  monitoring_enabled = nil, subnet_id = nil, disable_api_termination = nil,
                  instance_initiated_shutdown_behavior = nil, block_device_mappings = nil,
                  placement_group_name = nil, client_token = nil)
  launch_instances(image_id, { :min_count                            => min_count,
                               :max_count                            => max_count,
                               :user_data                            => user_data,
                               :group_ids                            => group_ids,
                               :key_name                             => key_name,
                               :instance_type                        => instance_type,
                               :addressing_type                      => addressing_type,
                               :kernel_id                            => kernel_id,
                               :ramdisk_id                           => ramdisk_id,
                               :availability_zone                    => availability_zone,
                               :monitoring_enabled                   => monitoring_enabled,
                               :subnet_id                            => subnet_id,
                               :disable_api_termination              => disable_api_termination,
                               :instance_initiated_shutdown_behavior => instance_initiated_shutdown_behavior,
                               :block_device_mappings                => block_device_mappings,
                               :placement_group_name                 => placement_group_name,
                               :client_token                         => client_token
                             })
end

#start_instances(*instance_aws_ids) ⇒ Object

Start instances.

ec2.start_instances("i-36e84a5e") #=>
  [{:aws_prev_state_name=>"stopped",
    :aws_instance_id=>"i-36e84a5e",
    :aws_current_state_code=>16,
    :aws_current_state_name=>"running",
    :aws_prev_state_code=>80}]


263
264
265
266
267
# File 'lib/ec2/right_ec2_instances.rb', line 263

def start_instances(*instance_aws_ids)
 instance_aws_ids = instance_aws_ids.flatten
 link = generate_request("StartInstances", amazonize_list('InstanceId', instance_aws_ids))
 request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
end

#stop_instances(*instance_aws_ids) ⇒ Object

Stop instances.

ec2.stop_instances("i-36e84a5e") #=>
  [{:aws_prev_state_code=>16,
    :aws_prev_state_name=>"running",
    :aws_instance_id=>"i-36e84a5e",
    :aws_current_state_code=>64,
    :aws_current_state_name=>"stopping"}]


278
279
280
281
282
# File 'lib/ec2/right_ec2_instances.rb', line 278

def stop_instances(*instance_aws_ids)
  instance_aws_ids = instance_aws_ids.flatten
  link = generate_request("StopInstances", amazonize_list('InstanceId', instance_aws_ids))
  request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
end

#terminate_instances(*instance_aws_ids) ⇒ Object

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

ec2.terminate_instances(['i-cceb49a4']) #=>
  [{:aws_instance_id=>"i-cceb49a4",
    :aws_current_state_code=>32,
    :aws_current_state_name=>"shutting-down",
    :aws_prev_state_code=>16,
    :aws_prev_state_name=>"running"}]


293
294
295
296
297
298
299
# File 'lib/ec2/right_ec2_instances.rb', line 293

def terminate_instances(*instance_aws_ids)
  instance_aws_ids = instance_aws_ids.flatten
  link = generate_request("TerminateInstances", amazonize_list('InstanceId', instance_aws_ids))
  request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#try_create_snapshot(volume_id, connect_timeout = nil, read_timeout = nil, description = '') ⇒ Object

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', 'KD: WooHoo!!') #=>
  {:aws_volume_id=>"vol-e429db8d",
   :aws_started_at=>"2009-10-01T09:23:38.000Z",
   :aws_description=>"KD: WooHoo!!",
   :aws_owner=>"648770000000",
   :aws_progress=>"",
   :aws_status=>"pending",
   :aws_volume_size=>1,
   :aws_id=>"snap-3df54854"}


215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/ec2/right_ec2_ebs.rb', line 215

def try_create_snapshot(volume_id, connect_timeout = nil, read_timeout = nil, description='')
  # For safety in the ensure block...we don't want to restore values
  # if we never read them in the first place
  orig_reiteration_time = nil
  orig_http_params = nil

  orig_reiteration_time = RightAws::AWSErrorHandler::reiteration_time
  RightAws::AWSErrorHandler::reiteration_time = 0

  orig_http_params = Rightscale::HttpConnection::params()
  new_http_params = orig_http_params.dup
  new_http_params[:http_connection_retry_count] = 0
  new_http_params[:http_connection_open_timeout] = connect_timeout if !connect_timeout.nil?
  new_http_params[:http_connection_read_timeout] = read_timeout if !read_timeout.nil?
  Rightscale::HttpConnection::params = new_http_params

  link = generate_request("CreateSnapshot",
                          "VolumeId"    => volume_id.to_s,
                          "Description" => description)
  request_info(link, QEc2DescribeSnapshotsParser.new(:logger => @logger)).first

rescue Exception
  on_exception
ensure
  RightAws::AWSErrorHandler::reiteration_time = orig_reiteration_time if orig_reiteration_time
  Rightscale::HttpConnection::params = orig_http_params if orig_http_params
end

#unmonitor_instances(*list) ⇒ Object

Disables monitoring for a running instances. For more information, refer to the Amazon CloudWatch Developer Guide.

ec2.unmonitor_instances('i-8437ddec') #=>
  {:instance_id=>"i-8437ddec", :monitoring_state=>"disabling"}


45
46
47
48
49
50
# File 'lib/ec2/right_ec2_monitoring.rb', line 45

def unmonitor_instances(*list)
  link = generate_request("UnmonitorInstances", amazonize_list('InstanceId', list.flatten) )
  request_info(link, QEc2MonitorInstancesParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end