Class: EC2::AWSAuthConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/EC2.rb,
lib/EC2/images.rb,
lib/EC2/keypairs.rb,
lib/EC2/instances.rb,
lib/EC2/security_groups.rb,
lib/EC2/image_attributes.rb

Overview

The library exposes one main interface class, ‘AWSAuthConnection’. This class performs all the operations for using the EC2 service including header signing. This class uses Net::HTTP to interface with EC2 Query API interface.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(aws_access_key_id, aws_secret_access_key, is_secure = true, server = DEFAULT_HOST, port = PORTS_BY_SECURITY[is_secure]) ⇒ AWSAuthConnection

Returns a new instance of AWSAuthConnection.



87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/EC2.rb', line 87

def initialize(aws_access_key_id, aws_secret_access_key, is_secure=true,
               server=DEFAULT_HOST, port=PORTS_BY_SECURITY[is_secure])
  
  @aws_access_key_id = aws_access_key_id
  @aws_secret_access_key = aws_secret_access_key
  @http = Net::HTTP.new(server, port)
  @http.use_ssl = is_secure
  # Don't verify the SSL certificates.  Avoids SSL Cert warning on every GET.
  @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  
  @verbose = false
  
end

Instance Attribute Details

#verboseObject

Allow viewing, or turning on and off, the verbose mode of the connection class. If ‘true’ some ‘puts’ are done to view variable contents.



85
86
87
# File 'lib/EC2.rb', line 85

def verbose
  @verbose
end

Instance Method Details

#authorize_security_group_ingress(*args) ⇒ Object Also known as: authorize

The AuthorizeSecurityGroupIngress operation adds permissions to a security group.

Permissions are specified in terms of the IP protocol (TCP, UDP or ICMP), the source of the request (by IP range or an Amazon EC2 user-group pair), source and destination port ranges (for TCP and UDP), and ICMP codes and types (for ICMP). When authorizing ICMP, -1 may be used as a wildcard in the type and code fields.

Permission changes are propagated to instances within the security group being modified as quickly as possible. However, a small delay is likely, depending on the number of instances that are members of the indicated group.

When authorizing a user/group pair permission, GroupName, SourceSecurityGroupName and SourceSecurityGroupOwnerId must be specified. When authorizing a CIDR IP permission, GroupName, IpProtocol, FromPort, ToPort and CidrIp must be specified. Mixing these two types of parameters is not allowed.



83
84
85
86
# File 'lib/EC2/security_groups.rb', line 83

def authorize_security_group_ingress(*args)
  params = auth_revoke_impl(*args)
  AuthorizeSecurityGroupIngressResponse.new(make_request("AuthorizeSecurityGroupIngress", params))
end

#create_keypair(keyName) ⇒ Object

The CreateKeyPair operation creates a new 2048 bit RSA keypair and returns a unique ID that can be used to reference this keypair when launching new instances.



16
17
18
19
# File 'lib/EC2/keypairs.rb', line 16

def create_keypair(keyName)
  params = { "KeyName" => keyName }
  CreateKeyPairResponse.new(make_request("CreateKeyPair", params))
end

#create_security_group(groupName, groupDescription) ⇒ Object Also known as: create_securitygroup

The CreateSecurityGroup operation creates a new security group.

Every instance is launched in a security group. If none is specified as part of the launch request then instances are launched in the default security group. Instances within the same security group have unrestricted network access to one another. Instances will reject network access attempts from other instances in a different security group. As the owner of instances you may grant or revoke specific permissions using the AuthorizeSecurityGroupIngress and RevokeSecurityGroupIngress operations.



23
24
25
26
27
28
29
# File 'lib/EC2/security_groups.rb', line 23

def create_security_group(groupName, groupDescription)
  params = {
    "GroupName" => groupName,
    "GroupDescription" => groupDescription
  }
  CreateSecurityGroupResponse.new(make_request("CreateSecurityGroup", params))
end

#delete_keypair(keyName) ⇒ Object

The DeleteKeyPair operation deletes a keypair.



