Class: Aws::Ec2

Inherits:
AwsBase show all
Includes:
AwsBaseInterface
Defined in:
lib/ec2/ec2.rb

Overview

Aws::EC2 – RightScale Amazon EC2 interface

The Aws::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   = Aws::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 Aws::AwsError in case of problems. Note that transient errors are automatically retried.

Defined Under Namespace

Classes: QEc2AllocateAddressParser, QEc2AttachAndDetachVolumeParser, QEc2AttachNetworkInterfaceParser, QEc2BundleInstanceParser, QEc2ConfirmProductInstanceParser, QEc2CreateImageParser, QEc2CreateKeyPairParser, QEc2CreateSnapshotParser, QEc2CreateVolumeParser, QEc2DescribeAddressesParser, QEc2DescribeAvailabilityZonesParser, QEc2DescribeBundleTasksParser, QEc2DescribeImageAttributeParser, QEc2DescribeImagesParser, QEc2DescribeInstancesParser, QEc2DescribeKeyPairParser, QEc2DescribeRegionsParser, QEc2DescribeSecurityGroupsParser, QEc2DescribeSnapshotsParser, QEc2DescribeTagsParser, QEc2DescribeVolumesParser, QEc2GetConsoleOutputParser, QEc2ImportPublicKeyParser, QEc2IpPermissionType, QEc2IpRangeItemType, QEc2MonitorInstancesParser, QEc2NetworkInterfacesParser, QEc2RegisterImageParser, QEc2SecurityGroupItemType, QEc2StartInstancesParser, QEc2StopInstancesParser, QEc2SubnetsParser, QEc2TerminateInstancesParser, QEc2UserIdGroupPairType, QEc2VpcsParser, RightBoolResponseParser

Constant Summary collapse

API_VERSION =

Amazon EC2 API version being used

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

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

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

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

'm1.small'
INSTANCE_TYPES =
['t1.micro', 'm1.small', 'c1.medium', 'm1.large', 'm1.xlarge', 'c1.xlarge']
@@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 AwsBaseInterface

AwsBaseInterface::DEFAULT_SIGNATURE_VERSION

Constants inherited from AwsBase

AwsBase::AMAZON_PROBLEMS

Instance Attribute Summary

Attributes included from AwsBaseInterface

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

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AwsBaseInterface

#cache_hits?, caching, caching=, #caching?, #close_conn, #close_connection, #connection, #escape_params, #generate_request2, #get_conn, #init, #multi_thread, #on_exception, #request_cache_or_info, #request_info2, #request_info3, #request_info_impl, #request_info_xml_simple, #request_info_xml_simple3, #signed_service_params, #symbolize, #update_cache

Methods inherited from AwsBase

amazon_problems, amazon_problems=

Constructor Details

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

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

  • :endpoint_url a fully qualified url to Amazon API endpoint (this overwrites: :server, :port, :service, :protocol and :region). Example: ‘eu-west-1.ec2.amazonaws.com/’

  • :server: EC2 service host, default: DEFAULT_HOST

  • :region: EC2 region (North America by default)

  • :port: EC2 service port, default: DEFAULT_PORT

  • :protocol: ‘http’ or ‘https’, default: DEFAULT_PROTOCOL

  • :multi_thread: true=HTTP connection per thread, false=per process

  • :logger: for log messages, default: Rails.logger else STDOUT

  • :signature_version: The signature version : ‘0’ or ‘1’(default)

  • :cache: true/false: caching for: ec2_describe_images, describe_instances,

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



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/ec2/ec2.rb', line 127

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,
        :api_version      => API_VERSION},
       aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'],
       aws_secret_access_key|| ENV['AWS_SECRET_ACCESS_KEY'],
       params)
  # EC2 doesn't really define any transient errors to retry, and in fact,
  # when they return a 503 it is usually for 'request limit exceeded' which
  # we most certainly should not retry.  So let's pare down the list of
  # retryable errors to InternalError only (see AwsBase for the default
  # list)
  amazon_problems = ['InternalError']
end

Class Method Details

.apiObject



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

def self.api
  @@api
end

.benchObject



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

def self.bench
  @@bench
end

.bench_ec2Object



100
101
102
# File 'lib/ec2/ec2.rb', line 100

def self.bench_ec2
  @@bench.service
end

.bench_xmlObject



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

def self.bench_xml
  @@bench.xml
end

.connection_nameObject



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

def self.connection_name
  :ec2_connection
end

Instance Method Details

#allocate_addressObject

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

ec2.allocate_address #=> '75.101.154.140'


1070
1071
1072
1073
1074
1075
# File 'lib/ec2/ec2.rb', line 1070

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

#associate_address(instance_id, public_ip) ⇒ Object

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

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


1082
1083
1084
1085
1086
1087
1088
1089
# File 'lib/ec2/ec2.rb', line 1082

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

#attach_network_interface(network_interface_id, instance_id, device_index) ⇒ Object

Attach a network interface to an instance docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachNetworkInterface.html

ec2.attach_network_interface(“eni-ffda3197”, “i-9cc316fe”, 1)



1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
# File 'lib/ec2/ec2.rb', line 1569

