| Class | RightAws::Ec2 |
| In: |
lib/ec2/right_ec2.rb
|
| Parent: | RightAwsBase |
The RightAws::EC2 class provides a complete interface to Amazon‘s Elastic Compute Cloud service, as well as the associated EBS (Elastic Block Store). For explanations of the semantics of each call, please refer to Amazon‘s documentation at developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=87
Examples:
Create an EC2 interface handle:
@ec2 = RightAws::Ec2.new(aws_access_key_id,
aws_secret_access_key)
Create a new SSH key pair:
@key = 'right_ec2_awesome_test_key' new_key = @ec2.create_key_pair(@key) keys = @ec2.describe_key_pairs
Create a security group:
@group = 'right_ec2_awesome_test_security_group' @ec2.create_security_group(@group,'My awesome test group') group = @ec2.describe_security_groups([@group])[0]
Configure a security group:
@ec2.authorize_security_group_named_ingress(@group, account_number, 'default') @ec2.authorize_security_group_IP_ingress(@group, 80,80,'udp','192.168.1.0/8')
Describe the available images:
images = @ec2.describe_images
Launch an instance:
ec2.run_instances('ami-9a9e7bf3', 1, 1, ['default'], @key, 'SomeImportantUserData', 'public')
Describe running instances:
@ec2.describe_instances
Error handling: all operations raise an RightAws::AwsError in case of problems. Note that transient errors are automatically retried.
| API_VERSION | = | "2008-12-01" | Amazon EC2 API version being used | |
| DEFAULT_HOST | = | "ec2.amazonaws.com" | ||
| DEFAULT_PATH | = | '/' | ||
| DEFAULT_PROTOCOL | = | 'https' | ||
| DEFAULT_PORT | = | 443 | ||
| DEFAULT_ADDRESSING_TYPE | = | 'public' | Default addressing type (public=NAT, direct=no-NAT) used when launching instances. | |
| DNS_ADDRESSING_SET | = | ['public','direct'] | ||
| DEFAULT_INSTANCE_TYPE | = | 'm1.small' | Amazon EC2 Instance Types : www.amazon.com/b?ie=UTF8&node=370375011 Default EC2 instance type (platform) | |
| INSTANCE_TYPES | = | ['m1.small','c1.medium','m1.large','m1.xlarge','c1.xlarge'] |
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:
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.
# File lib/ec2/right_ec2.rb, line 116
116: def initialize(aws_access_key_id=nil, aws_secret_access_key=nil, params={})
117: init({ :name => 'EC2',
118: :default_host => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).host : DEFAULT_HOST,
119: :default_port => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).port : DEFAULT_PORT,
120: :default_service => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).path : DEFAULT_PATH,
121: :default_protocol => ENV['EC2_URL'] ? URI.parse(ENV['EC2_URL']).scheme : DEFAULT_PROTOCOL },
122: aws_access_key_id || ENV['AWS_ACCESS_KEY_ID'] ,
123: aws_secret_access_key|| ENV['AWS_SECRET_ACCESS_KEY'],
124: params)
125: # EC2 doesn't really define any transient errors to retry, and in fact,
126: # when they return a 503 it is usually for 'request limit exceeded' which
127: # we most certainly should not retry. So let's pare down the list of
128: # retryable errors to InternalError only (see RightAwsBase for the default
129: # list)
130: amazon_problems = ['InternalError']
131: end
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'
# File lib/ec2/right_ec2.rb, line 914
914: def allocate_address
915: link = generate_request("AllocateAddress")
916: request_info(link, QEc2AllocateAddressParser.new(:logger => @logger))
917: rescue Exception
918: on_exception
919: end
Associate an elastic IP address with an instance. Returns true or an exception.
ec2.associate_address('i-d630cbbf', '75.101.154.140') #=> true
# File lib/ec2/right_ec2.rb, line 926
926: def associate_address(instance_id, public_ip)
927: link = generate_request("AssociateAddress",
928: "InstanceId" => instance_id.to_s,
929: "PublicIp" => public_ip.to_s)
930: request_info(link, RightBoolResponseParser.new(:logger => @logger))
931: rescue Exception
932: on_exception
933: end
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" }
# File lib/ec2/right_ec2.rb, line 1093
1093: def attach_volume(volume_id, instance_id, device)
1094: link = generate_request("AttachVolume",
1095: "VolumeId" => volume_id.to_s,
1096: "InstanceId" => instance_id.to_s,
1097: "Device" => device.to_s)
1098: request_info(link, QEc2AttachAndDetachVolumeParser.new(:logger => @logger))
1099: rescue Exception
1100: on_exception
1101: end
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
# File lib/ec2/right_ec2.rb, line 831
831: def authorize_security_group_IP_ingress(name, from_port, to_port, protocol='tcp', cidr_ip='0.0.0.0/0')
832: link = generate_request("AuthorizeSecurityGroupIngress",
833: 'GroupName' => name.to_s,
834: 'IpProtocol' => protocol.to_s,
835: 'FromPort' => from_port.to_s,
836: 'ToPort' => to_port.to_s,
837: 'CidrIp' => cidr_ip.to_s)
838: request_info(link, RightBoolResponseParser.new(:logger => @logger))
839: rescue Exception
840: on_exception
841: end
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
# File lib/ec2/right_ec2.rb, line 802
802: def authorize_security_group_named_ingress(name, owner, group)
803: link = generate_request("AuthorizeSecurityGroupIngress",
804: 'GroupName' => name.to_s,
805: 'SourceSecurityGroupName' => group.to_s,
806: 'SourceSecurityGroupOwnerId' => owner.to_s.gsub(/-/,''))
807: request_info(link, RightBoolResponseParser.new(:logger => @logger))
808: rescue Exception
809: on_exception
810: end
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"}]
# File lib/ec2/right_ec2.rb, line 641
641: def bundle_instance(instance_id, s3_bucket, s3_prefix,
642: s3_owner_aws_access_key_id=nil, s3_owner_aws_secret_access_key=nil,
643: s3_expires = S3Interface::DEFAULT_EXPIRES_AFTER,
644: s3_upload_policy='ec2-bundle-read')
645: # S3 access and signatures
646: s3_owner_aws_access_key_id ||= @aws_access_key_id
647: s3_owner_aws_secret_access_key ||= @aws_secret_access_key
648: s3_expires = Time.now.utc + s3_expires if s3_expires.is_a?(Fixnum) && (s3_expires < S3Interface::ONE_YEAR_IN_SECONDS)
649: # policy
650: policy = { 'expiration' => s3_expires.strftime('%Y-%m-%dT%H:%M:%SZ'),
651: 'conditions' => [ { 'bucket' => s3_bucket },
652: { 'acl' => s3_upload_policy },
653: [ 'starts-with', '$key', s3_prefix ] ] }.to_json
654: policy64 = Base64.encode64(policy).gsub("\n","")
655: signed_policy64 = AwsUtils.sign(s3_owner_aws_secret_access_key, policy64)
656: # fill request params
657: params = { 'InstanceId' => instance_id,
658: 'Storage.S3.AWSAccessKeyId' => s3_owner_aws_access_key_id,
659: 'Storage.S3.UploadPolicy' => policy64,
660: 'Storage.S3.UploadPolicySignature' => signed_policy64,
661: 'Storage.S3.Bucket' => s3_bucket,
662: 'Storage.S3.Prefix' => s3_prefix,
663: }
664: link = generate_request("BundleInstance", params)
665: request_info(link, QEc2BundleInstanceParser.new)
666: rescue Exception
667: on_exception
668: end
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"}
# File lib/ec2/right_ec2.rb, line 705
705: def cancel_bundle_task(bundle_id)
706: link = generate_request("CancelBundleTask", { 'BundleId' => bundle_id })
707: request_info(link, QEc2BundleInstanceParser.new)
708: rescue Exception
709: on_exception
710: end
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"
# File lib/ec2/right_ec2.rb, line 428
428: def confirm_product_instance(instance, product_code)
429: link = generate_request("ConfirmProductInstance", { 'ProductCode' => product_code,
430: 'InstanceId' => instance })
431: request_info(link, QEc2ConfirmProductInstanceParser.new(:logger => @logger))
432: end
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-----"}
# File lib/ec2/right_ec2.rb, line 885
885: def create_key_pair(name)
886: link = generate_request("CreateKeyPair",
887: 'KeyName' => name.to_s)
888: request_info(link, QEc2CreateKeyPairParser.new(:logger => @logger))
889: rescue Exception
890: on_exception
891: end
Create new Security Group. Returns true or an exception.
ec2.create_security_group('default-1',"Default allowing SSH, HTTP, and HTTPS ingress") #=> true
# File lib/ec2/right_ec2.rb, line 774
774: def create_security_group(name, description)
775: # EC2 doesn't like an empty description...
776: description = " " if description.blank?
777: link = generate_request("CreateSecurityGroup",
778: 'GroupName' => name.to_s,
779: 'GroupDescription' => description.to_s)
780: request_info(link, RightBoolResponseParser.new(:logger => @logger))
781: rescue Exception
782: on_exception
783: end
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"}
# File lib/ec2/right_ec2.rb, line 1160
1160: def create_snapshot(volume_id)
1161: link = generate_request("CreateSnapshot",
1162: "VolumeId" => volume_id.to_s)
1163: request_info(link, QEc2CreateSnapshotParser.new(:logger => @logger))
1164: rescue Exception
1165: on_exception
1166: end
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}
# File lib/ec2/right_ec2.rb, line 1060
1060: def create_volume(snapshot_id, size, zone)
1061: link = generate_request("CreateVolume",
1062: "SnapshotId" => snapshot_id.to_s,
1063: "Size" => size.to_s,
1064: "AvailabilityZone" => zone.to_s )
1065: request_info(link, QEc2CreateVolumeParser.new(:logger => @logger))
1066: rescue Exception
1067: on_exception
1068: end
Delete a key pair. Returns true or an exception.
ec2.delete_key_pair('my_awesome_key') #=> true
# File lib/ec2/right_ec2.rb, line 897
897: def delete_key_pair(name)
898: link = generate_request("DeleteKeyPair",
899: 'KeyName' => name.to_s)
900: request_info(link, RightBoolResponseParser.new(:logger => @logger))
901: rescue Exception
902: on_exception
903: end
Remove Security Group. Returns true or an exception.
ec2.delete_security_group('default-1') #=> true
# File lib/ec2/right_ec2.rb, line 789
789: def delete_security_group(name)
790: link = generate_request("DeleteSecurityGroup",
791: 'GroupName' => name.to_s)
792: request_info(link, RightBoolResponseParser.new(:logger => @logger))
793: rescue Exception
794: on_exception
795: end
Delete the specified snapshot.
ec2.delete_snapshot('snap-55a5403c') #=> true
# File lib/ec2/right_ec2.rb, line 1211
1211: def delete_snapshot(snapshot_id)
1212: link = generate_request("DeleteSnapshot",
1213: "SnapshotId" => snapshot_id.to_s)
1214: request_info(link, RightBoolResponseParser.new(:logger => @logger))
1215: rescue Exception
1216: on_exception
1217: end
Delete the specified EBS volume. This does not deletes any snapshots created from this volume.
ec2.delete_volume('vol-b48a6fdd') #=> true
# File lib/ec2/right_ec2.rb, line 1075
1075: def delete_volume(volume_id)
1076: link = generate_request("DeleteVolume",
1077: "VolumeId" => volume_id.to_s)
1078: request_info(link, RightBoolResponseParser.new(:logger => @logger))
1079: rescue Exception
1080: on_exception
1081: end
Deregister image at Amazon. Returns true or an exception.
ec2.deregister_image('ami-e444444d') #=> true
# File lib/ec2/right_ec2.rb, line 269
269: def deregister_image(image_id)
270: link = generate_request("DeregisterImage",
271: 'ImageId' => image_id.to_s)
272: request_info(link, RightBoolResponseParser.new(:logger => @logger))
273: rescue Exception
274: on_exception
275: end
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"}]
# File lib/ec2/right_ec2.rb, line 943
943: def describe_addresses(list=[])
944: link = generate_request("DescribeAddresses",
945: hash_params('PublicIp',list.to_a))
946: request_cache_or_info :describe_addresses, link, QEc2DescribeAddressesParser, @@bench, list.blank?
947: rescue Exception
948: on_exception
949: end
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"}]
# File lib/ec2/right_ec2.rb, line 992
992: def describe_availability_zones(list=[])
993: link = generate_request("DescribeAvailabilityZones",
994: hash_params('ZoneName',list.to_a))
995: request_cache_or_info :describe_availability_zones, link, QEc2DescribeAvailabilityZonesParser, @@bench, list.blank?
996: rescue Exception
997: on_exception
998: end
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"}]
# File lib/ec2/right_ec2.rb, line 685
685: def describe_bundle_tasks(list=[])
686: link = generate_request("DescribeBundleTasks", hash_params('BundleId', list.to_a))
687: request_info(link, QEc2DescribeBundleTasksParser.new)
688: rescue Exception
689: on_exception
690: end
Describe image attributes. Currently ‘launchPermission’, ‘productCodes’, ‘kernel’, ‘ramdisk’ and ‘blockDeviceMapping’ are supported.
ec2.describe_image_attribute('ami-e444444d') #=> {:groups=>["all"], :users=>["000000000777"]}
# File lib/ec2/right_ec2.rb, line 282
282: def describe_image_attribute(image_id, attribute='launchPermission')
283: link = generate_request("DescribeImageAttribute",
284: 'ImageId' => image_id,
285: 'Attribute' => attribute)
286: request_info(link, QEc2DescribeImageAttributeParser.new(:logger => @logger))
287: rescue Exception
288: on_exception
289: end
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"}]
# File lib/ec2/right_ec2.rb, line 220
220: def describe_images(list=[], image_type=nil)
221: list = list.to_a
222: cache_for = list.empty? && !image_type ? :describe_images : nil
223: ec2_describe_images({ 'ImageId' => list }, image_type, cache_for)
224: end
Example:
ec2.describe_images_by_executable_by('522821470517')
ec2.describe_images_by_executable_by('self')
ec2.describe_images_by_executable_by('all')
# File lib/ec2/right_ec2.rb, line 245
245: def describe_images_by_executable_by(list=['self'], image_type=nil)
246: list = list.to_a
247: cache_for = list==['self'] && !image_type ? :describe_images_by_executable_by : nil
248: ec2_describe_images({ 'ExecutableBy' => list }, image_type, cache_for)
249: end
Example:
ec2.describe_images_by_owner('522821470517')
ec2.describe_images_by_owner('self')
# File lib/ec2/right_ec2.rb, line 232
232: def describe_images_by_owner(list=['self'], image_type=nil)
233: list = list.to_a
234: cache_for = list==['self'] && !image_type ? :describe_images_by_owner : nil
235: ec2_describe_images({ 'Owner' => list }, image_type, cache_for)
236: end
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",
..., {...}]
# File lib/ec2/right_ec2.rb, line 414
414: def describe_instances(list=[])
415: link = generate_request("DescribeInstances", hash_params('InstanceId',list.to_a))
416: request_cache_or_info(:describe_instances, link, QEc2DescribeInstancesParser, @@bench, list.blank?) do |parser|
417: get_desc_instances(parser.result)
418: end
419: rescue Exception
420: on_exception
421: end
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"},
..., {...} ]
# File lib/ec2/right_ec2.rb, line 871
871: def describe_key_pairs(list=[])
872: link = generate_request("DescribeKeyPairs", hash_params('KeyName',list.to_a))
873: request_cache_or_info :describe_key_pairs, link, QEc2DescribeKeyPairParser, @@bench, list.blank?
874: rescue Exception
875: on_exception
876: end
Describe regions.
ec2.describe_regions #=> ["eu-west-1", "us-east-1"]
# File lib/ec2/right_ec2.rb, line 1008
1008: def describe_regions(list=[])
1009: link = generate_request("DescribeRegions",
1010: hash_params('RegionName',list.to_a))
1011: request_cache_or_info :describe_regions, link, QEc2DescribeRegionsParser, @@bench, list.blank?
1012: rescue Exception
1013: on_exception
1014: end
Retrieve Security Group information. If list is omitted the returns the whole list of groups.
ec2.describe_security_groups #=>
[{:aws_group_name => "default-1",
:aws_owner => "000000000888",
:aws_description => "Default allowing SSH, HTTP, and HTTPS ingress",
:aws_perms =>
[{:owner => "000000000888", :group => "default"},
{:owner => "000000000888", :group => "default-1"},
{:to_port => "-1", :protocol => "icmp", :from_port => "-1", :cidr_ips => "0.0.0.0/0"},
{:to_port => "22", :protocol => "tcp", :from_port => "22", :cidr_ips => "0.0.0.0/0"},
{:to_port => "80", :protocol => "tcp", :from_port => "80", :cidr_ips => "0.0.0.0/0"},
{:to_port => "443", :protocol => "tcp", :from_port => "443", :cidr_ips => "0.0.0.0/0"}]},
..., {...}]
# File lib/ec2/right_ec2.rb, line 731
731: def describe_security_groups(list=[])
732: link = generate_request("DescribeSecurityGroups", hash_params('GroupName',list.to_a))
733: request_cache_or_info( :describe_security_groups, link, QEc2DescribeSecurityGroupsParser, @@bench, list.blank?) do |parser|
734: result = []
735: parser.result.each do |item|
736: perms = []
737: item.ipPermissions.each do |perm|
738: perm.groups.each do |ngroup|
739: perms << {:group => ngroup.groupName,
740: :owner => ngroup.userId}
741: end
742: perm.ipRanges.each do |cidr_ip|
743: perms << {:from_port => perm.fromPort,
744: :to_port => perm.toPort,
745: :protocol => perm.ipProtocol,
746: :cidr_ips => cidr_ip}
747: end
748: end
749:
750: # delete duplication
751: perms.each_index do |i|
752: (0...i).each do |j|
753: if perms[i] == perms[j] then perms[i] = nil; break; end
754: end
755: end
756: perms.compact!
757:
758: result << {:aws_owner => item.ownerId,
759: :aws_group_name => item.groupName,
760: :aws_description => item.groupDescription,
761: :aws_perms => perms}
762:
763: end
764: result
765: end
766: rescue Exception
767: on_exception
768: end
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" },...]
# File lib/ec2/right_ec2.rb, line 1143
1143: def describe_snapshots(list=[])
1144: link = generate_request("DescribeSnapshots",
1145: hash_params('SnapshotId',list.to_a))
1146: request_cache_or_info :describe_snapshots, link, QEc2DescribeSnapshotsParser, @@bench, list.blank?
1147: rescue Exception
1148: on_exception
1149: end
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,}, ... ]
# File lib/ec2/right_ec2.rb, line 1041
1041: def describe_volumes(list=[])
1042: link = generate_request("DescribeVolumes",
1043: hash_params('VolumeId',list.to_a))
1044: request_cache_or_info :describe_volumes, link, QEc2DescribeVolumesParser, @@bench, list.blank?
1045: rescue Exception
1046: on_exception
1047: end
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"}
# File lib/ec2/right_ec2.rb, line 1112
1112: def detach_volume(volume_id, instance_id=nil, device=nil, force=nil)
1113: hash = { "VolumeId" => volume_id.to_s }
1114: hash["InstanceId"] = instance_id.to_s unless instance_id.blank?
1115: hash["Device"] = device.to_s unless device.blank?
1116: hash["Force"] = 'true' if force
1117: #
1118: link = generate_request("DetachVolume", hash)
1119: request_info(link, QEc2AttachAndDetachVolumeParser.new(:logger => @logger))
1120: rescue Exception
1121: on_exception
1122: end
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
# File lib/ec2/right_ec2.rb, line 956
956: def disassociate_address(public_ip)
957: link = generate_request("DisassociateAddress",
958: "PublicIp" => public_ip.to_s)
959: request_info(link, RightBoolResponseParser.new(:logger => @logger))
960: rescue Exception
961: on_exception
962: end
Retreive EC2 instance OS logs. Returns a hash of data or an exception.
ec2.get_console_output('i-f222222d') =>
{:aws_instance_id => 'i-f222222d',
:aws_timestamp => "2007-05-23T14:36:07.000-07:00",
:timestamp => Wed May 23 21:36:07 UTC 2007, # Time instance
:aws_output => "Linux version 2.6.16-xenU (builder@patchbat.amazonsa) (gcc version 4.0.1 20050727 ..."
# File lib/ec2/right_ec2.rb, line 574
574: def get_console_output(instance_id)
575: link = generate_request("GetConsoleOutput", { 'InstanceId.1' => instance_id })
576: request_info(link, QEc2GetConsoleOutputParser.new(:logger => @logger))
577: rescue Exception
578: on_exception
579: end
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"
# File lib/ec2/right_ec2.rb, line 614
614: def get_initial_password(instance_id, private_key)
615: console_output = get_console_output(instance_id)
616: crypted_password = console_output[:aws_output][%r{<Password>(.+)</Password>}m] && $1
617: unless crypted_password
618: raise AwsError.new("Initial password was not found in console output for #{instance_id}")
619: else
620: OpenSSL::PKey::RSA.new(private_key).private_decrypt(Base64.decode64(crypted_password))
621: end
622: rescue Exception
623: on_exception
624: end
Launch new EC2 instances. Returns a list of launched instances or an exception.
lparams keys (default values in parenthesis):
:min_count fixnum, (1)
:max_count fixnum, (1)
:group_ids array or string ([] == 'default')
:instance_type string (DEFAULT_INSTACE_TYPE)
:addressing_type string (DEFAULT_ADDRESSING_TYPE
:key_name string
:kernel_id string
:ramdisk_id string
:availability_zone string
:block_device_mappings string
:user_data string
ec2.launch_instances('ami-e444444d', :group_ids => 'my_awesome_group',
:user_data => "Woohoo!!!",
:addressing_type => "public",
:key_name => "my_awesome_key",
:availability_zone => "us-east-1c") #=>
[{:aws_image_id => "ami-e444444d",
:aws_reason => "",
:aws_state_code => "0",
:aws_owner => "000000000888",
:aws_instance_id => "i-123f1234",
:aws_reservation_id => "r-aabbccdd",
:aws_state => "pending",
:dns_name => "",
:ssh_key_name => "my_awesome_key",
:aws_groups => ["my_awesome_group"],
:private_dns_name => "",
:aws_instance_type => "m1.small",
:aws_launch_time => "2008-1-1T00:00:00.000Z",
:aws_ramdisk_id => "ari-8605e0ef"
:aws_kernel_id => "aki-9905e0f0",
:ami_launch_index => "0",
:aws_availability_zone => "us-east-1c"
}]
# File lib/ec2/right_ec2.rb, line 514
514: def launch_instances(image_id, lparams={})
515: @logger.info("Launching instance of image #{image_id} for #{@aws_access_key_id}, " +
516: "key: #{lparams[:key_name]}, groups: #{(lparams[:group_ids]).to_a.join(',')}")
517: # careful: keyName and securityGroups may be nil
518: params = hash_params('SecurityGroup', lparams[:group_ids].to_a)
519: params.update( {'ImageId' => image_id,
520: 'MinCount' => (lparams[:min_count] || 1).to_s,
521: 'MaxCount' => (lparams[:max_count] || 1).to_s,
522: 'AddressingType' => lparams[:addressing_type] || DEFAULT_ADDRESSING_TYPE,
523: 'InstanceType' => lparams[:instance_type] || DEFAULT_INSTANCE_TYPE })
524: # optional params
525: params['KeyName'] = lparams[:key_name] unless lparams[:key_name].blank?
526: params['KernelId'] = lparams[:kernel_id] unless lparams[:kernel_id].blank?
527: params['RamdiskId'] = lparams[:ramdisk_id] unless lparams[:ramdisk_id].blank?
528: params['Placement.AvailabilityZone'] = lparams[:availability_zone] unless lparams[:availability_zone].blank?
529: params['BlockDeviceMappings'] = lparams[:block_device_mappings] unless lparams[:block_device_mappings].blank?
530: unless lparams[:user_data].blank?
531: lparams[:user_data].strip!
532: # Do not use CGI::escape(encode64(...)) as it is done in Amazons EC2 library.
533: # Amazon 169.254.169.254 does not like escaped symbols!
534: # And it doesn't like "\n" inside of encoded string! Grrr....
535: # Otherwise, some of UserData symbols will be lost...
536: params['UserData'] = Base64.encode64(lparams[:user_data]).delete("\n").strip unless lparams[:user_data].blank?
537: end
538: link = generate_request("RunInstances", params)
539: #debugger
540: instances = request_info(link, QEc2DescribeInstancesParser.new(:logger => @logger))
541: get_desc_instances(instances)
542: rescue Exception
543: on_exception
544: end
Modify an image‘s attributes. It is recommended that you use modify_image_launch_perm_add_users, modify_image_launch_perm_remove_users, etc. instead of modify_image_attribute because the signature of modify_image_attribute may change with EC2 service changes.
attribute : currently, only 'launchPermission' is supported. operation_type : currently, only 'add' & 'remove' are supported. vars: :user_group : currently, only 'all' is supported. :user_id :product_code
# File lib/ec2/right_ec2.rb, line 315
315: def modify_image_attribute(image_id, attribute, operation_type = nil, vars = {})
316: params = {'ImageId' => image_id,
317: 'Attribute' => attribute}
318: params['OperationType'] = operation_type if operation_type
319: params.update(hash_params('UserId', vars[:user_id].to_a)) if vars[:user_id]
320: params.update(hash_params('UserGroup', vars[:user_group].to_a)) if vars[:user_group]
321: params.update(hash_params('ProductCode', vars[:product_code])) if vars[:product_code]
322: link = generate_request("ModifyImageAttribute", params)
323: request_info(link, RightBoolResponseParser.new(:logger => @logger))
324: rescue Exception
325: on_exception
326: end
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
# File lib/ec2/right_ec2.rb, line 350
350: def modify_image_launch_perm_add_groups(image_id, user_group=['all'])
351: modify_image_attribute(image_id, 'launchPermission', 'add', :user_group => user_group.to_a)
352: end
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
# File lib/ec2/right_ec2.rb, line 333
333: def modify_image_launch_perm_add_users(image_id, user_id=[])
334: modify_image_attribute(image_id, 'launchPermission', 'add', :user_id => user_id.to_a)
335: end
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
# File lib/ec2/right_ec2.rb, line 358
358: def modify_image_launch_perm_remove_groups(image_id, user_group=['all'])
359: modify_image_attribute(image_id, 'launchPermission', 'remove', :user_group => user_group.to_a)
360: end
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
# File lib/ec2/right_ec2.rb, line 341
341: def modify_image_launch_perm_remove_users(image_id, user_id=[])
342: modify_image_attribute(image_id, 'launchPermission', 'remove', :user_id => user_id.to_a)
343: end
Add product code to image
ec2.modify_image_product_code('ami-e444444d','0ABCDEF') #=> true
# File lib/ec2/right_ec2.rb, line 366
366: def modify_image_product_code(image_id, product_code=[])
367: modify_image_attribute(image_id, 'productCodes', nil, :product_code => product_code.to_a)
368: end
Reboot an EC2 instance. Returns true or an exception.
ec2.reboot_instances(['i-f222222d','i-f222222e']) #=> true
# File lib/ec2/right_ec2.rb, line 585
585: def reboot_instances(list)
586: link = generate_request("RebootInstances", hash_params('InstanceId', list.to_a))
587: request_info(link, RightBoolResponseParser.new(:logger => @logger))
588: rescue Exception
589: on_exception
590: end
Register new image at Amazon. Returns new image id or an exception.
ec2.register_image('bucket/key/manifest') #=> 'ami-e444444d'
# File lib/ec2/right_ec2.rb, line 257
257: def register_image(image_location)
258: link = generate_request("RegisterImage",
259: 'ImageLocation' => image_location.to_s)
260: request_info(link, QEc2RegisterImageParser.new(:logger => @logger))
261: rescue Exception
262: on_exception
263: end
Release an elastic IP address associated with your account. Returns true or an exception.
ec2.release_address('75.101.154.140') #=> true
# File lib/ec2/right_ec2.rb, line 969
969: def release_address(public_ip)
970: link = generate_request("ReleaseAddress",
971: "PublicIp" => public_ip.to_s)
972: request_info(link, RightBoolResponseParser.new(:logger => @logger))
973: rescue Exception
974: on_exception
975: end
Reset image attribute. Currently, only ‘launchPermission’ is supported. Returns true or an exception.
ec2.reset_image_attribute('ami-e444444d') #=> true
# File lib/ec2/right_ec2.rb, line 295
295: def reset_image_attribute(image_id, attribute='launchPermission')
296: link = generate_request("ResetImageAttribute",
297: 'ImageId' => image_id,
298: 'Attribute' => attribute)
299: request_info(link, RightBoolResponseParser.new(:logger => @logger))
300: rescue Exception
301: on_exception
302: end
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
# File lib/ec2/right_ec2.rb, line 847
847: def revoke_security_group_IP_ingress(name, from_port, to_port, protocol='tcp', cidr_ip='0.0.0.0/0')
848: link = generate_request("RevokeSecurityGroupIngress",
849: 'GroupName' => name.to_s,
850: 'IpProtocol' => protocol.to_s,
851: 'FromPort' => from_port.to_s,
852: 'ToPort' => to_port.to_s,
853: 'CidrIp' => cidr_ip.to_s)
854: request_info(link, RightBoolResponseParser.new(:logger => @logger))
855: rescue Exception
856: on_exception
857: end
Revoke named ingress for security group.
ec2.revoke_security_group_named_ingress('my_awesome_group', aws_user_id, 'another_group_name') #=> true
# File lib/ec2/right_ec2.rb, line 816
816: def revoke_security_group_named_ingress(name, owner, group)
817: link = generate_request("RevokeSecurityGroupIngress",
818: 'GroupName' => name.to_s,
819: 'SourceSecurityGroupName' => group.to_s,
820: 'SourceSecurityGroupOwnerId' => owner.to_s.gsub(/-/,''))
821: request_info(link, RightBoolResponseParser.new(:logger => @logger))
822: rescue Exception
823: on_exception
824: end
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"
}]
# File lib/ec2/right_ec2.rb, line 456
456: def run_instances(image_id, min_count, max_count, group_ids, key_name, user_data='',
457: addressing_type = nil, instance_type = nil,
458: kernel_id = nil, ramdisk_id = nil, availability_zone = nil,
459: block_device_mappings = nil)
460: launch_instances(image_id, { :min_count => min_count,
461: :max_count => max_count,
462: :user_data => user_data,
463: :group_ids => group_ids,
464: :key_name => key_name,
465: :instance_type => instance_type,
466: :addressing_type => addressing_type,
467: :kernel_id => kernel_id,
468: :ramdisk_id => ramdisk_id,
469: :availability_zone => availability_zone,
470: :block_device_mappings => block_device_mappings
471: })
472: end
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}]
# File lib/ec2/right_ec2.rb, line 560
560: def terminate_instances(list=[])
561: link = generate_request("TerminateInstances", hash_params('InstanceId',list.to_a))
562: request_info(link, QEc2TerminateInstancesParser.new(:logger => @logger))
563: rescue Exception
564: on_exception
565: end
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"}
# File lib/ec2/right_ec2.rb, line 1180
1180: def try_create_snapshot(volume_id, connect_timeout = nil, read_timeout = nil)
1181: # For safety in the ensure block...we don't want to restore values
1182: # if we never read them in the first place
1183: orig_reiteration_time = nil
1184: orig_http_params = nil
1185:
1186: orig_reiteration_time = RightAws::AWSErrorHandler::reiteration_time
1187: RightAws::AWSErrorHandler::reiteration_time = 0
1188:
1189: orig_http_params = Rightscale::HttpConnection::params()
1190: new_http_params = orig_http_params.dup
1191: new_http_params[:http_connection_retry_count] = 0
1192: new_http_params[:http_connection_open_timeout] = connect_timeout if !connect_timeout.nil?
1193: new_http_params[:http_connection_read_timeout] = read_timeout if !read_timeout.nil?
1194: Rightscale::HttpConnection::params = new_http_params
1195:
1196: link = generate_request("CreateSnapshot",
1197: "VolumeId" => volume_id.to_s)
1198: request_info(link, QEc2CreateSnapshotParser.new(:logger => @logger))
1199:
1200: rescue Exception
1201: on_exception
1202: ensure
1203: RightAws::AWSErrorHandler::reiteration_time = orig_reiteration_time if orig_reiteration_time
1204: Rightscale::HttpConnection::params = orig_http_params if orig_http_params
1205: end