31
32
33
34
# File 'lib/EC2/keypairs.rb', line 31

def delete_keypair(keyName)
  params = { "KeyName" => keyName }
  DeleteKeyPairResponse.new(make_request("DeleteKeyPair", params))
end

#delete_security_group(groupName) ⇒ Object Also known as: delete_securitygroup

The DeleteSecurityGroup operation deletes a security group.

If an attempt is made to delete a security group and any instances exist that are members of that group a fault is returned.



56
57
58
59
# File 'lib/EC2/security_groups.rb', line 56

def delete_security_group(groupName)
  params = { "GroupName" => groupName }
  DeleteSecurityGroupResponse.new(make_request("DeleteSecurityGroup", params))
end

#deregister_image(imageId) ⇒ Object

The DeregisterImage operation deregisters an AMI. Once deregistered, instances of the AMI may no longer be launched.



80
81
82
83
# File 'lib/EC2/images.rb', line 80

def deregister_image(imageId)
  params = { "ImageId" => imageId }
  DeregisterImageResponse.new(make_request("DeregisterImage", params))
end

#describe_image_attribute(imageId, attribute) ⇒ Object

The DescribeImageAttribute operation returns information about an attribute of an AMI.



34
35
36
37
# File 'lib/EC2/image_attributes.rb', line 34

def describe_image_attribute(imageId, attribute)
  params = { "ImageId" => imageId, "Attribute" => attribute }
  DescribeImageAttributeResponse.new(make_request("DescribeImageAttribute", params))
end

#describe_images(imageIds = [], owners = [], executableBy = []) ⇒ Object

The DescribeImages operation returns information about AMIs available for use by the user. This includes both public AMIs (those available for any user to launch) and private AMIs (those owned by the user making the request and those owned by other users that the user making the request has explicit launch permissions for).

The list of AMIs returned can be modified via optional lists of AMI IDs, owners or users with launch permissions. If all three optional lists are empty all AMIs the user has launch permissions for are returned. Launch permissions fall into three categories:

Launch Permission Description

* public	The all group has launch permissions for the AMI. All users have 
  launch permissions for these AMIs.
* explicit	The owner of the AMIs has granted a specific user launch permissions for the AMI.
* implicit	A user has implicit launch permissions for all AMIs he or she owns.

If one or more of the lists are specified the result set is the intersection of AMIs matching the criteria of the individual lists.

Providing the list of AMI IDs requests information for those AMIs only. If no AMI IDs are provided, information of all relevant AMIs will be returned. If an AMI is specified that does not exist a fault is returned. If an AMI is specified that exists but the user making the request does not have launch permissions for, then that AMI will not be included in the returned results.

Providing the list of owners requests information for AMIs owned by the specified owners only. Only AMIs the user has launch permissions for are returned. The items of the list may be account ids for AMIs owned by users with those account ids, amazon for AMIs owned by Amazon or self for AMIs owned by the user making the request.

The executable list may be provided to request information for AMIs that only the specified users have launch permissions for. The items of the list may be account ids for AMIs owned by the user making the request that the users with the specified account ids have explicit launch permissions for, self for AMIs the user making the request has explicit launch permissions for or all for public AMIs.

Deregistered images will be included in the returned results for an unspecified interval subsequent to deregistration.



71
72
73
74
75
76
# File 'lib/EC2/images.rb', line 71

def describe_images(imageIds=[], owners=[], executableBy=[])
  params = pathlist("ImageId", imageIds)
  params.merge!(pathlist("Owner", owners))
  params.merge!(pathlist("ExecutableBy", executableBy))
  DescribeImagesResponse.new(make_request("DescribeImages", params))
end

#describe_instances(instanceIds = []) ⇒ Object

The DescribeInstances operation returns information about instances owned by the user making the request.

An optional list of instance IDs may be provided to request information for those instances only. If no instance IDs are provided, information of all relevant instances information will be returned. If an instance is specified that does not exist a fault is returned. If an instance is specified that exists but is not owned by the user making the request, then that instance will not be included in the returned results.

