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_vpc2.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, QEc2AssociateAddressParser, QEc2AttachAndDetachVolumeParser, QEc2AttachVpnGatewayParser, QEc2BundleInstanceParser, QEc2CancelSpotInstanceParser, QEc2ConfirmProductInstanceParser, QEc2CreateKeyPairParser, QEc2CreateSecurityGroupsParser, QEc2CreateVolumeParser, QEc2DescribeAddressesParser, QEc2DescribeAvailabilityZonesParser, QEc2DescribeBundleTasksParser, QEc2DescribeCustomerGatewaysParser, QEc2DescribeDhcpOptionsParser, QEc2DescribeImageAttributeParser, QEc2DescribeImagesParser, QEc2DescribeInstanceAttributeParser, QEc2DescribeInstancesParser, QEc2DescribeInternetGatewaysParser, QEc2DescribeKeyPairParser, QEc2DescribeLicensesParser, QEc2DescribePlacementGroupsParser, QEc2DescribeRegionsParser, QEc2DescribeReservedInstancesOfferingsParser, QEc2DescribeReservedInstancesParser, QEc2DescribeRouteTablesParser, 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

"2011-02-28"
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']
@@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_hash_with_key_mapping, #amazonize_list, #amazonize_list_with_key_mapping, #cache_hits?, caching, caching=, #caching?, #destroy_connection, #generate_request_impl, #get_connection, #get_connections_storage, #get_server_url, #incrementally_list_items, #init, #map_api_keys_and_values, #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_address(options = {}) ⇒ Object

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

ec2.allocate_address #=>
  { :public_ip => "50.19.214.224",
    :domain    => "standard"}

ec2.allocate_address(:domain => 'vpc') #=>
  { :allocation_id => "eipalloc-c6abfeaf",
    :domain        => "vpc",
    :public_ip     => "184.72.112.39"}


251
252
253
254
255
256
257
258
# File 'lib/ec2/right_ec2.rb', line 251

