This is an interface to the 2014-05-01 version of the Amazon AWS API
(http://aws.amazon.com/ec2). It was written provide access to the new tag and
metadata interface that is not currently supported by Net::Amazon::EC2, as
well as to provide developers with an extension mechanism for the API. This
library will also support the Open Stack open source cloud
(http://www.openstack.org/).

The main interface is the VM::EC2 object, which provides methods for
interrogating the Amazon EC2, launching instances, and managing instance
lifecycle. These methods return the following major object classes which act
as specialized interfaces to AWS:

In addition, there is a high level interface for interacting with EC2 servers
and volumes, including file transfer and remote shell facilities:

VM::EC2::Staging::Manager -- Manage a set of servers and volumes.
VM::EC2::Staging::Server -- A staging server, with remote shell and file transfer
facilities.
VM::EC2::Staging::Volume -- A staging volume with the ability to copy itself between
availability zones and regions.

There is also a high-level API called "VM::EC2::Staging::Manager" for
managing groups of staging servers and volumes which greatly simplifies the
task of creating and updating instances that mount multiple volumes. The API
also provides a one-line command for migrating EBS-backed AMIs from one zone
to another. See VM::EC2::Staging::Manager.

The interface provided by these modules is based on that described at
http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/. The following
caveats apply:

1) Not all of the Amazon API is currently implemented. Specifically,
a handful calls dealing with cluster management and VM importing
are missing. See L</MISSING METHODS> for a list of all the
unimplemented API calls. Volunteers to fill in these gaps are
most welcome!
2) For consistency with common Perl coding practices, method calls
are lowercase and words in long method names are separated by
underscores. The Amazon API prefers mixed case. So in the Amazon
API the call to fetch instance information is "DescribeInstances",
while in VM::EC2, the method is "describe_instances". To avoid
annoyance, if you use the mixed case form for a method name, the
Perl autoloader will automatically translate it to underscores for
you, and vice-versa; this means you can call either
$ec2->describe_instances() or $ec2->DescribeInstances().
3) Named arguments passed to methods are all lowercase, use
underscores to separate words and start with hyphens.
In other words, if the AWS API calls for an argument named
"InstanceId" to be passed to the "DescribeInstances" call, then
the corresponding Perl function will look like:
$instance = $ec2->describe_instances(-instance_id=>'i-12345')
In most cases automatic case translation will be performed for you
on arguments. So in the previous example, you could use
-InstanceId as well as -instance_id. The exception
is when an absurdly long argument name was replaced with an
abbreviated one as described below. In this case, you must use
the documented argument name.
In a small number of cases, when the parameter name was absurdly
long, it has been abbreviated. For example, the
"Placement.AvailabilityZone" parameter has been represented as
-placement_zone and not -placement_availability_zone. See the
documentation for these cases.
4) For each of the describe_foo() methods (where "foo" is a type of
resource such as "instance"), you can fetch the resource by using
their IDs either with the long form:
$ec2->describe_foo(-foo_id=>['a','b','c']),
or a shortcut form:
$ec2->describe_foo('a','b','c');
Both forms are listed in the headings in the documentation.
5) When the API calls for a list of arguments named Arg.1, Arg.2,
then the Perl interface allows you to use an anonymous array for
the consecutive values. For example to call describe_instances()
with multiple instance IDs, use:
@i = $ec2->describe_instances(-instance_id=>['i-12345','i-87654'])
6) All Filter arguments are represented as a -filter argument whose value is
an anonymous hash:
@i = $ec2->describe_instances(-filter=>{architecture=>'i386',
'tag:Name' =>'WebServer'})
If there are no other arguments you wish to pass, you can omit the
-filter argument and just pass a hashref:
@i = $ec2->describe_instances({architecture=>'i386',
'tag:Name' =>'WebServer'})
For any filter, you may represent multiple OR arguments as an arrayref:
@i = $ec2->describe-instances({'instance-state-name'=>['stopped','terminated']})
When adding or removing tags, the -tag argument uses the same syntax.
7) The tagnames of each XML object returned from AWS are converted into methods
with the same name and typography. So the <privateIpAddress> tag in a
DescribeInstancesResponse, becomes:
$instance->privateIpAddress
You can also use the more Perlish form -- this is equivalent:
$instance->private_ip_address
Methods that correspond to complex objects in the XML hierarchy
return the appropriate Perl object. For example, an instance's
blockDeviceMapping() method returns an object of type
VM::EC2::BlockDevice::Mapping.
All objects have a fields() method that will return the XML
tagnames listed in the AWS specifications.
@fields = sort $instance->fields;
# 'amiLaunchIndex', 'architecture', 'blockDeviceMapping', ...
8) Whenever an object has a unique ID, string overloading is used so that
the object interpolates the ID into the string. For example, when you
print a VM::EC2::Volume object, or use it in another string context,
then it will appear as the string "vol-123456". Nevertheless, it will
continue to be usable for method calls.
($v) = $ec2->describe_volumes();
print $v,"\n"; # prints as "vol-123456"
$zone = $v->availabilityZone; # acts like an object
9) Many objects have convenience methods that invoke the AWS API on your
behalf. For example, instance objects have a current_status() method that returns
the run status of the object, as well as start(), stop() and terminate()
methods that control the instance's lifecycle.
if ($instance->current_status eq 'running') {
$instance->stop;
}
10) Calls to AWS that have failed for one reason or another (invalid
arguments, communications problems, service interruptions) will
return undef and set the VM::EC2->is_error() method to true. The
error message and its code can then be recovered by calling
VM::EC2->error.
$i = $ec2->describe_instance('i-123456');
unless ($i) {
warn 'Got no instance. Message was: ',$ec2->error;
}
You may also elect to raise an exception when an error occurs.
See the new() method for details.