Recently terminated instances will be included in the returned results for a small interval subsequent to their termination. This interval is typically of the order of one hour.



93
94
95
96
# File 'lib/EC2/instances.rb', line 93

def describe_instances(instanceIds=[])
  params = pathlist("InstanceId", instanceIds)
  DescribeInstancesResponse.new(make_request("DescribeInstances", params))
end

#describe_keypairs(keyNames = []) ⇒ Object

The DescribeKeyPairs operation returns information about keypairs available for use by the user making the request. Selected keypairs may be specified or the list may be left empty if information for all registered keypairs is required.



25
26
27
28
# File 'lib/EC2/keypairs.rb', line 25

def describe_keypairs(keyNames=[])
  params = pathlist("KeyName", keyNames)
  DescribeKeyPairsResponse.new(make_request("DescribeKeyPairs", params))
end

#describe_security_groups(groupNames = []) ⇒ Object Also known as: describe_securitygroups

The DescribeSecurityGroups operation returns information about security groups owned by the user making the request.

An optional list of security group names may be provided to request information for those security groups only. If no security group names are provided, information of all security groups will be returned. If a group is specified that does not exist a fault is returned.



42
43
44
45
# File 'lib/EC2/security_groups.rb', line 42

def describe_security_groups(groupNames=[])
  params = pathlist("GroupName", groupNames)
  DescribeSecurityGroupsResponse.new(make_request("DescribeSecurityGroups", params))
end

#modify_image_attribute(imageId, attribute, operationType, attributeValueHash) ⇒ Object

The ModifyImageAttribute operation modifies an attribute of an AMI.

Currently the only attribute supported is launchPermission. By modifying this attribute it is possible to make an AMI public or to grant specific users launch permissions for the AMI. To make the AMI public add the group=all attribute item. To grant launch permissions for a specific user add a userId=<userid> attribute item.



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/EC2/image_attributes.rb', line 20

def modify_image_attribute(imageId, attribute, operationType, attributeValueHash)
  params = {
    "ImageId" => imageId,
    "Attribute" => attribute,
    "OperationType" => operationType
  }
  if attribute == "launchPermission"
    params.merge!(pathlist("UserGroup", attributeValueHash[:userGroups])) if attributeValueHash.has_key? :userGroups
    params.merge!(pathlist("UserId", attributeValueHash[:userIds])) if attributeValueHash.has_key? :userIds
  end
  ModifyImageAttributeResponse.new(make_request("ModifyImageAttribute", params))
end

#register_image(imageLocation) ⇒ Object

The RegisterImage operation registers an AMI with Amazon EC2. Images must be registered before they can be launched. Each AMI is associated with an unique ID which is provided by the EC2 service via the Registerimage operation. As part of the registration process, Amazon EC2 will retrieve the specified image manifest from Amazon S3 and verify that the image is owned by the user requesting image registration. The image manifest is retrieved once and stored within the Amazon EC2 network. Any modifications to an image in Amazon S3 invalidate this registration. If you do have to make changes and upload a new image deregister the previous image and register the new image.



24
25
26
27
# File 'lib/EC2/images.rb', line 24

def register_image(imageLocation)
  params = { "ImageLocation" => imageLocation }
  RegisterImageResponse.new(make_request("RegisterImage", params))
end

#reset_image_attribute(imageId, attribute) ⇒ Object

The ResetImageAttribute operation resets an attribute of an AMI to its default value.



40
41
42
43
# File 'lib/EC2/image_attributes.rb', line 40

def reset_image_attribute(imageId, attribute)
  params = { "ImageId" => imageId, "Attribute" => attribute }
  ResetImageAttributeResponse.new(make_request("ResetImageAttribute", params))
end

#revoke_security_group_ingress(*args) ⇒ Object Also known as: revoke

The RevokeSecurityGroupIngress operation revokes existing permissions that were previously granted to a security group. The permissions to revoke must be specified using the same values originally used to grant the permission.