def allocate_address(options={})
  request_hash = {}
  request_hash['Domain'] = options[:domain] unless options[:domain].right_blank?
  link = generate_request("AllocateAddress", request_hash)
  request_info(link, QEc2AllocateAddressParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#associate_address(instance_id, options = {}) ⇒ Object

Associate an elastic IP address with an instance. Options: :public_ip, :allocation_id. Returns a hash of data or an exception.

ec2.associate_address('i-d630cbbf', :public_ip => '75.101.154.140') #=>
  { :return => true }

ec2.associate_address(inst, :allocation_id => "eipalloc-c6abfeaf") #=>
  { :return         => true,
    :association_id => 'eipassoc-fc5ca095'}


271
272
273
274
275
276
277
278
279
# File 'lib/ec2/right_ec2.rb', line 271

def associate_address(instance_id, options={})
  request_hash = { "InstanceId" => instance_id.to_s }
  request_hash['PublicIp']     = options[:public_ip]     unless options[:public_ip].right_blank?
  request_hash['AllocationId'] = options[:allocation_id] unless options[:allocation_id].right_blank?
  link = generate_request("AssociateAddress", request_hash)
  request_info(link, QEc2AssociateAddressParser.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"}]


194
195
196
197
198
199
200
# File 'lib/ec2/right_ec2_vpc.rb', line 194

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

#associate_route_table(route_table_id, subnet_id) ⇒ Object

Associates a subnet with a route table. The subnet and route table must be in the same VPC. This association causes traffic originating from the subnet to be routed according to the routes in the route table. The action returns an association ID, which you need if you want to disassociate the route table from the subnet later. A route table can be associated with multiple subnets.

ec2.associate_route_table("rtb-be3006d7", "subnet-b95f76d0") #=> true

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



211
212
213
214
215
216
217
218
# File 'lib/ec2/right_ec2_vpc2.rb', line 211

def associate_route_table(route_table_id, subnet_id)
  request_hash = { 'RouteTableId' => route_table_id,
                   'SubnetId'     => subnet_id }
  link = generate_request("AssociateRouteTable", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#attach_internet_gateway(internet_gateway_id, vpc_id) ⇒ Object

Attaches an Internet gateway to a VPC, enabling connectivity between the Internet and the VPC.

ec2.attach_internet_gateway("igw-6585c10c", "vpc-df80a6b6") #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachInternetGateway.html



87
88
89
90
91
92
93
94
# File 'lib/ec2/right_ec2_vpc2.rb', line 87

def attach_internet_gateway(internet_gateway_id, vpc_id)
  request_hash = { 'InternetGatewayId' => internet_gateway_id,
                   'VpcId'             => vpc_id }
  link = generate_request("AttachInternetGateway", request_hash)
  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"}


313
314
315
316
317
318
319
# File 'lib/ec2/right_ec2_vpc.rb', line 313

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


420
421
422
# File 'lib/ec2/right_ec2_security_groups.rb', line 420

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


403
404
405
# File 'lib/ec2/right_ec2_security_groups.rb', line 403

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


460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/ec2/right_ec2_instances.rb', line 460

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


529
530
531
532
533
534
# File 'lib/ec2/right_ec2_instances.rb', line 529

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


250
251
252
253
# File 'lib/ec2/right_ec2_spot_instances.rb', line 250

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"


121
122
123
124
125
# File 'lib/ec2/right_ec2_instances.rb', line 121

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


247
248
249
250
251
252
253
254
# File 'lib/ec2/right_ec2_vpc.rb', line 247

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


176
177
178
179
180
181
182
183
# File 'lib/ec2/right_ec2_vpc.rb', line 176

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"


325
326
327
328
329
330
331
332
# File 'lib/ec2/right_ec2_images.rb', line 325

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_internet_gatewayObject

Create internet gateway

ec2.create_internet_gateway #=> 
  { :internet_gateway_id=>"igw-6585c10c", :tags=>{}}

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



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

def create_internet_gateway
  link = generate_request("CreateInternetGateway")
  request_info(link, QEc2DescribeInternetGatewaysParser.new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_key_pair(name) ⇒ Object

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

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


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

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_route(route_table_id, destination_cidr_block, options = {}) ⇒ Object

Creates a new route in a route table within a VPC. The route’s target can be either a gateway attached to the VPC or a NAT instance in the VPC. Options: :gateway_id, :instance_id

ec2.create_route("rtb-be3006d7",  "0.0.0.1/32", :gateway_id => 'igw-6585c10c') #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateRoute.html



263
264
265
266
267
268
269
270
271
272
# File 'lib/ec2/right_ec2_vpc2.rb', line 263

def create_route(route_table_id, destination_cidr_block, options = {})
  request_hash = { 'RouteTableId'         => route_table_id,
                   'DestinationCidrBlock' => destination_cidr_block }
  request_hash['GatewayId']  = options[:gateway_id]  unless options[:gateway_id].right_blank?
  request_hash['InstanceId'] = options[:instance_id] unless options[:instance_id].right_blank?      
  link = generate_request("CreateRoute", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_route_table(vpc_id) ⇒ Object

Creates a new route table within a VPC. After you create a new route table, you can add routes and associate the table with a subne

ec2.create_route_table("vpc-df80a6b6") #=>
  {:route_table_id=>"rtb-4331072a",
   :route_set=>
    [{:state=>"active",
      :destination_cidr_block=>"10.0.3.0/24",
      :gateway_id=>"local"}],
   :vpc_id=>"vpc-df80a6b6",
   :association_set=>[],
   :tags=>{}}

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



182
183
184
185
186
187
# File 'lib/ec2/right_ec2_vpc2.rb', line 182

def create_route_table(vpc_id)
  link = generate_request("CreateRouteTable", 'VpcId' => vpc_id )
  request_info(link, QEc2DescribeRouteTablesParser::new(:logger => @logger)).first
rescue Exception
  on_exception
end

#create_security_group(name, description = nil, options = {}) ⇒ Object

Create new Security Group. Returns true or an exception. Options: :vpc_id

ec2.create_security_group('default-1',"Default allowing SSH, HTTP, and HTTPS ingress") #=>
  { :group_id=>"sg-f0227599", :return=>true }

ec2.create_security_group('default-2',"my VPC group", :vpc_id => 'vpc-e16c0000') #=>
  { :group_id=>"sg-76d1c31a", :return=>true }


158
159
160
161
162
163
164
165
166
# File 'lib/ec2/right_ec2_security_groups.rb', line 158

def create_security_group(name, description = nil, options = {})
  options = options.dup
  options[:group_name]        = name      
  options[:group_description] = description.right_blank? ? '-' : description # EC2 rejects an empty description...
  link = generate_request("CreateSecurityGroup", map_api_keys_and_values(options, :group_name, :group_description, :vpc_id))
  request_info(link, QEc2CreateSecurityGroupsParser.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"}


206
207
208
209
210
211
212
213
# File 'lib/ec2/right_ec2_ebs.rb', line 206

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


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

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


124
125
126
127
128
129
130
131
132
# File 'lib/ec2/right_ec2_vpc.rb', line 124

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, options = {}) ⇒ 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"}


68
69
70
71
72
73
74
75
# File 'lib/ec2/right_ec2_vpc.rb', line 68

def create_vpc(cidr_block, options = {})
  request_hash = {'CidrBlock' => cidr_block}
  request_hash['instanceTenancy'] = options[:instance_tenancy] unless options[:instance_tenancy].right_blank?
  link = generate_request("CreateVpc", request_hash )
  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"}


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

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


299
300
301
302
303
304
305
306
# File 'lib/ec2/right_ec2_vpc.rb', line 299

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


260
261
262
263
264
265
# File 'lib/ec2/right_ec2_vpc.rb', line 260

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


206
207
208
209
210
211
# File 'lib/ec2/right_ec2_vpc.rb', line 206

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_internet_gateway(internet_gateway_id) ⇒ Object

Delete internet gateway.

ec2.delete_internet_gateway("igw-6585c10c") #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteInternetGateway.html



74
75
76
77
78
79
# File 'lib/ec2/right_ec2_vpc2.rb', line 74

def delete_internet_gateway(internet_gateway_id)
  link = generate_request("DeleteInternetGateway", 'InternetGatewayId' => internet_gateway_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


226
227
228
229
230
231
232
# File 'lib/ec2/right_ec2.rb', line 226

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_route(route_table_id, destination_cidr_block) ⇒ Object

Deletes a route from a route table in a VPC.

ec2.delete_route("rtb-be3006d7",  "0.0.0.1/32") #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteRoute.html



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

def delete_route(route_table_id, destination_cidr_block)
  link = generate_request("DeleteRoute", 'RouteTableId'         => route_table_id,
                                         'DestinationCidrBlock' => destination_cidr_block )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_route_table(route_table_id) ⇒ Object

Deletes a route table from a VPC. The route table must not be associated with a subnet. You can’t delete the main route table.

ec2.delete_route_table("rtb-4331072a") #=> true

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



195
196
197
198
199
200
# File 'lib/ec2/right_ec2_vpc2.rb', line 195

def delete_route_table(route_table_id)
  link = generate_request("DeleteRouteTable", 'RouteTableId' => route_table_id )
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_security_group(group_id_or_options = {}) ⇒ Object

Remove Security Group. Returns true or an exception. Options: :group_name, :group_id

# Delete security group by group_id:
ec2.delete_security_group('sg-90054ef9') #=> true
ec2.delete_security_group(:group_id => 'sg-90054ef9') #=> true

# Delete security group by name (EC2 only):
ec2.delete_security_group(:group_name => 'my-group']) #=> true


178
179
180
181
182
183
184
# File 'lib/ec2/right_ec2_security_groups.rb', line 178

def delete_security_group(group_id_or_options={})
  options = group_id_or_options.is_a?(Hash) ? group_id_or_options : { :group_id => group_id_or_options } 
  link = generate_request("DeleteSecurityGroup", map_api_keys_and_values(options, :group_name, :group_id))
  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


346
347
348
349
350
351
352
# File 'lib/ec2/right_ec2_ebs.rb', line 346

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


288
289
290
291
# File 'lib/ec2/right_ec2_spot_instances.rb', line 288

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


138
139
140
141
142
143
# File 'lib/ec2/right_ec2_vpc.rb', line 138

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


81
82
83
84
85
86
# File 'lib/ec2/right_ec2_vpc.rb', line 81

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


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

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


337
338
339
340
341
342
# File 'lib/ec2/right_ec2_vpc.rb', line 337

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 IPs by public addresses.

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-75ebd41b", :domain=>"standard", :public_ip=>"50.17.211.96"},
                              :domain=>"vpc", :public_ip=>"184.72.112.39",  :allocation_id=>"eipalloc-c6abfeaf"}]

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

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

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



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

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

#describe_addresses_by_allocation_ids(*list_and_options) ⇒ Object

List elastic IPs by allocation ids.

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

describe_addresses_by_allocation_ids("eipalloc-c6abfeaf") #=>
  [{:domain=>"vpc",
    :public_ip=>"184.72.112.39",
    :allocation_id=>"eipalloc-c6abfeaf"}]

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


314
315
316
# File 'lib/ec2/right_ec2.rb', line 314

def describe_addresses_by_allocation_ids(*list_and_options)
  describe_resources_with_list_and_options('DescribeAddresses', 'AllocationId', 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



372
373
374
# File 'lib/ec2/right_ec2.rb', line 372

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



512
513
514
# File 'lib/ec2/right_ec2_instances.rb', line 512

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



234
235
236
# File 'lib/ec2/right_ec2_vpc.rb', line 234

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



164
165
166
# File 'lib/ec2/right_ec2_vpc.rb', line 164

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.

Returns: String (or nil) for ‘description’, ‘kernel’, ‘ramdisk’; Hash for ‘launchPermission’; Array for ‘productCodes’, ‘blockDeviceMapping’

ec2.describe_image_attribute('ami-00000000', 'description')        #=> 'My cool Image'
ec2.describe_image_attribute('ami-00000000', 'launchPermission')   #=> {:user_ids=>["443739700000", "115864000000", "309179000000", "857501300000"]}
ec2.describe_image_attribute('ami-00000000', 'productCodes')       #=> ["8ED10000"]
ec2.describe_image_attribute('ami-00000000', 'kernel')             #=> "aki-9b00e5f2"
ec2.describe_image_attribute('ami-00000000', 'ramdisk')            #=> nil
ec2.describe_image_attribute('ami-00000000', 'blockDeviceMapping') #=> [{:device_name=>"sda2", :virtual_name=>"ephemeral0"},
                                                                        {:device_name=>"sda1", :virtual_name=>"ami"},
                                                                        {:device_name=>"/dev/sda1", :virtual_name=>"root"},
                                                                        {:device_name=>"sda3", :virtual_name=>"swap"}]


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

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: ‘instanceType’, ‘kernel’, ‘ramdisk’, ‘userData’, ‘rootDeviceName’, ‘disableApiTermination’, ‘instanceInitiatedShutdownBehavior’, ‘sourceDestCheck’, ‘blockDeviceMapping’, ‘groupSet’

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"


345
346
347
348
349
350
351
352
353
354
# File 'lib/ec2/right_ec2_instances.rb', line 345

def describe_instance_attribute(instance_id, attribute)
  link = generate_request('DescribeInstanceAttribute',
                          'InstanceId' => instance_id,
                          'Attribute'  => attribute)
  value = request_info(link, QEc2DescribeInstanceAttributeParser.new(:logger => @logger))
  value = Base64.decode64(value) if attribute == "userData" && !value.right_blank?
  value
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 #=>
  [{:source_dest_check=>true,
      :subnet_id=>"subnet-da6cf9b3",
      :aws_kernel_id=>"aki-3932d150",
      :ami_launch_index=>"0",
      :tags=>{},
      :aws_reservation_id=>"r-7cd25c11",
      :aws_owner=>"826693181925",
      :state_reason_code=>"Client.UserInitiatedShutdown",
      :aws_instance_id=>"i-2d898e41",
      :hypervisor=>"xen",
      :root_device_name=>"/dev/sda1",
      :aws_ramdisk_id=>"ari-c515f6ac",
      :aws_instance_type=>"m1.large",
      :groups=>[{:group_name=>"2009-07-15-default", :group_id=>"sg-90c5d6fc"}],
      :block_device_mappings=>
        [{:device_name=>"/dev/sda1",
          :ebs_status=>"attached",
          :ebs_attach_time=>"2011-03-04T18:51:58.000Z",
          :ebs_delete_on_termination=>true,
          :ebs_volume_id=>"vol-38f2bd50"}],
      :state_reason_message=>
        "Client.UserInitiatedShutdown: User initiated shutdown",
      :aws_image_id=>"ami-a3638cca",
      :virtualization_type=>"paravirtual",
      :aws_launch_time=>"2011-03-04T18:13:59.000Z",
      :private_dns_name=>"",
      :aws_product_codes=>[],
      :aws_availability_zone=>"us-east-1a",
      :aws_state_code=>80,
      :architecture=>"x86_64",
      :dns_name=>"",
      :client_token=>"1299262447-684266-NNgyH-ouPTI-MzG6h-5AIRk",
      :root_device_type=>"ebs",
      :vpc_id=>"vpc-e16cf988",
      :monitoring_state=>"disabled",
      :ssh_key_name=>"default",
      :private_ip_address=>"192.168.0.52",
      :aws_reason=>"User initiated ",
      :aws_state=>"stopped"}, ...]

 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



110
111
112
113
114
# File 'lib/ec2/right_ec2_instances.rb', line 110

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_internet_gateways(*list_and_options) ⇒ Object

Describe internet gateways.

ec2.describe_internet_gateways #=>
  [{:state=>"available",
    :internet_gateway_id=>"igw-6585c10c",
    :vpc_id=>"vpc-df80a6b6",
    :tags=>{}},
   {:internet_gateway_id=>"igw-883503e1",
    :tags=>{}}]

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



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

def describe_internet_gateways(*list_and_options)
  describe_resources_with_list_and_options('DescribeInternetGateways', 'InternetGatewayId', QEc2DescribeInternetGatewaysParser, list_and_options)
rescue Exception
  on_exception
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



188
189
190
# File 'lib/ec2/right_ec2.rb', line 188

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  #=>
 [{:region_endpoint=>"ec2.eu-west-1.amazonaws.com",      :region_name=>"eu-west-1"},
  {:region_endpoint=>"ec2.us-east-1.amazonaws.com",      :region_name=>"us-east-1"},
  {:region_endpoint=>"ec2.ap-northeast-1.amazonaws.com", :region_name=>"ap-northeast-1"},
  {:region_endpoint=>"ec2.us-west-1.amazonaws.com",      :region_name=>"us-west-1"},
  {:region_endpoint=>"ec2.ap-southeast-1.amazonaws.com", :region_name=>"ap-southeast-1"}]

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



395
396
397
# File 'lib/ec2/right_ec2.rb', line 395

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

[{:currency_code=>"USD",
  :aws_fixed_price=>350.0,
  :aws_availability_zone=>"us-east-1c",
  :aws_instance_count=>1,
  :tags=>{},
  :aws_id=>"4357912c-ad94-4f57-8625-15ca71a8e66d",
  :aws_product_description=>"Linux/UNIX",
  :aws_state=>"active",
  :aws_start=>"2010-03-18T20:39:39.569Z",
  :aws_duration=>94608000,
  :aws_instance_type=>"m1.small",
  :instance_tenancy=>"default",
  :aws_usage_price=>0.03}]

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



58
59
60
# File 'lib/ec2/right_ec2_reserved_instances.rb', line 58

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 #=>
  [{:currency_code=>"USD",
    :aws_fixed_price=>700.0,
    :aws_id=>"248e7b75-933c-451b-b126-be25865e02a5",
    :aws_product_description=>"Linux/UNIX",
    :aws_instance_type=>"c1.medium",
    :aws_duration=>94608000,
    :instance_tenancy=>"default",
    :aws_usage_price=>0.06,
    :aws_availability_zone=>"us-east-1a"},
   {:currency_code=>"USD",
    :aws_fixed_price=>700.0,
    :aws_id=>"c48ab04c-7e03-46b2-891a-2df1116e51a3",
    :aws_product_description=>"Linux/UNIX (Amazon VPC)",
    :aws_instance_type=>"c1.medium",
    :aws_duration=>94608000,
    :instance_tenancy=>"default",
    :aws_usage_price=>0.06,
    :aws_availability_zone=>"us-east-1a"}, ... ]

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



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

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
155
156
157
158
159
160
161
162
163
164
# 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)
  # Resource IDs to fetch
  request_hash  = amazonize_list(remote_item_name, list)
  # Other custom options
  options.each do |key, values|
    next if values.right_blank?
    case key
    when :filters then
      request_hash.merge!(amazonize_list(['Filter.?.Name', 'Filter.?.Value.?'], values))
    else
      request_hash.merge!(amazonize_list(key.to_s.right_camelize, values))
    end
  end
  cache_for = (list.right_blank? && options.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_route_tables(*list_and_options) ⇒ Object

Describe route tables.

# List all tables
ec2.describe_route_tables #=>
  [{:route_table_id=>"rtb-be3006d7",
    :route_set=>
     [{:state=>"active",
       :destination_cidr_block=>"10.0.3.0/24",
       :gateway_id=>"local"}],
    :vpc_id=>"vpc-df80a6b6",
    :association_set=>[],
    :tags=>{}},
   {:route_table_id=>"rtb-e36cf98a",
    :route_set=>
     [{:state=>"active",
       :destination_cidr_block=>"192.168.0.0/24",
       :gateway_id=>"local"}],
    :vpc_id=>"vpc-e16cf988",
    :association_set=>
     [{:route_table_id=>"rtb-e36cf98a",
       :main=>true,
       :route_table_association_id=>"rtbassoc-e26cf98b"}],
    :tags=>{}}, ... ]

# Filter tables by VpcId
ec2.describe_route_tables(:filters => {'vpc-id' => "vpc-df80a6b6"})

# Custom route table
ec2.describe_route_tables("rtb-be3006d7") #=> 
  [{:vpc_id=>"vpc-df80a6b6",
    :route_set=>
     [{:state=>"active",
       :destination_cidr_block=>"0.0.0.1/32",
       :gateway_id=>"igw-6585c10c"},
      {:state=>"active",
       :destination_cidr_block=>"10.0.3.0/24",
       :gateway_id=>"local"}],
    :route_table_id=>"rtb-be3006d7",
    :tags=>{},
    :association_set=>
     [{:route_table_association_id=>"rtbassoc-a02610c9",
       :subnet_id=>"subnet-b95f76d0",
       :route_table_id=>"rtb-be3006d7"}]}]

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



162
163
164
165
166
# File 'lib/ec2/right_ec2_vpc2.rb', line 162

def describe_route_tables(*list_and_options)
  describe_resources_with_list_and_options('DescribeRouteTables', 'RouteTableId', QEc2DescribeRouteTablesParser, list_and_options)
rescue Exception
  on_exception
end

#describe_security_groups(*list_and_options) ⇒ Object

Retrieve Security Groups information. Options: By default this methods expects security group ids but if you wanna pass their names then :describe_by => :group_name option must be set.

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=>
      [{:protocol=>"-1", :cidr_ips=>"0.0.0.0/0", :direction=>:egress},
      {:protocol=>"tcp",
        :cidr_ips=>"127.0.0.2/32",
        :direction=>:egress,
        :from_port=>"1111",
        :to_port=>"1111"},
      {:protocol=>"tcp",
        :cidr_ips=>"127.0.0.1/32",
        :direction=>:egress,
        :from_port=>"1111",
        :to_port=>"1111"}],
    :aws_group_name=>"kd-vpc-egress-test-1",
    :vpc_id=>"vpc-e16cf988",
    :aws_description=>"vpc test",
    :aws_owner=>"826693181925",
    :group_id=>"sg-b72032db"}]

 # Describe by group ids
 ec2.describe_security_groups("sg-a0b85dc9", "sg-00b05d39", "sg-a1b86dc8")

 # Describe by group names
 ec2.describe_security_groups("default", "default1", "kd", :describe_by => :group_name)

# 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_name=>"default",
       :protocol=>"tcp",
       :owner=>"048291609141",
       :from_port=>"1"},
      {:to_port=>"65535",
       :group_name=>"default",
       :protocol=>"udp",
       :owner=>"048291609141",
       :from_port=>"1"},
      {:to_port=>"-1",
       :group_name=>"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



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/ec2/right_ec2_security_groups.rb', line 102

def describe_security_groups(*list_and_options)
  list, options = AwsUtils::split_items_and_params(list_and_options)
  describe_by   = options.delete(:describe_by) == :group_name ? 'GroupName' : 'GroupId'
  describe_resources_with_list_and_options('DescribeSecurityGroups', describe_by, 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] }
      result_item[:group_id] = item[:group_id] unless item[:group_id].right_blank?
      result_item[:vpc_id]   = item[:vpc_id]   unless item[:vpc_id].right_blank?
      aws_perms = []
      item[:ip_permissions].each do |permission|
        result_perm = {}
        result_perm[:from_port] = permission[:from_port]   unless permission[:from_port].right_blank?
        result_perm[:to_port]   = permission[:to_port]     unless permission[:to_port].right_blank?
        result_perm[:protocol]  = permission[:ip_protocol]
        result_perm[:direction] = permission[:direction]
        # IP permissions
        Array(permission[:ip_ranges]).each do |ip_range|
          perm = result_perm.dup
          # Mhhh... For Eucalyptus we somehow get used to use ":cidr_ip" instead of ":cidr_ips"...
          if @params[:eucalyptus] then  perm[:cidr_ip]  = ip_range
          else                          perm[:cidr_ips] = ip_range
          end
          aws_perms << perm
        end
        # Group permissions
        Array(permission[:groups]).each do |group|
          perm = result_perm.dup
          perm[:group_name] = group[:group_name] unless group[:group_name].right_blank?
          perm[:group_id]   = group[:group_id]   unless group[:group_id].right_blank?
          perm[:owner]      = group[:user_id]    unless group[:user_id].right_blank?
          aws_perms << perm
        end
      end
      result_item[:aws_perms] = aws_perms.uniq
      result << result_item
    end
    result
  end
end

#describe_security_groups_by_name(*list) ⇒ Object



145
146
147
# File 'lib/ec2/right_ec2_security_groups.rb', line 145

def describe_security_groups_by_name(*list)
  describe_security_groups(list, :describe_by => :group_name)
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']}}


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

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 options: :restorable_by, :owner and :filters

Options: :restorable_by => Array or String, :owner => Array or String, :filters => Hash

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_size=>2,
    :tags=>{},
    :aws_id=>"snap-d010f6b9",
    :owner_alias=>"amazon",
    :aws_progress=>"100%",
    :aws_status=>"completed",
    :aws_description=>
     "Windows 2003 R2 Installation Media [Deprecated] - Enterprise Edition 64-bit",
    :aws_owner=>"711940113766",
    :aws_volume_id=>"vol-351efb5c",
    :aws_started_at=>"2008-10-20T18:23:59.000Z"},
   {:aws_volume_size=>2,
    :tags=>{},
    :aws_id=>"snap-a310f6ca",
    :owner_alias=>"amazon",
    :aws_progress=>"100%",
    :aws_status=>"completed",
    :aws_description=>"Windows 2003 R2 Installation Media 64-bit",
    :aws_owner=>"711940113766",
    :aws_volume_id=>"vol-001efb69",
    :aws_started_at=>"2008-10-20T18:25:53.000Z"}, ... ]