def attach_network_interface(network_interface_id, instance_id, device_index)
  params = {
    "NetworkInterfaceId" => network_interface_id,
    "InstanceId" => instance_id,
    "DeviceIndex" => device_index,
    "Version" => "2013-02-01",
  }
  link = generate_request('AttachNetworkInterface', params)
  request_info(link, QEc2AttachNetworkInterfaceParser.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" }


1286
1287
1288
1289
1290
1291
1292
1293
1294
# File 'lib/ec2/ec2.rb', line 1286

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

#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


970
971
972
973
974
975
976
977
978
979
980
# File 'lib/ec2/ec2.rb', line 970

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

#authorize_security_group_named_ingress(name, owner, group) ⇒ Object

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

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


941
942
943
944
945
946
947
948
949
# File 'lib/ec2/ec2.rb', line 941

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

#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, Aws::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"}]


741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
# File 'lib/ec2/ec2.rb', line 741

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' => s3_expires.strftime('%Y-%m-%dT%H:%M:%SZ'),
                     'conditions' => [{'bucket' => s3_bucket},
                                      {'acl' => s3_upload_policy},
                                      ['starts-with', '$key', s3_prefix]]}.to_json
  policy64        = Base64.encode64(policy).gsub("\n", "")
  signed_policy64 = Utils.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"}


805
806
807
808
809
810
# File 'lib/ec2/ec2.rb', line 805

def cancel_bundle_task(bundle_id)
  link = generate_request("CancelBundleTask", {'BundleId' => bundle_id})
  request_info(link, QEc2BundleInstanceParser.new)
rescue Exception
  on_exception
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"


457
458
459
460
461
# File 'lib/ec2/ec2.rb', line 457

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_image(instance_id, name, description = "") ⇒ Object

Creates an Amazon EBS-backed AMI from an Amazon EBS-backed instance Instance must be either the running or stopped state

ec2.create_image(‘i-4jhdmaw’, ‘New image’)



1266
1267
1268
1269
1270
1271
1272
1273
1274
# File 'lib/ec2/ec2.rb', line 1266

def create_image(instance_id, name, description="")
  link = generate_request("CreateImage",
                          "InstanceId" => instance_id,
                          "Name" => name,
                          "Description" => description)
  request_info(link, QEc2CreateImageParser.new(:logger => @logger))
rescue
    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-----"}


1024
1025
1026
1027
1028
1029
1030
# File 'lib/ec2/ec2.rb', line 1024

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_network_interface(subnet_id, *args) ⇒ Object

Create a new network interface in a VPC docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateNetworkInterface.html

ec2.create_network_interface(“subnet-a61dafcf”)



1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
# File 'lib/ec2/ec2.rb', line 1552

def create_network_interface(subnet_id, *args)
  if args.last.is_a?(Hash)
    params = args.pop.dup
  else
    params = {}
  end
  params.merge!({'SubnetId' => subnet_id, 'Version' => "2013-02-01"})
  link = generate_request('CreateNetworkInterface', params)
  request_info(link, QEc2NetworkInterfacesParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_security_group(name, description) ⇒ Object

Create new Security Group. Returns true or an exception.

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


876
877
878
879
880
881
882
883
884
885
# File 'lib/ec2/ec2.rb', line 876

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

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

Create a snapshot of specified volume.

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


1365
1366
1367
1368
1369
1370
# File 'lib/ec2/ec2.rb', line 1365

def create_snapshot(volume_id, options={})
  link = generate_request("CreateSnapshot", options.merge({"VolumeId" => volume_id.to_s}))
  request_info(link, QEc2CreateSnapshotParser.new(:logger => @logger))
rescue Exception
  on_exception
end

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

Create subnet in a VPC docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSubnet.html

ec2.create_subnet(vpc_id, cidr_block) ec2.create_subnet(vpc_id, cidr_block, availability_zone))



1619
1620
1621
1622
1623
1624
1625
1626
# File 'lib/ec2/ec2.rb', line 1619

def create_subnet(vpc_id, cidr_block, availability_zone = nil)
  params = { "VpcId" => vpc_id, "CidrBlock" => cidr_block }
  params["AvailabilityZone"] = availability_zone if availability_zone
  link = generate_request("CreateSubnet", params)
  request_info(link, QEc2SubnetsParser.new("subnet", :logger => @logger))
rescue Exception
  on_exception
end

#create_tag(resource_id, key, value = nil) ⇒ Object

Add/replace one tag to a resource docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference_query_CreateTags.html

ec2.create_tag('ami-1a2b3c4d', 'webserver') #=> true
ec2.create_tag('i-7f4d3a2b',   'stack', 'Production') #=> true


1429
1430
1431
1432
1433
1434
1435
1436
1437
# File 'lib/ec2/ec2.rb', line 1429

def create_tag(resource_id, key, value = nil)
  link = generate_request("CreateTags",
                          "ResourceId.1" => resource_id.to_s,
                          "Tag.1.Key"    => key.to_s,
                          "Tag.1.Value"  => value.to_s)
  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 => Tue Jun 24 18:13:32 UTC 2008,
     :aws_size       => 94}


1238
1239
1240
1241
1242
1243
1244
1245
1246
# File 'lib/ec2/ec2.rb', line 1238