As of version 1.24, VM::EC2 supports asynchronous calls to AWS using
AnyEvent::HTTP. This allows you to make multiple calls in parallel for a
significant improvement in performance.

In asynchronous mode, VM::EC2 calls that ordinarily wait for AWS to respond and
then return objects corresponding to EC2 instances, volumes, images, and so
forth, will instead immediately return an AnyEvent condition variable. You can
retrieve the result of the call by calling the condition variable's
recv() method, or by setting a callback to be executed when the call is
complete.

To make an asynchronous call, you can set the global variable $VM::EC2::ASYNC to
a true value

Here is an example of a normal synchronous call:

my @instances = $ec2->describe_instances();

Here is the asynchronous version initiated after setting $VM::EC2::ASYNC (using
a local block to limit its effects).

In case of an error recv() will return undef and the error object can be
recovered using the condition variable's error() method (this is an
enhancement over AnyEvent's standard condition variable class):

You may attach a callback CODE reference to the condition variable using its
cb() method, in which case the callback will be invoked when the APi
call is complete. The callback will be invoked with a single argument
consisting of the condition variable. Ordinarily you will call recv()
on the variable and then do something with the result:

For callbacks to be invoked, someone must be run an event loop using one of the
event frameworks that AnyEvent supports (e.g. Coro, Tk or Gtk). Alternately,
you may simply run:

AnyEvent->condvar->recv();

If $VM::EC2::ASYNC is false, you can issue a single asynchronous call by
appending "_async" to the name of the method call. Similarly, if
$VM::EC2::ASYNC is true, you can make a single normal synchrous call by
appending "_sync" to the method name.

You may stack multiple asynchronous calls on top of one another. When you call
recv() on any of the returned condition variables, they will all run in
parallel. Hence the three calls will take no longer than the longest
individual one:

If this looks mysterious, please consult AnyEvent for full documentation and
examples.

Lastly, be advised that some of the objects returned by calls to VM::EC2, such
as the VM::EC2::Instance object, will make their own calls into VM::EC2 for
certain methods. Some of these methods will block (be synchronous) of
necessity, even if you have set $VM::EC2::ASYNC. For example, the instance
object's current_status() method must block in order to update the
object and return the current status. Other object methods may behave
unpredictably in async mode. Caveat emptor!

The extensive (and growing) Amazon API has many calls that you may never need.
To avoid the performance overhead of loading the interfaces to all these
calls, you may use Perl's import mechanism to load only those modules you care
about. By default, all methods are loaded.

Loading is controlled by the "use" import list, and follows the
conventions described in the Exporter module:

Related API calls are grouped together using the scheme described at
http://docs.aws.amazon.com/AWSEC2/latest/APIReference/OperationList-query.html.
The modules that define the API calls can be found in VM/EC2/REST/; you can
read their documentation by running perldoc VM::EC2::REST::"name of
module":

The script sync_to_snapshot.pl, distributed with this module, illustrates a
relatively complex set of steps on EC2 that does something useful. Given a
list of directories or files on the local filesystem it copies the files into
an EBS snapshot with the desired name by executing the following steps:

1. Provisions a new EBS volume on EC2 large enough to hold the data.

2. Spins up a staging instance to manage the network transfer of data from the
local machine to the staging volume.

3. Creates a temporary ssh keypair and a security group that allows an
rsync-over-ssh.

4. Formats and mounts the volume if necessary.

5. Initiates an rsync-over-ssh for the designated files and directories.

6. Unmounts and snapshots the volume.

7. Cleans up.

If a snapshot of the same name already exists, then it is used to create the
staging volume, enabling network-efficient synchronization of the files. A
snapshot tag named "Version" is incremented each time you
synchronize.