ec2.describe_snapshots("snap-e676e28a", "snap-e176e281")

ec2.describe_snapshots(:restorable_by => ['123456781234'],
                       :owner         => ['self', 'amazon'],
                       :filters       => {'tag:MyTag' => 'MyValue'})

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



186
187
188
# File 'lib/ec2/right_ec2_ebs.rb', line 186

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

#describe_snapshots_by_restorable_by(*list_and_options) ⇒ Object



190
191
192
# File 'lib/ec2/right_ec2_ebs.rb', line 190

def describe_snapshots_by_restorable_by(*list_and_options)
  describe_resources_with_list_and_options('DescribeSnapshots', 'RestorableBy', 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"}


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

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 #=>
  [{:product_description=>"Linux/UNIX",
    :type=>"one-time",
    :availability_zone=>"us-east-1b",
    :monitoring_enabled=>false,
    :tags=>{},
    :image_id=>"ami-08f41161",
    :groups=>[{:group_id=>"sg-a0b85dc9", :group_name=>"default"}],
    :spot_price=>0.01,
    :create_time=>"2010-03-24T10:41:28.000Z",
    :instance_type=>"c1.medium",
    :state=>"open",
    :spot_instance_request_id=>"sir-9652a604",
    :key_name=>"rightscale_test"},
   {:product_description=>"Linux/UNIX",
    :type=>"one-time",
    :availability_zone=>"us-east-1b",
    :monitoring_enabled=>false,
    :tags=>{},
    :image_id=>"ami-08f41161",
    :groups=>[{:group_id=>"sg-a0b85dc9", :group_name=>"default"}],
    :spot_price=>0.01,
    :create_time=>"2010-03-24T11:40:27.000Z",
    :instance_type=>"c1.medium",
    :state=>"open",
    :spot_instance_request_id=>"sir-fa912802",
    :key_name=>"rightscale_test"}, ... ]

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



132
133
134
# File 'lib/ec2/right_ec2_spot_instances.rb', line 132

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, :api_version => '2011-05-15')
  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