def create_volume(snapshot_id, size, zone)
  params = {'Size' => size.to_s, 'AvailabilityZone' => zone.to_s}
  params['SnapshotId'] = snapshot_id if snapshot_id && snapshot_id.length > 0 # snapshotId is conditional
  link = generate_request("CreateVolume",
                          params)
  request_info(link, QEc2CreateVolumeParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#create_vpc(cidr_block = "10.0.0.0/16") ⇒ Object

Create VPC docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVpc.html

ec2.create_vpc(“10.0.0.0/16”) FIXME: EVen though the EC2 docs describe the parameter instanceTenancy, I could not get it to recognize that



1486
1487
1488
1489
1490
1491
1492
# File 'lib/ec2/ec2.rb', line 1486

def create_vpc(cidr_block = "10.0.0.0/16")
  params = { "CidrBlock" => cidr_block }
  link = generate_request("CreateVpc", params)
  request_info(link, QEc2VpcsParser.new("vpc", :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


1053
1054
1055
1056
1057
1058
1059
# File 'lib/ec2/ec2.rb', line 1053

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_network_interface(network_interface_id) ⇒ Object

Delete a network interface from a VPC docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteNetworkInterface.html

ec2.delete_network_interface(“eni-ffda3197”)



1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
# File 'lib/ec2/ec2.rb', line 1603

def delete_network_interface(network_interface_id)
  params = {
    "NetworkInterfaceId" => network_interface_id,
    "Version" => "2013-02-01",
  }
  link = generate_request('DeleteNetworkInterface', params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_security_group(name) ⇒ Object

Remove Security Group. Returns true or an exception.

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


891
892
893
894
895
896
897
# File 'lib/ec2/ec2.rb', line 891

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

#delete_snapshot(snapshot_id) ⇒ Object

Delete the specified snapshot.

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


1415
1416
1417
1418
1419
1420
1421
# File 'lib/ec2/ec2.rb', line 1415

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_subnet(subnet_id) ⇒ Object



1653
1654
1655
1656
1657
1658
1659
# File 'lib/ec2/ec2.rb', line 1653

def delete_subnet(subnet_id)
  params = { "SubnetId" => subnet_id }
  link = generate_request("DeleteSubnet", params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#delete_tag(resource_id, key, value = nil) ⇒ Object

Delete one or all tags from a resource docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference_query_DeleteTags.html

ec2.delete_tag('i-7f4d3a2b', 'stack') #=> true
ec2.delete_tag('i-7f4d3a2b', 'stack', 'Production') #=> true

“If you omit Tag.n.Value, we delete the tag regardless of its value. If you specify this parameter with an empty string as the value, we delete the key only if its value is an empty string.” docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference_query_DeleteTags.html



1466
1467
1468
1469
1470
1471
1472
1473
1474
# File 'lib/ec2/ec2.rb', line 1466

def delete_tag(resource_id, key, value = nil)
  request_args = {"ResourceId.1" => resource_id.to_s, "Tag.1.Key" => key.to_s}
  request_args["Tag.1.Value"] = value.to_s if value

  link = generate_request("DeleteTags", request_args)
  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


1253
1254
1255
1256
1257
1258
1259
# File 'lib/ec2/ec2.rb', line 1253

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



1517
1518
1519
1520
1521
1522
1523
# File 'lib/ec2/ec2.rb', line 1517

def delete_vpc(vpc_id)
  params = { "VpcId" => vpc_id }
  link = generate_request("DeleteVpc", params)
  request_info(link, RightBoolResponseParser.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


290
291
292
293
294
295
296
# File 'lib/ec2/ec2.rb', line 290

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 = []) ⇒ Object

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

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

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


1099
1100
1101
1102
1103
1104
1105
# File 'lib/ec2/ec2.rb', line 1099

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

#describe_availability_zones(list = []) ⇒ Object

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

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

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


1148
1149
1150
1151
1152
1153
1154
# File 'lib/ec2/ec2.rb', line 1148

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

#describe_availability_zones2(options = {}) ⇒ Object

This is using the new way, but not sure it’s backwrads compatible



1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
# File 'lib/ec2/ec2.rb', line 1157

def describe_availability_zones2(options={})
  link = generate_request("DescribeAvailabilityZones", options={})
  request_info_xml_simple(self.class.connection_name, @params, link, @logger,
                          :group_tags     =>{"DBInstances"      =>"DBInstance",
                                             "DBParameterGroups"=>"DBParameterGroup",
                                             "DBSecurityGroups" =>"DBSecurityGroup",
                                             "EC2SecurityGroups"=>"EC2SecurityGroup",
                                             "IPRanges"         =>"IPRange"},
                          :force_array    =>["DBInstances",
                                             "DBParameterGroups",
                                             "DBSecurityGroups",
                                             "EC2SecurityGroups",
                                             "IPRanges"],
                          :pull_out_array =>options[:pull_out_array],
                          :pull_out_single=>options[:pull_out_single],
                          :wrapper        =>options[:wrapper])
rescue Exception
  on_exception
end

#describe_bundle_tasks(list = []) ⇒ Object

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

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


785
786
787
788
789
790
# File 'lib/ec2/ec2.rb', line 785

def describe_bundle_tasks(list=[])
  link = generate_request("DescribeBundleTasks", hash_params('BundleId', list.to_a))
  request_info(link, QEc2DescribeBundleTasksParser.new)
rescue Exception
  on_exception
end

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

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

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


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

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 = [], image_type = nil) ⇒ Object

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

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

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

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


241
242
243
244
245
# File 'lib/ec2/ec2.rb', line 241

def describe_images(list=[], image_type=nil)
  list      = list.to_a
  cache_for = list.empty? && !image_type ? :describe_images : nil
  ec2_describe_images({'ImageId' => list}, image_type, cache_for)
end

#describe_images_by_executable_by(list = ['self'], image_type = nil) ⇒ Object

Example:

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


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

def describe_images_by_executable_by(list=['self'], image_type=nil)
  list      = list.to_a
  cache_for = list==['self'] && !image_type ? :describe_images_by_executable_by : nil
  ec2_describe_images({'ExecutableBy' => list}, image_type, cache_for)
end

#describe_images_by_owner(list = ['self'], image_type = nil) ⇒ Object

Example:

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


253
254
255
256
257
# File 'lib/ec2/ec2.rb', line 253

def describe_images_by_owner(list=['self'], image_type=nil)
  list      = list.to_a
  cache_for = list==['self'] && !image_type ? :describe_images_by_owner : nil
  ec2_describe_images({'Owner' => list}, image_type, cache_for)
end

#describe_instances(list = []) ⇒ Object

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

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


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

def describe_instances(list=[])
  link = generate_request("DescribeInstances", hash_params('InstanceId', list.to_a))
  request_cache_or_info(:describe_instances, link, QEc2DescribeInstancesParser, @@bench, list.nil? || list.empty?) do |parser|
    get_desc_instances(parser.result)
  end
rescue Exception
  on_exception
end

#describe_key_pairs(list = []) ⇒ Object

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

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


1010
1011
1012
1013
1014
1015
# File 'lib/ec2/ec2.rb', line 1010

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

#describe_network_interfaces(*args) ⇒ Object

Describe network interfaces in a VPC docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeNetworkInterfaces.html

ec2.describe_network_interfaces ec2.describe_network_interfaces(ifaceId1, ifaceId2, …,

'Filter.1.Name' => 'addresses.primary',
'Filter.1.Value.1' => true,
'Filter.2.Name' => ...)


1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
# File 'lib/ec2/ec2.rb', line 1533

def describe_network_interfaces(*args)
  if args.last.is_a?(Hash)
    filters = args.pop.dup
  else
    filters = {}
  end
  ids = hash_params('NetworkInterfaceId', args)
  params = filters.merge(ids)
  params['Version'] = "2013-02-01"
  link = generate_request('DescribeNetworkInterfaces', params)
  request_info(link, QEc2NetworkInterfacesParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#describe_owned_snapshots(list = []) ⇒ Object



1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
# File 'lib/ec2/ec2.rb', line 1344

def describe_owned_snapshots(list=[])
  params = {"Owner" => "self"}
  snap_ids = hash_params('SnapshotId', list.to_a)
  params.update(snap_ids)
  link = generate_request("DescribeSnapshots",
                          params)
  request_cache_or_info :describe_owned_snapshots, link, QEc2DescribeSnapshotsParser, @@bench, list.nil? || list.empty?
rescue Exception
  on_exception
end

#describe_regions(list = []) ⇒ Object

Describe regions.

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


1186
1187
1188
1189
1190
1191
1192
# File 'lib/ec2/ec2.rb', line 1186

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

#describe_security_groups(list = []) ⇒ Object

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

ec2.describe_security_groups #=>
  [{:aws_group_name  => "default-1",
    :aws_owner       => "000000000888",
    :aws_description => "a default security group",
    :aws_perms       =>
      [ {:protocol => "tcp", :from_port=>"1000", :to_port=>"2000",
         :ip_ranges=>[{cidr_ip=>"10.1.2.3/32"}, {cidr_ip=>"192.168.1.10/24"}],
         :groups =>  [{:owner=>"123456789012", :group_name="default"}] },

        {:protocol ="icmp", :from_port="-1", :to_port=>"-1",
         :ip_ranges=>[{:cidr_ip=>"0.0.0.0/0"}],
         :groups=>[] },

        {:protocol=>"udp", :from_port=>"0", :to_port=>"65535",
         :ip_ranges=>[],
         :groups=>[{:owner=>"123456789012", :group_name=>"newgroup"}, {:owner=>"123456789012", :group_name=>"default"}],

        {:protocol=>"tcp", :from_port="22", :to_port=>"22",
         :ip_ranges=>[{:cidr_ip=>"0.0.0.0/0"}],
         :groups=>[{:owner=>"", :group_name=>"default"}] },

       ..., {...}
      ]


842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
# File 'lib/ec2/ec2.rb', line 842

def describe_security_groups(list=[])
  link = generate_request("DescribeSecurityGroups", hash_params('GroupName', list.to_a))
  request_cache_or_info(:describe_security_groups, link, QEc2DescribeSecurityGroupsParser, @@bench, list.nil? || list.empty?) do |parser|
  result = []
  parser.result.each do |item|
    perms = []
    item.ipPermissions.each do |perm|
      current = {:from_port => perm.fromPort,
                 :to_port => perm.toPort,
                 :protocol => perm.ipProtocol,
                 :groups => [], :ip_ranges => []}
      perm.groups.each do |ngroup|
         current[:groups] << {:group_name => ngroup.groupName, :owner => ngroup.userId}
      end
      perm.ipRanges.each do |cidr_ip|
         current[:ip_ranges] << {:cidr_ip => cidr_ip.cidrIp}
      end
    perms << current
    end
    result << {:aws_owner       => item.ownerId,
               :aws_group_name  => item.groupName,
               :aws_description => item.groupDescription,
               :aws_perms       => perms}
    end
    result
  end
rescue Exception
  on_exception
end

#describe_snapshots(list = []) ⇒ Object

Describe all EBS snapshots.

ec2.describe_snapshots #=>

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


1336
1337
1338
1339
1340
1341
1342
# File 'lib/ec2/ec2.rb', line 1336

def describe_snapshots(list=[])
  link = generate_request("DescribeSnapshots",
                          hash_params('SnapshotId', list.to_a))
  request_cache_or_info :describe_snapshots, link, QEc2DescribeSnapshotsParser, @@bench, list.nil? || list.empty?
rescue Exception
  on_exception
end

#describe_subnets(*args) ⇒ Object

Describe subnets docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html

ec2.describe_subnets ecs.describe_subnets(subnetId1, SubnetId2, …,

'Filter.1.Name' => 'state',
'Filter.1.Value.1' => 'pending',
'Filter.2.Name' => ...)


1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
# File 'lib/ec2/ec2.rb', line 1636

def describe_subnets(*args)
  if args.last.is_a?(Hash)
    params = args.pop.dup
  else
    params = {}
  end
  1.upto(args.size) { |i| params["SubnetId.#{i}"] = args[i-1] }
  link = generate_request("DescribeSubnets", params)
  request_info(link, QEc2SubnetsParser.new("item", :logger => @logger))
rescue Exception
  on_exception
end

#describe_tags(filters = {}) ⇒ Object

Describe tags docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference_query_DescribeTags.html

ec2.describe_tags
ec2.describe_tags(
  'Filter.1.Name' => 'resource-type', 'Filter.1.Value.1' => 'instance',
  'Filter.2.Name' => 'value',         'Filter.2.Value.1' => 'Test', 'Filter.2.Value.2' => 'Production'
)


1448
1449
1450
1451
1452
1453
# File 'lib/ec2/ec2.rb', line 1448

def describe_tags(filters = {})
  link = generate_request("DescribeTags", filters)
  request_info(link, QEc2DescribeTagsParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#describe_volumes(list = []) ⇒ Object

Describe all EBS volumes.

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


1219
1220
1221
1222
1223
1224
1225
# File 'lib/ec2/ec2.rb', line 1219

def describe_volumes(list=[])
  link = generate_request("DescribeVolumes",
                          hash_params('VolumeId', list.to_a))
  request_cache_or_info :describe_volumes, link, QEc2DescribeVolumesParser, @@bench, list.nil? || list.empty?
rescue Exception
  on_exception
end

#describe_vpcs(*args) ⇒ Object

Describe VPC’s docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVpcs.html

ec2.describe_vpcs ec2.describe_vpcs(vpcId1, vpcId2, ‘Filter.1.Name’ => ‘state’, ‘Filter.1.Value’ = > ‘pending’, …)



1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
# File 'lib/ec2/ec2.rb', line 1500

def describe_vpcs(*args)
  if args.last.is_a?(Hash)
    params = args.pop.dup
  else
    params = {}
  end
  1.upto(args.size) { |i| params["VpcId.#{i}"] = args[i-1] }
  link = generate_request("DescribeVpcs", params)
  request_info(link, QEc2VpcsParser.new("item", :logger => @logger))
rescue Exception
  on_exception
end

#detach_network_interface(attachment_id, force = false) ⇒ Object

Detach a network interface from an instance docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DetachNetworkInterface.html

ec2.detach_network_interface(“eni-attach-d94b09b0”) ec2.detach_network_interface(“eni-attach-d94b09b0”, true)



1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
# File 'lib/ec2/ec2.rb', line 1587

def detach_network_interface(attachment_id, force=false)
  params = {
    "AttachmentId" => attachment_id,
    "Force" => force,
    "Version" => "2013-02-01",
  }
  link = generate_request('DetachNetworkInterface', params)
  request_info(link, RightBoolResponseParser.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"}


1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
# File 'lib/ec2/ec2.rb', line 1305

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 Aws::Utils.blank?(instance_id)
  hash["Device"] = device.to_s unless Aws::Utils.blank?(device)
  hash["Force"] = 'true' if     force
  #
  link = generate_request("DetachVolume", hash)
  request_info(link, QEc2AttachAndDetachVolumeParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#disassociate_address(public_ip) ⇒ Object

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

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


1112
1113
1114
1115
1116
1117
1118
# File 'lib/ec2/ec2.rb', line 1112

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

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

params:

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


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

def ec2_describe_images(params={}, image_type=nil, cache_for=nil) #:nodoc:
  request_hash = {}
  params.each do |list_by, list|
    request_hash.merge! hash_params(list_by, list.to_a)
  end
  if image_type
    request_hash['Filter.1.Name']    = "image-type"
    request_hash['Filter.1.Value.1'] = image_type
  end
  link = generate_request("DescribeImages", request_hash)
  request_cache_or_info cache_for, link, QEc2DescribeImagesParser, @@bench, cache_for
rescue Exception
  on_exception
end

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

:nodoc:



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

def generate_request(action, params={}) #:nodoc:
  service_hash = {"Action"         => action,
                  "AWSAccessKeyId" => @aws_access_key_id,
                  "Version"        => @@api}
  service_hash.update(params)
  service_params = signed_service_params(@aws_secret_access_key, service_hash, :get, @params[:server], @params[:service])

  # use POST method if the length of the query string is too large
  if service_params.size > 2000
    if signature_version == '2'
      # resign the request because HTTP verb is included into signature
      service_params = signed_service_params(@aws_secret_access_key, service_hash, :post, @params[:server], @params[:service])
    end
    request                 = Net::HTTP::Post.new(@params[:service])
    request.body            = service_params
    request['Content-Type'] = 'application/x-www-form-urlencoded'
  else
    request = Net::HTTP::Get.new("#{@params[:service]}?#{service_params}")
  end
  # prepare output hash
  {:request  => request,
   :server   => @params[:server],
   :port     => @params[:port],
   :protocol => @params[:protocol]}
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 ..."


674
675
676
677
678
679
# File 'lib/ec2/ec2.rb', line 674

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



402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/ec2/ec2.rb', line 402

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

#get_initial_password(instance_id, private_key) ⇒ Object

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

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

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

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

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


714
715
716
717
718
719
720
721
722
723
724
# File 'lib/ec2/ec2.rb', line 714

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

#hash_params(prefix, list) ⇒ Object

:nodoc:



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

def hash_params(prefix, list) #:nodoc:
  groups = {}
  list.each_index { |i| groups.update("#{prefix}.#{i+1}"=>list[i]) } if list
  return groups
end

#hash_params_with_suffix(prefix, suffix, list) ⇒ Object

:nodoc:



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

def hash_params_with_suffix(prefix, suffix, list) #:nodoc:
  groups = {}
  list.each_index { |i| groups.update("#{prefix}.#{i+1}.suffix"=>list[i]) }
  return groups
end

#import_key_pair(name, public_key) ⇒ Object

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

ec2.import_key_pair('my_awesome_key',
                    'ssh-rsa AABB3NzaC1yc2FSAAADAQABAAABAQCntvz2Cpx8EE4lBRjQKOtwNaGeJXjgnFLaxnQH4HB+dRTinjlew+153KLCjAMbbanD9Wym/b1FfSHywP299RdTPpBZ2QD7Hh7qKp8penGszFQbaSewYQTBP9Htjn7NDg3VeVcIx0LP3lmp4ZNnYDZGLKCGJJ+ldT/cljW3FAA2/xwco98BujLlKUcU/BZlZ4zvESM3S0gF3pgOjuz2UKAEbsbuuaEQP88NZ/GXXIUgGNFoJSpxDrNCHA7pap/3gdyPq3zTkt4YK/bSxSJ24FMfYtehB36V9rqV8RsIro+yrzRBW4XcA976OKQbh5pS75rp herp@derp')
#=>
  {: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"}


1040
1041
1042
1043
1044
1045
1046
1047
# File 'lib/ec2/ec2.rb', line 1040

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

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

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

lparams keys (default values in parenthesis):

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

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


546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/ec2/ec2.rb', line 546

def launch_instances(image_id, options={})
  @logger.info("Launching instance of image #{image_id}, " +
                   "key: #{options[:key_name]}, groups: #{(options[:group_ids]).to_a.join(',')}")
  # careful: keyName and securityGroups may be nil
  params = hash_params('SecurityGroup', options[:group_ids].to_a)
  params.update({'ImageId'        => image_id,
                 'MinCount'       => (options[:min_count] || 1).to_s,
                 'MaxCount'       => (options[:max_count] || 1).to_s,
                 'AddressingType' => options[:addressing_type] || DEFAULT_ADDRESSING_TYPE,
                 'InstanceType'   => options[:instance_type] || DEFAULT_INSTANCE_TYPE})
  # optional params
  params.merge!(hash_params('SecurityGroupId',options[:SecurityGroupId].to_a)) unless Aws::Utils.blank?(options[:SecurityGroupId])
  params['KeyName'] = options[:key_name] unless Aws::Utils.blank?(options[:key_name])
  params['KernelId'] = options[:kernel_id] unless Aws::Utils.blank?(options[:kernel_id])
  params['RamdiskId'] = options[:ramdisk_id] unless Aws::Utils.blank?(options[:ramdisk_id])
  params['Placement.AvailabilityZone'] = options[:availability_zone] unless Aws::Utils.blank?(options[:availability_zone])
  params['BlockDeviceMappings'] = options[:block_device_mappings] unless Aws::Utils.blank?(options[:block_device_mappings])
  params['Monitoring.Enabled'] = options[:monitoring_enabled] unless Aws::Utils.blank?(options[:monitoring_enabled])
  params['SubnetId'] = options[:subnet_id] unless Aws::Utils.blank?(options[:subnet_id])
  params['AdditionalInfo'] = options[:additional_info] unless Aws::Utils.blank?(options[:additional_info])
  params['DisableApiTermination'] = options[:disable_api_termination].to_s unless options[:disable_api_termination].nil?
  params['InstanceInitiatedShutdownBehavior'] = options[:instance_initiated_shutdown_behavior] unless Aws::Utils.blank?(options[:instance_initiated_shutdown_behavior])
  unless Aws::Utils.blank?(options[:user_data])
    options[:user_data].strip!
    # Do not use CGI::escape(encode64(...)) as it is done in Amazons EC2 library.
    # Amazon 169.254.169.254 does not like escaped symbols!
    # And it doesn't like "\n" inside of encoded string! Grrr....
    # Otherwise, some of UserData symbols will be lost...
    params['UserData'] = Base64.encode64(options[:user_data]).delete("\n").strip unless Aws::Utils.blank?(options[:user_data])
  end
  unless Aws::Utils.blank?(options[:block_device_mappings])
    options[:block_device_mappings].size.times do |n|
      if options[:block_device_mappings][n][:virtual_name]
        params["BlockDeviceMapping.#{n+1}.VirtualName"] = options[:block_device_mappings][n][:virtual_name]
      end
      if options[:block_device_mappings][n][:device_name]
        params["BlockDeviceMapping.#{n+1}.DeviceName"] = options[:block_device_mappings][n][:device_name]
      end
      if options[:block_device_mappings][n][:ebs_snapshot_id]
        params["BlockDeviceMapping.#{n+1}.Ebs.SnapshotId"] = options[:block_device_mappings][n][:ebs_snapshot_id]
      end
    end
  end
  link      = generate_request("RunInstances", params)
  #debugger
  instances = request_info(link, QEc2DescribeInstancesParser.new(:logger => @logger))
  get_desc_instances(instances)
rescue Exception
  on_exception
end

#manage_security_group_ingress(name, from_port, to_port, protocol, action, source_ip_ranges, source_groups = []) ⇒ Object

Authorize OR Revoke ingress for security group, depending on the value of the ‘action’ parameter. If you ‘authorize’ then you allow instances that are member of some other security groups, or some range of ip addresses to open connections to instances in my group. Can specify an array of ip addresses, source groups or mix of both in a single rule:

ec2.manage_security_group_ingress(‘authorize’, ‘new_firewall’, 80, 80, ‘tcp’, [‘192.168.0.1/32’, ‘10.0.0.1/24’],

[{'group_name'=>'default', 'owner'=>'297467797945'}, {'group_name'=>'test', 'owner'=>'123456789012'}])

ec2.manage_security_group_ingress(‘new_firewall’, 0, 1000, ‘udp’, ‘revoke’, [],

[{'group_name'=>'default', 'owner'=>'123456789012'}])

ec2.manage_security_group_ingress(‘new_firewall’, 0, 1000, ‘udp’, ‘authorize’, [‘0.0.0.0/0’])

Similarly, if you specify ‘revoke’ as the action parameter then you will remove the specified source ip addresses or source groups from access to instances in the named group:



915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# File 'lib/ec2/ec2.rb', line 915

def manage_security_group_ingress(name, from_port, to_port, protocol, action, source_ip_ranges, source_groups = [])
  call_params = {  'GroupName'   => name.to_s,
                  'IpPermissions.1.IpProtocol' => protocol.to_s,
                   'IpPermissions.1.FromPort'   => from_port.to_s,
                   'IpPermissions.1.ToPort'     => to_port.to_s  }
  source_ip_ranges.each_index do |i|
    call_params.merge!({"IpPermissions.1.IpRanges.#{i+1}.CidrIp" => source_ip_ranges[i].to_s})
  end
  source_groups.each_index do |i|
    call_params.merge!({"IpPermissions.1.Groups.#{i+1}.GroupName" => source_groups[i]['group_name'].to_s,
                        "IpPermissions.1.Groups.#{i+1}.UserId"=> source_groups[i]['owner'].to_s.gsub(/-/,'')})
  end
  unless ['Authorize', 'Revoke'].include?(action.capitalize)
     raise AwsError.new("Invalid action #{action} - must be one of \'Authorize\' or \'Revoke\'")
  end
  link = generate_request("#{action.capitalize}SecurityGroupIngress", call_params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
  rescue Exception
    on_exception
end

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

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

operation_type : currently, only 'Add' & 'Remove' are supported.
vars:
  :user_group  : currently, only 'all' is supported.
  :user_id
  :product_code
  :description


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

def modify_image_attribute(image_id, operation_type = nil, vars = {})
  params = {'ImageId' => image_id }
  params.update(hash_params_with_suffix("LaunchPermission.#{operation_type}", 'UserId', vars[:user_id].to_a)) if vars[:user_id]
  params.update(hash_params_with_suffix("LaunchPermission.#{operation_type}", 'Group', vars[:user_group].to_a)) if vars[:user_group]
  params.update(hash_params('ProductCode', vars[:product_code])) if vars[:product_code]
  params.update('Description.Value' => vars[:description].to_s) if vars[:description]
  link = generate_request("ModifyImageAttribute", params)
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#modify_image_description(image_id, description = '') ⇒ Object

Change image description

ec2.modify_image_description('ami-e444444d','My new AMI') #=> true


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

def modify_image_description(image_id, description='')
  modify_image_attribute(image_id, nil, :description => description)
end

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

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

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


370
371
372
# File 'lib/ec2/ec2.rb', line 370

def modify_image_launch_perm_add_groups(image_id, user_group=['all'])
  modify_image_attribute(image_id, 'Add', :user_group => user_group.to_a)
end

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

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

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


353
354
355
# File 'lib/ec2/ec2.rb', line 353

def modify_image_launch_perm_add_users(image_id, user_id=[])
  modify_image_attribute(image_id, 'Add', :user_id => user_id.to_a)
end

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

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

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


378
379
380
# File 'lib/ec2/ec2.rb', line 378

def modify_image_launch_perm_remove_groups(image_id, user_group=['all'])
  modify_image_attribute(image_id, 'Remove', :user_group => user_group.to_a)
end

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

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

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


361
362
363
# File 'lib/ec2/ec2.rb', line 361

def modify_image_launch_perm_remove_users(image_id, user_id=[])
  modify_image_attribute(image_id, 'Remove', :user_id => user_id.to_a)
end

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

Add product code to image

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


386
387
388
# File 'lib/ec2/ec2.rb', line 386

def modify_image_product_code(image_id, product_code=[])
  modify_image_attribute(image_id, nil, :product_code => product_code.to_a)
end

#monitor_instances(list = []) ⇒ Object



597
598
599
600
601
602
# File 'lib/ec2/ec2.rb', line 597

def monitor_instances(list=[])
  link = generate_request("MonitorInstances", hash_params('InstanceId', list.to_a))
  request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#reboot_instances(list) ⇒ Object

Reboot an EC2 instance. Returns true or an exception.

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


685
686
687
688
689
690
# File 'lib/ec2/ec2.rb', line 685

def reboot_instances(list)
  link = generate_request("RebootInstances", hash_params('InstanceId', list.to_a))
  request_info(link, RightBoolResponseParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#register_image(image_location) ⇒ Object

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

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


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

def register_image(image_location)
  link = generate_request("RegisterImage",
                          'ImageLocation' => image_location.to_s)
  request_info(link, QEc2RegisterImageParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#release_address(public_ip) ⇒ Object

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

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


1125
1126
1127
1128
1129
1130
1131
# File 'lib/ec2/ec2.rb', line 1125

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

#request_info(request, parser, options = {}) ⇒ Object

Sends request to Amazon and parses the response Raises AwsError if any banana happened todo: remove this and switch to using request_info2



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

def request_info(request, parser, options={}) #:nodoc:
  conn = get_conn(self.class.connection_name, @params, @logger)
  request_info_impl(conn, @@bench, request, parser, options)
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


316
317
318
319
320
321
322
323
# File 'lib/ec2/ec2.rb', line 316

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

#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


986
987
988
989
990
991
992
993
994
995
996
# File 'lib/ec2/ec2.rb', line 986

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

#revoke_security_group_named_ingress(name, owner, group) ⇒ Object

Revoke named ingress for security group.

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


955
956
957
958
959
960
961
962
963
# File 'lib/ec2/ec2.rb', line 955

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

#run_instances(image_id, min_count, max_count, group_ids, key_name, user_data = '', addressing_type = nil, instance_type = nil, kernel_id = nil, ramdisk_id = nil, availability_zone = nil, block_device_mappings = nil) ⇒ Object

DEPRECATED, USE launch_instances instead.

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

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


487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/ec2/ec2.rb', line 487

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

#start_instances(list = []) ⇒ Object

Start EBS-backed EC2 instances. Returns a list of instance state changes or an exception.

ec2.start_instances(['i-f222222d', 'i-f222222e']) #=>
  [{:aws_instance_id         => "i-f222222d",
    :aws_current_state_code  => 0,
    :aws_current_state       => "pending",
    :aws_prev_state_code     => 80,
    :aws_prev_state          => "stopped"},
   {:aws_instance_id         => "i-f222222e",
    :aws_current_state_code  => 0,
    :aws_current_state       => "pending",
    :aws_prev_state_code     => 80,
    :aws_prev_state          => "stopped"}]


660
661
662
663
664
665
# File 'lib/ec2/ec2.rb', line 660

def start_instances(list=[])
  link = generate_request("StartInstances", hash_params('InstanceId', list.to_a))
  request_info(link, QEc2StartInstancesParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#stop_instances(list = []) ⇒ Object

Stop EBS-backed EC2 instances. Returns a list of instance state changes or an exception.

ec2.stop_instances(['i-f222222d', 'i-f222222e']) #=>
  [{:aws_instance_id         => "i-f222222d",
    :aws_current_state_code  => 64,
    :aws_current_state       => "stopping",
    :aws_prev_state_code     => 16,
    :aws_prev_state          => "running"},
   {:aws_instance_id         => "i-f222222e",
    :aws_current_state_code  => 64,
    :aws_current_state       => "stopping",
    :aws_prev_state_code     => 16,
    :aws_prev_state          => "running"}]


639
640
641
642
643
644
# File 'lib/ec2/ec2.rb', line 639

def stop_instances(list=[])
  link = generate_request("StopInstances", hash_params('InstanceId', list.to_a))
  request_info(link, QEc2StopInstancesParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#terminate_instances(list = []) ⇒ Object

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

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


618
619
620
621
622
623
# File 'lib/ec2/ec2.rb', line 618

def terminate_instances(list=[])
  link = generate_request("TerminateInstances", hash_params('InstanceId', list.to_a))
  request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
rescue Exception
  on_exception
end

#try_create_snapshot(volume_id, connect_timeout = nil, read_timeout = nil) ⇒ 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') #=>
    {:aws_volume_id  => "vol-fd9f7a94",
     :aws_started_at => Tue Jun 24 18:40:40 UTC 2008,
     :aws_progress   => "",
     :aws_status     => "pending",
     :aws_id         => "snap-d56783bc"}


1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
# File 'lib/ec2/ec2.rb', line 1384

def try_create_snapshot(volume_id, connect_timeout = nil, read_timeout = nil)
  # 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                         = Aws::AWSErrorHandler::reiteration_time
  Aws::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)
  request_info(link, QEc2CreateSnapshotParser.new(:logger => @logger))

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