-access_key Access ID for an authorized user
-secret_key Secret key corresponding to the Access ID
-security_token Temporary security token obtained through a call to the
AWS Security Token Service
-endpoint The URL for making API requests
-region The region to receive the API requests
-raise_error If true, throw an exception.
-print_error If true, print errors to STDERR.

One or more of -access_key or -secret_key can be omitted if the environment
variables EC2_ACCESS_KEY and EC2_SECRET_KEY are defined. If no endpoint is
specified, then the environment variable EC2_URL is consulted; otherwise the
generic endpoint http://ec2.amazonaws.com/ is used. You can also select the
endpoint by specifying one of the Amazon regions, such as
"us-west-2", with the -region argument. The endpoint specified by
-region will override -endpoint.

-security_token is used in conjunction with temporary security tokens returned
by $ec2-> get_federation_token() and
$ec2->get_session_token() to grant restricted, time-limited access
to some or all your EC2 resources to users who do not have access to your
account. If you pass either a VM::EC2::Security::Token object, or the
VM::EC2::Security::Credentials object contained within the token object, then
new() does not need the -access_key or -secret_key arguments. You may
also pass a session token string scalar to -security_token, in which case you
must also pass the access key ID and secret keys generated at the same time
the session token was created. See
http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/UsingIAM.html and
"AWS SECURITY TOKENS".

To use an Open Stack cloud, please provide the appropriate endpoint URL.

By default, when the Amazon API reports an error, such as attempting to perform
an invalid operation on an instance, the corresponding method will return
empty and the error message can be recovered from $ec2-> error().
However, if you pass -raise_error=>1 to new(), the module will
instead raise a fatal error, which you can trap with eval{} and report with
$@:

Change the handling of error conditions. Pass a true value to cause Amazon API
errors to raise a fatal error. Pass false to make methods return undef. In
either case, you can detect the error condition by calling is_error()
and fetch the error message using error(). This method will also return
the current state of the raise error flag.

If a method fails, it will return undef. However, some methods, such as
describe_images(), will also return undef if no resources matches your
search criteria. Call is_error() to distinguish the two eventualities:

If the most recently-executed method failed, $ec2-> error() will
return the error code and other descriptive information. This method will
return undef if the most recently executed method was successful.

The returned object is actually an AWS::Error object, which has two methods
named code() and message(). If used in a string context, its
operator overloading returns the composite string "$message
[$code]".

Looks up the account ID corresponding to the credentials provided when the
VM::EC2 instance was created. The way this is done is to fetch the
"default" security group, which is guaranteed to exist, and then
return its groupId field. The result is cached so that subsequent accesses are
fast.

Load the 'instances' module to bring in methods for interrogating, launching and
manipulating EC2 instances. This module is part of the ':standard' API group.
The methods are described in detail in VM::EC2::REST::instance. Briefly:

Load the 'ebs' module to bring in methods specific for elastic block storage
volumes and snapshots. This module is part of the ':standard' API group. The
methods are described in detail in VM::EC2::REST::ebs. Briefly:

The methods in this module (loaded with ':standard') allow you to create, delete
and fetch resource tags. You may find that you rarely need to use these
methods directly because every object produced by VM::EC2 supports a simple
tag interface:

See VM::EC2::Generic for a full description of the uniform object tagging
interface, and VM::EC2::REST::tag for methods that allow you to manipulate the
tags on multiple objects simultaneously. The methods defined by this module
are:

EC2 virtual private clouds (VPCs) provide facilities for creating tiered
applications combining public and private subnetworks, and for extending your
home/corporate network into the cloud. VPC-related methods are defined in the
customer_gateway, dhcp, elastic_network_interface, private_ip,
internet_gateway, network_acl, route_table, vpc, vpn, and vpn_gateway modules,
and are loaded by importing ':vpc'. See VM::EC2::REST::vpc for an
introduction.

The VM::EC2::VPC and VM::EC2::VPC::Subnet modules define convenience methods
that simplify working with VPC objects. This allows for steps that typically
follow each other, such as creating a route table and associating it with a
subnet, happen automatically. For example, this series of calls creates a VPC
with a single subnet, creates an Internet gateway attached to the VPC,
associates a new route table with the subnet and then creates a default route
from the subnet to the Internet gateway:

The methods in the 'elastic_load_balancer' and 'autoscaling' modules allow you
to retrieve information about Elastic Load Balancers, create new ELBs, and
change the properties of the ELBs, as well as define autoscaling groups and
their launch configurations. These modules are both imported by the ':scaling'
import group. See VM::EC2::REST::elastic_load_balancer and
VM::EC2::REST::autoscaling for descriptions of the facilities enabled by this
module.

The VM::EC2::Security::Policy module provides a simple Identity and Access
Management (IAM) policy statement generator geared for use with AWS security
tokens (see next section). Its facilities are defined in
VM::EC2::Security::Token.