Permissions are specified in terms of the IP protocol (TCP, UDP or ICMP), the source of the request (by IP range or an Amazon EC2 user-group pair), source and destination port ranges (for TCP and UDP), and ICMP codes and types (for ICMP). When authorizing ICMP, -1 may be used as a wildcard in the type and code fields.

Permission changes are propagated to instances within the security group being modified as quickly as possible. However, a small delay is likely, depending on the number of instances that are members of the indicated group.

When revoking a user/group pair permission, GroupName, SourceSecurityGroupName and SourceSecurityGroupOwnerId must be specified. When authorizing a CIDR IP permission, GroupName, IpProtocol, FromPort, ToPort and CidrIp must be specified. Mixing these two types of parameters is not allowed.



111
112
113
114
# File 'lib/EC2/security_groups.rb', line 111

def revoke_security_group_ingress(*args)
  params = auth_revoke_impl(*args)
  RevokeSecurityGroupIngressResponse.new(make_request("RevokeSecurityGroupIngress", params))
end

#run_instances(imageId, kwargs = {}) ⇒ Object

The RunInstances operation launches a specified number of instances.

Note:

The Query version of RunInstances only allows instances of a 
single AMI to be launched in one call. This is different 
from the SOAP API call of the same name but similar to the 
ec2-run-instances command line tool.

A call to RunInstances is guaranteed to start no fewer than the requested minimum. If there is insufficient capacity available then no instances will be started. Amazon EC2 will make a best effort attempt to satisfy the requested maximum values.

Every instance is launched in a security group. This may be specified as part of the launch request. If a security group is not indicated then instances are started in a the default security group.

An optional keypair ID may be provided for each image in the launch request. All instances that are created from images for which this is provided will have access to the associated public key at boot time (detailed below). This key may be used to provide secure access to an instance of an image on a per-instance basis. Amazon EC2 public images make use of this functionality to provide secure passwordless access to instances (and launching those images without a keypair ID will leave them inaccessible).

The public key material is made available to the instance at boot time by placing it in a file named openssh_id.pub on a logical device that is exposed to the instance as /dev/sda2 (the ephemeral store). The format of this file is suitable for use as an entry within ~/.ssh/authorized_keys (the OpenSSH format). This can be done at boot time (as part of rclocal, for example) allowing for secure password-less access. As the need arises, other formats will also be considered.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/EC2/instances.rb', line 47

def run_instances(imageId, kwargs={})
  
  # setup the default input parameters hash
  in_params = { :minCount=>1, :maxCount=>1, :keyname=>nil, :groupIds=>[], :userData=>nil, :base64Encoded=>false }
  
  # Override or extend the default input params with any passed in kwargs
  in_params.merge!(kwargs)
  
  # If userData is passed in then URL escape and Base64 encode it
  # as needed.  Need for URL Escape + Base64 encoding is determined 
  # by base64Encoded param.
  if in_params[:userData]
    if in_params[:base64Encoded]
      userData = in_params[:userData]
    else
      userData = CGI::escape(Base64.encode64(in_params[:userData]).strip())
    end
  else
    userData = nil
  end

  params = {
    "ImageId"  => imageId,
    "MinCount" => in_params[:minCount].to_s,
    "MaxCount" => in_params[:maxCount].to_s,
  }.merge(pathlist("SecurityGroup", in_params[:groupIds])) 
  
  params["KeyName"] = in_params[:keyname] unless in_params[:keyname].nil? 
  params["UserData"] = userData unless userData.nil?

  RunInstancesResponse.new(make_request("RunInstances", params))
end

#terminate_instances(instanceIds) ⇒ Object

The TerminateInstances operation shuts down one or more instances. This operation is idempotent and terminating an instance that is in the process of shutting down (or already terminated) will succeed.

Terminated instances remain visible for a short period of time (approximately one hour) after termination, after which their instance ID is invalidated.



105
106
107
108
# File 'lib/EC2/instances.rb', line 105

def terminate_instances(instanceIds)
  params = pathlist("InstanceId", instanceIds)
  TerminateInstancesResponse.new(make_request("TerminateInstances", params))
end