110
111
112
# File 'lib/ec2/right_ec2_vpc.rb', line 110

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 #=>
  [{:instance_tenancy=>"default",
    :vpc_id=>"vpc-e16cf988",
    :tags=>{},
    :dhcp_options_id=>"default",
    :cidr_block=>"192.168.0.0/24",
    :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



56
57
58
# File 'lib/ec2/right_ec2_vpc.rb', line 56

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



368
369
370
# File 'lib/ec2/right_ec2_vpc.rb', line 368

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



287
288
289
# File 'lib/ec2/right_ec2_vpc.rb', line 287

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

#detach_internet_gateway(internet_gateway_id, vpc_id) ⇒ Object

Detaches an Internet gateway from a VPC, disabling connectivity between the Internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses.

ec2.detach_internet_gateway("igw-6585c10c", "vpc-df80a6b6") #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachInternetGateway.html



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

def detach_internet_gateway(internet_gateway_id, vpc_id)
  request_hash = { 'InternetGatewayId' => internet_gateway_id,
                   'VpcId'             => vpc_id }
  link = generate_request("DetachInternetGateway", request_hash)
  request_info(link, RightHttp2xxParser::new(:logger => @logger))
rescue Exception
  on_exception
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


325
326
327
328
329
330
331
# File 'lib/ec2/right_ec2_vpc.rb', line 325

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(options = {}) ⇒ Object

Disassociate the specified elastic IP address from the instance to which it is assigned. Options: :public_ip, :association_id. Returns true or an exception.

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


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

def disassociate_address(options = {})
  request_hash = {}
  request_hash['PublicIp']      = options[:public_ip]      unless options[:public_ip].right_blank?
  request_hash['AssociationId'] = options[:association_id] unless options[:association_id].right_blank?
  link = generate_request("DisassociateAddress", request_hash)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#disassociate_route_table(route_table_association_id) ⇒ Object

Disassociates a subnet from a route table.

ec2.disassociate_route_table(route_table_association_id) #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DisassociateRouteTable.html



226
227
228
229
230
231
# File 'lib/ec2/right_ec2_vpc2.rb', line 226

def disassociate_route_table(route_table_association_id)
  link = generate_request("DisassociateRouteTable", 'AssociationId' => route_table_association_id )
  request_info(link, RightHttp2xxParser.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.



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/ec2/right_ec2_security_groups.rb', line 373

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 = {}, custom_options = {}) ⇒ Object

:nodoc:



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

def generate_request(action, params={}, custom_options={}) #:nodoc:
  generate_request_impl(:get, action, params, custom_options)
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 ..."


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

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
49
# 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]
      # Security Groups
      instance[:groups]             = instance[:groups].right_blank? ? reservation[:aws_groups] : instance[: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"


414
415
416
417
418
419
420
421
422
423
424
# File 'lib/ec2/right_ec2_instances.rb', line 414

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… ;(



432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/ec2/right_ec2_instances.rb', line 432

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

#grant_security_group_egress(group_id, permissions) ⇒ Object



194
195
196
# File 'lib/ec2/right_ec2_security_groups.rb', line 194

def grant_security_group_egress(group_id, permissions)
  modify_security_group(:grant, :egress, group_id, permissions)
end

#grant_security_group_ingress(group_id, permissions) ⇒ Object



186
187
188
# File 'lib/ec2/right_ec2_security_groups.rb', line 186

def grant_security_group_ingress(group_id, permissions)
  modify_security_group(:grant, :ingress, group_id, permissions)
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"}


198
199
200
201
202
203
204
205
# File 'lib/ec2/right_ec2.rb', line 198

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, :group_ids, :group_names, :private_ip_address

Returns a list of launched instances or an exception.

ec2.launch_instances( "ami-78779511",
                      :min_count => 1,
                      :group_names => ["default", "eugeg223123123"],
                      :user_data => 'Ohoho!',
                      :availability_zone => "us-east-1a",
                      :disable_api_termination => false,
                      :instance_initiated_shutdown_behavior => 'terminate',
                      :block_device_mappings => [ {:ebs_snapshot_id=>"snap-e40fd188",
                                                   :ebs_delete_on_termination=>true,
                                                   :device_name => "/dev/sdk",
                                                   :virtual_name => "mystorage"} ] ) #=>
  [{:hypervisor=>"xen",
    :private_dns_name=>"",
    :client_token=>"1309532374-551037-gcsBj-gEypk-piG06-ODfQm",
    :monitoring_state=>"disabled",
    :aws_availability_zone=>"us-east-1a",
    :root_device_name=>"/dev/sda1",
    :state_reason_code=>"pending",
    :dns_name=>"",
    :tags=>{},
    :aws_reason=>"",
    :virtualization_type=>"paravirtual",
    :state_reason_message=>"pending",
    :aws_reservation_id=>"r-6fada703",
    :aws_ramdisk_id=>"ari-a51cf9cc",
    :ami_launch_index=>"0",
    :groups=>
     [{:group_id=>"sg-a0b85dc9", :group_name=>"default"},
      {:group_id=>"sg-70733019", :group_name=>"eugeg223123123"}],
    :aws_owner=>"826693181925",
    :aws_instance_type=>"m1.small",
    :aws_state=>"pending",
    :root_device_type=>"ebs",
    :aws_image_id=>"ami-78779511",
    :aws_kernel_id=>"aki-a71cf9ce",
    :aws_launch_time=>"2011-07-01T14:59:35.000Z",
    :aws_state_code=>0,
    :aws_instance_id=>"i-4f202621",
    :aws_product_codes=>[]}]


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

def launch_instances(image_id, options={})
  options[:user_data] = options[:user_data].to_s
  params = map_api_keys_and_values( options,
    :key_name, :addressing_type, :kernel_id,
    :ramdisk_id, :subnet_id, :instance_initiated_shutdown_behavior,
    :private_ip_address, :additional_info, :license_pool,
    :image_id                => { :value => image_id },
    :min_count               => { :value => options[:min_count] || 1 },
    :max_count               => { :value => options[:max_count] || options[:min_count] || 1 },
    :placement_tenancy       => 'Placement.Tenancy',
    :placement_group_name    => 'Placement.GroupName',
    :availability_zone       => 'Placement.AvailabilityZone',
    :group_names             => { :amazonize_list => 'SecurityGroup' },
    :group_ids               => { :amazonize_list => 'SecurityGroupId' },
    :block_device_mappings   => { :amazonize_bdm  => 'BlockDeviceMapping' },
    :instance_type           => { :value => options[:instance_type] || DEFAULT_INSTANCE_TYPE },
    :disable_api_termination => { :value => Proc.new{ !options[:disable_api_termination].nil? && options[:disable_api_termination].to_s }},
    :client_token            => { :value => !@params[:eucalyptus] && (options[:client_token] || AwsUtils::generate_unique_token)},
    :user_data               => { :value => Proc.new { !options[:user_data].empty? && Base64.encode64(options[:user_data]).delete("\n") }},
    :monitoring_enabled      => { :name  => 'Monitoring.Enabled',
                                  :value => Proc.new{ options[:monitoring_enabled] && options[:monitoring_enabled].to_s }})
  # 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, value) ⇒ 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 can take next values: 'launchPermission', 'productCode', 'description'.
Value is a String for'description'. is a String or an Array for 'productCode' and
is a Hash {:add_user_ids, :add_groups, :remove_user_ids, :remove_groups } for 'launchPermission'.


249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/ec2/right_ec2_images.rb', line 249

def modify_image_attribute(image_id, attribute, value)
  params = { 'ImageId' => image_id }
  case attribute.to_s
  when 'launchPermission'
    params.update(amazonize_list('LaunchPermission.Add.?.UserId',    value[:add_user_ids]))
    params.update(amazonize_list('LaunchPermission.Add.?.Group',     value[:add_groups]))
    params.update(amazonize_list('LaunchPermission.Remove.?.UserId', value[:remove_user_ids]))
    params.update(amazonize_list('LaunchPermission.Remove.?.Group',  value[:remove_groups]))
  when 'productCode'
    params.update(amazonize_list('ProductCode', value))
  when 'description'
    params['Description.Value'] = value
  end
  link = generate_request("ModifyImageAttribute", params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_image_description(image_id, description) ⇒ Object

Modify image description

ec2.modify_image_product_code('ami-e444444d','My cool image') #=> true


314
315
316
# File 'lib/ec2/right_ec2_images.rb', line 314

def modify_image_description(image_id, description)
  modify_image_attribute(image_id, 'description', description)
end

#modify_image_launch_perm_add_groups(image_id, *groups) ⇒ 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


290
291
292
# File 'lib/ec2/right_ec2_images.rb', line 290

def modify_image_launch_perm_add_groups(image_id, *groups)
  modify_image_attribute(image_id, 'launchPermission', :add_groups => groups.flatten)
end

#modify_image_launch_perm_add_users(image_id, *user_ids) ⇒ 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


273
274
275
# File 'lib/ec2/right_ec2_images.rb', line 273

def modify_image_launch_perm_add_users(image_id, *user_ids)
  modify_image_attribute(image_id, 'launchPermission', :add_user_ids => user_ids.flatten)
end

#modify_image_launch_perm_remove_groups(image_id, *groups) ⇒ 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


298
299
300
# File 'lib/ec2/right_ec2_images.rb', line 298

def modify_image_launch_perm_remove_groups(image_id, *groups)
  modify_image_attribute(image_id, 'launchPermission', :remove_groups => groups.flatten)
end

#modify_image_launch_perm_remove_users(image_id, *user_ids) ⇒ 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


281
282
283
# File 'lib/ec2/right_ec2_images.rb', line 281

def modify_image_launch_perm_remove_users(image_id, *user_ids)
  modify_image_attribute(image_id, 'launchPermission', :remove_user_ids => user_ids.flatten)
end

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

Add product code to image

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


306
307
308
# File 'lib/ec2/right_ec2_images.rb', line 306

def modify_image_product_code(image_id, product_codes=[])
  modify_image_attribute(image_id, 'productCodes',product_codes)
end

#modify_instance_attribute(instance_id, attribute, value) ⇒ Object

Modify instance attribute.

Attributes: ‘InstanceType’, ‘Kernel’, ‘Ramdisk’, ‘UserData’, ‘DisableApiTermination’, ‘InstanceInitiatedShutdownBehavior’, ‘SourceDestCheck’, ‘GroupId’

ec2.modify_instance_attribute(instance, 'instanceInitiatedShutdownBehavior", "stop") #=> true


378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/ec2/right_ec2_instances.rb', line 378

def modify_instance_attribute(instance_id, attribute, value)
  request_hash = {'InstanceId' => instance_id}
  attribute = attribute.to_s.right_underscore.right_camelize
  case attribute
  when 'UserData' then request_hash["#{attribute}.Value"] = Base64.encode64(value).delete("\n")
  when 'GroupId'  then request_hash.merge!(amazonize_list('GroupId', value))
  else                 request_hash["#{attribute}.Value"] = value
  end
  link = generate_request('ModifyInstanceAttribute', request_hash)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_security_group(action, direction, group_id, permissions) ⇒ Object

Modify AWS security group permissions.

Options:
  action      - :authorize (or :grant) | :revoke (or :remove)
  direction   - :ingress | :egress
  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 | -1
    # or (ingress)
    :groups             => { UserId1 => GroupId1, UserName2 => GroupId2 }
    :groups             => [ [ UserId1, GroupId1 ], [ UserName2 => GroupId2 ] ]
    # or (egress)
    :groups             => [ GroupId1, GroupId2 ]
    # 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(:authorize, :ingress, 'sg-75d1c319',
                          :cidr_ip  =>  "127.0.0.0/31",
                          :port     => 811,
                          :protocol => 'tcp' ) #=> true

ec2.modify_security_group(:revoke, :ingress, 'sg-75d1c319',
                          :cidr_ips =>  ["127.0.0.1/32", "127.0.0.2/32"],
                          :port     => 812,
                          :protocol => 'tcp' ) #=> true

# Group based permissions:

ec2.modify_security_group(:authorize, :ingress, 'sg-75d1c319',
                          :groups   => { "586789340000" => "sg-75d1c300",
                                         "635201710000" => "sg-75d1c301" },
                          :port     => 801,
                          :protocol => 'tcp' ) #=> true

ec2.modify_security_group(:revoke, :ingress, 'sg-75d1c319',
                          :groups   => [[ "586789340000", "sg-75d1c300" ],
                                        [ "586789340000", "sg-75d1c302" ]],
                          :port     => 809,
                          :protocol => 'tcp' ) #=> true

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

ec2.modify_security_group(:authorize, :ingress, 'sg-75d1c319',
                          [{ :groups   => { "586789340000" => "sg-75d1c300",
                                            "635201710000" => "sg-75d1c301" },
                                            :port          => 803,
                                            :protocol      => 'tcp'},
                           { :cidr_ips =>  ["127.0.0.1/32", "127.0.0.2/32"],
                             :port     => 812,
                             :protocol => 'tcp' }]) #=> true


261
262
263
264
265
266
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/ec2/right_ec2_security_groups.rb', line 261

def modify_security_group(action, direction, group_id, permissions)
  hash = {}
  raise "Unknown action #{action.inspect}!"       unless [:authorize, :grant, :revoke, :remove].include?(action)
  raise "Unknown direction #{direction.inspect}!" unless [:ingress, :egress].include?(direction)
  # Remote action
  remote_action = case action
                  when :authorize, :grant  then direction == :ingress ? "AuthorizeSecurityGroupIngress" : "AuthorizeSecurityGroupEgress"
                  when :revoke,    :remove then direction == :ingress ? "RevokeSecurityGroupIngress"    : "RevokeSecurityGroupEgress"
                  end
  # Group Name
  hash["GroupId"] = group_id
  # Permissions
  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
    # Groups
    case direction
    when :ingress
      #  :groups => {UserId1 => GroupId1, ... UserIdN => GroupIdN}
      #  or (this allows using same UserId multiple times )
      #  :groups => [[UserId1, GroupId1], ... [UserIdN, GroupIdN]]
      #  or even (unset user is == current account user)
      #  :groups => [GroupId1, GroupId2, ... GroupIdN]
      #  :groups => [[UserId1, GroupId1], GroupId2, ... GroupIdN, ... [UserIdM, GroupIdM]]
      #
      index = 1
      unless permission[:group_names].right_blank?
        owner_and_groups = []
        groups_only      = []
        Array(permission[:group_names]).each do |item|
          if item.is_a?(Array) && item.size == 2
            owner_and_groups << item
          else
            groups_only << item
          end
        end
        hash.merge!(amazonize_list( ["IpPermissions.#{pid}.Groups.?.UserId", "IpPermissions.#{pid}.Groups.?.GroupName"], owner_and_groups, :index => index ))
        index += owner_and_groups.size
        groups_only = groups_only.flatten
        hash.merge!(amazonize_list( "IpPermissions.#{pid}.Groups.?.GroupName", groups_only, :index => index ))
        index += groups_only.size
      end
      unless permission[:groups].right_blank?
        owner_and_groups = []
        groups_only      = []
        Array(permission[:groups]).each do |item|
          if item.is_a?(Array) && item.size == 2
            owner_and_groups << item
          else
            groups_only << item
          end
        end
        hash.merge!(amazonize_list( ["IpPermissions.#{pid}.Groups.?.UserId", "IpPermissions.#{pid}.Groups.?.GroupId"], owner_and_groups, :index => index ))
        index += owner_and_groups.size
        groups_only = groups_only.flatten
        hash.merge!(amazonize_list( "IpPermissions.#{pid}.Groups.?.GroupId", groups_only, :index => index ))
      end
    when :egress
      #  :groups => [GroupId1, ... GroupIdN]
      hash.merge!(amazonize_list( "IpPermissions.#{pid}.Groups.?.GroupId", permission[:groups] ))
    end
    # 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(remote_action, hash)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_snapshot_attribute(snapshot_id, attribute, value) ⇒ Object

Modify snapshot attribute.

Attribute can take only 'createVolumePermission' value.
Value is a Hash {:add_user_ids, :add_groups, :remove_user_ids, :remove_groups }.


291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/ec2/right_ec2_ebs.rb', line 291

def modify_snapshot_attribute(snapshot_id, attribute, value)
  params = { 'SnapshotId' => snapshot_id }
  case attribute.to_s
  when 'createVolumePermission'
    params.update(amazonize_list('CreateVolumePermission.Add.?.UserId',    value[:add_user_ids]))
    params.update(amazonize_list('CreateVolumePermission.Add.?.Group',     value[:add_groups]))
    params.update(amazonize_list('CreateVolumePermission.Remove.?.UserId', value[:remove_user_ids]))
    params.update(amazonize_list('CreateVolumePermission.Remove.?.Group',  value[:remove_groups]))
  end
  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, *groups) ⇒ 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


326
327
328
329
330
# File 'lib/ec2/right_ec2_ebs.rb', line 326

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

#modify_snapshot_attribute_create_volume_permission_add_users(snapshot_id, *user_ids) ⇒ Object

Grant create volume permission for a list of users.

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


310
311
312
# File 'lib/ec2/right_ec2_ebs.rb', line 310

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

#modify_snapshot_attribute_create_volume_permission_remove_groups(snapshot_id, *groups) ⇒ 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


336
337
338
339
340
# File 'lib/ec2/right_ec2_ebs.rb', line 336

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

#modify_snapshot_attribute_create_volume_permission_remove_users(snapshot_id, *user_ids) ⇒ Object

Revoke create volume permission for a list of users.

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


318
319
320
# File 'lib/ec2/right_ec2_ebs.rb', line 318

def modify_snapshot_attribute_create_volume_permission_remove_users(snapshot_id, *user_ids)
  modify_snapshot_attribute(snapshot_id, 'createVolumePermission', :remove_user_ids => user_ids.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

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


101
102
103
104
105
106
107
# File 'lib/ec2/right_ec2_reserved_instances.rb', line 101

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


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

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(options = {}) ⇒ Object

Release an elastic IP address associated with your account. Options: :public_ip, :allocation_id. Returns true or an exception.

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


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

def release_address(options = {})
  request_hash = {}
  request_hash['PublicIp']     = options[:public_ip]     unless options[:public_ip].right_blank?
  request_hash['AllocationId'] = options[:allocation_id] unless options[:allocation_id].right_blank?
  link = generate_request("ReleaseAddress", request_hash)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#replace_route(route_table_id, destination_cidr_block, options = {}) ⇒ Object

Replaces an existing route within a route table in a VPC Options: :gateway_id, :instance_id

ec2.replace_route("rtb-be3006d7",  "0.0.0.2/32", :gateway_id => 'igw-6585c10c') #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRoute.html



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

def replace_route(route_table_id, destination_cidr_block, options = {})
  request_hash = { 'RouteTableId'         => route_table_id,
                   'DestinationCidrBlock' => destination_cidr_block }
  request_hash['GatewayId']  = options[:gateway_id]  unless options[:gateway_id].right_blank?
  request_hash['InstanceId'] = options[:instance_id] unless options[:instance_id].right_blank?      
  link = generate_request("ReplaceRoute", request_hash)
  request_info(link, RightHttp2xxParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#replace_route_table_association(route_table_id, route_table_association_id) ⇒ Object

Changes the route table associated with a given subnet in a VPC. After you execute this action, the subnet uses the routes in the new route table it’s associated with. You can also use this action to change which table is the main route table in the VPC. You just specify the main route table’s association ID and the route table that you want to be the new main route table.

ec2.replace_route_table_association("rtb-be3006d7", "rtbassoc-a02610c9") #=> true

P.S. docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ReplaceRouteTableAssociation.html



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

def replace_route_table_association(route_table_id, route_table_association_id)
  request_hash = { 'RouteTableId'  => route_table_id,
                   'AssociationId' => route_table_association_id }
  link = generate_request("ReplaceRouteTableAssociation", request_hash)
  request_info(link, RightHttp2xxParser.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,
  :group_ids => ["sg-a0b85dc9"],
  :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=>[{:group_id=>"sg-a0b85dc9", :group_name=>"default"}],
    :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=>[{:group_id=>"sg-a0b85dc9", :group_name=>"default"}],
    :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',
  :group_names => ['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'
                               } ] ) #=>
  [{:type=>"one-time",
    :image_id=>"ami-08f41161",
    :availability_zone_group=>"azg1",
    :key_name=>"default",
    :spot_instance_request_id=>"sir-66c79a12",
    :block_device_mappings=>
     [{:ebs_volume_size=>3,
       :virtual_name=>"ephemeral2",
       :device_name=>"/dev/sdk",
       :ebs_snapshot_id=>"snap-145cbc7d",
       :ebs_delete_on_termination=>true}],
    :spot_price=>0.01,
    :product_description=>"Linux/UNIX",
    :state=>"open",
    :instance_type=>"m1.small",
    :availability_zone=>"us-east-1a",
    :groups=>[{:group_id=>"sg-a0b85dc9", :group_name=>"default"}],
    :valid_from=>"2011-07-01T14:26:33.000Z",
    :tags=>{},
    :monitoring_enabled=>true,
    :valid_until=>"2011-07-01T14:28:03.000Z",
    :create_time=>"2011-07-01T14:26:24.000Z",
    :launch_group=>"lg1"}]


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

def request_spot_instances(options)
  options[:user_data] = options[:user_data].to_s
  request_hash = map_api_keys_and_values( options,
    :spot_price, :availability_zone_group, :launch_group, :type, :instance_count,
    :image_id              => 'LaunchSpecification.ImageId',
    :instance_type         => 'LaunchSpecification.InstanceType',
    :key_name              => 'LaunchSpecification.KeyName',
    :addressing_type       => 'LaunchSpecification.AddressingType',
    :kernel_id             => 'LaunchSpecification.KernelId',
    :ramdisk_id            => 'LaunchSpecification.RamdiskId',
    :subnet_id             => 'LaunchSpecification.SubnetId',
    :availability_zone     => 'LaunchSpecification.Placement.AvailabilityZone',
    :monitoring_enabled    => 'LaunchSpecification.Monitoring.Enabled',
    :valid_from            => { :value => Proc.new { !options[:valid_from].right_blank?  && AwsUtils::utc_iso8601(options[:valid_from]) }},
    :valid_until           => { :value => Proc.new { !options[:valid_until].right_blank? && AwsUtils::utc_iso8601(options[:valid_until]) }},
    :user_data             => { :name  => 'LaunchSpecification.UserData',
                                :value => Proc.new { !options[:user_data].empty? && Base64.encode64(options[:user_data]).delete("\n") }},
    :group_names           => { :amazonize_list => 'LaunchSpecification.SecurityGroup'},
    :group_ids             => { :amazonize_list => 'LaunchSpecification.SecurityGroupId'},
    :block_device_mappings => { :amazonize_bdm  => 'LaunchSpecification.BlockDeviceMapping'})
  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


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

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’, ‘sourceDestCheck’

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


362
363
364
365
366
367
368
369
# File 'lib/ec2/right_ec2_instances.rb', line 362

def reset_instance_attribute(instance_id, attribute)
  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


277
278
279
280
281
282
283
284
# File 'lib/ec2/right_ec2_ebs.rb', line 277

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_egress(group_id, permissions) ⇒ Object



198
199
200
# File 'lib/ec2/right_ec2_security_groups.rb', line 198

def revoke_security_group_egress(group_id, permissions)
  modify_security_group(:revoke, :egress, group_id, permissions)
end

#revoke_security_group_ingress(group_id, permissions) ⇒ Object



190
191
192
# File 'lib/ec2/right_ec2_security_groups.rb', line 190

def revoke_security_group_ingress(group_id, permissions)
  modify_security_group(:revoke, :ingress, group_id, permissions)
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


428
429
430
# File 'lib/ec2/right_ec2_security_groups.rb', line 428

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


411
412
413
# File 'lib/ec2/right_ec2_security_groups.rb', line 411

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_names, 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,['2009-07-15-default'],'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",
   :groups             => [{:group_name=>"2009-07-15-default", :group_id=>"sg-90c5d6fc"}],
   :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"
   }]


149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/ec2/right_ec2_instances.rb', line 149

def run_instances(image_id, min_count, max_count, group_names, 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_names                          => group_names,
                               :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}]


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

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_and_options) ⇒ Object

Stop instances.

Options: :force => true|false

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


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

def stop_instances(*instance_aws_ids_and_options)
  list, options = AwsUtils::split_items_and_params(instance_aws_ids_and_options)
  request_hash = {}
  request_hash['Force'] = true if options[:force]
  request_hash.merge!(amazonize_list('InstanceId', list))
  link = generate_request("StopInstances", request_hash)
  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"}]


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

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


230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/ec2/right_ec2_ebs.rb', line 230

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