AWS security tokens provide a way to grant temporary access to resources in your
EC2 space without giving them permanent accounts. They also provide the
foundation for mobile services and multifactor authentication devices (MFA).
These methods are defined in 'security_token', which is part of the
':standard' group. See VM::EC2::REST::security_token for details. Here is a
quick example:

The 'spot_instance' and 'reserved_instance' modules allow you to create and
manipulate spot and reserved instances. They are both part of the ':misc'
import group. See VM::EC2::REST::spot_instance and
VM::EC2::REST::reserved_instance. For example:

VM::EC2 provides a series of methods that allow your script to wait in an
efficient manner for desired state changes in instances, volumes and other
objects. They are described in detail the individual modules to which they
apply, but in each case the method will block until each member of a list of
objects transitions to a terminal state (e.g. "completed" in the
case of a snapshot). Briefly:

Generic version of the last four methods. Wait for all members of the provided
list of Amazon objects instances to reach some terminal state listed in the
second argument, and then return a hash reference that maps each object ID to
its final state.

If a timeout is provided, in seconds, then the method will abort after waiting
the indicated time and return undef.

Get or change the timeout for wait_for_instances(),
wait_for_attachments(), and wait_for_volumes(). The timeout is
given in seconds, and defaults to 600 (10 minutes). You can set this to 0 to
wait forever.

This method attempts to guess what version string to use when communicating with
various endpoints. When talking to endpoints that contain the string
"Eucalyptus" uses the old EC2 API "2009-04-04". When
talking to other endpoints, uses the latest EC2 version string.

This module uses Amazon AWS signing protocol version 2, as described at
http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?using-query-api.html.
It uses the HmacSHA256 signature method, which is the most secure method
currently available. For additional security, use "https" for the
communications endpoint:

To subclass VM::EC2 objects (or implement your own from scratch) you will need
to override the object dispatch mechanism. Fortunately this is very easy.
After "use VM::EC2" call VM::EC2::Dispatch-> register()
one or more times:

VM::EC2::Dispatch->register($call_name => $dispatch).

The first argument, $call_name, is name of the Amazon API call, such as
"DescribeImages".

The second argument, $dispatch, instructs VM::EC2::Dispatch how to create
objects from the parsed XML. There are three possible syntaxes:

1) A CODE references, such as an anonymous subroutine.
In this case the code reference will be invoked to handle the
parsed XML returned from the request. The code will receive
two arguments consisting of the parsed
content of the response, and the VM::EC2 object used to generate the
request.
2) A VM::EC2::Dispatch method name, optionally followed by its arguments
delimited by commas. Example:
"fetch_items,securityGroupInfo,VM::EC2::SecurityGroup"
This tells Dispatch to invoke its fetch_items() method with
the following arguments:
$dispatch->fetch_items($parsed_xml,$ec2,'securityGroupInfo','VM::EC2::SecurityGroup')
The fetch_items() method is used for responses in which a
list of objects is embedded within a series of <item> tags.
See L<VM::EC2::Dispatch> for more information.
Other commonly-used methods are "fetch_one", and "boolean".
3) A class name, such as 'MyVolume'
In this case, class MyVolume is loaded and then its new() method
is called with the four arguments ($parsed_xml,$ec2,$xmlns,$requestid),
where $parsed_xml is the parsed XML response, $ec2 is the VM::EC2
object that generated the request, $xmlns is the XML namespace
of the XML response, and $requestid is the AWS-generated ID for the
request. Only the first two arguments are really useful.
I suggest you inherit from VM::EC2::Generic and use the inherited new()
method to store the parsed XML object and other arguments.

Dispatch tries each of (1), (2) and (3), in order. This means that class names
cannot collide with method names.

The parsed content is the result of passing the raw XML through a XML::Simple
object created with:

In general, this will give you a hash of hashes. Any tag named 'item' will be
forced to point to an array reference, and any tag named "key" will
be flattened as described in the XML::Simple documentation.

A simple way to examine the raw parsed XML is to invoke any VM::EC2::Generic's
as_string() method:

my ($i) = $ec2->describe_instances;
print $i->as_string;

This will give you a Data::Dumper representation of the XML after it has been
parsed.

The suggested way to override the dispatch table is from within a subclass of
VM::EC2:

The git source for this library can be found at
https://github.com/lstein/LibVM-EC2-Perl, To contribute to development, please
obtain a github account and then either:

1) Fork a copy of the repository, make your changes against this repository,
and send a pull request to me to incorporate your changes.
2) Contact me by email and ask for push privileges on the repository.

This package and its accompanying libraries is free software; you can
redistribute it and/or modify it under the terms of the GPL (either version 1,
or at your option, any later version) or the Artistic License 2.0. Refer to
LICENSE for the full license text. In addition, please see DISCLAIMER.txt for
disclaimers of warranty.