1VM::EC2(3)            User Contributed Perl Documentation           VM::EC2(3)
2
3
4

NAME

6       VM::EC2 - Perl interface to Amazon EC2, Virtual Private Cloud, Elastic
7       Load Balancing, Autoscaling, and Relational Database services
8

SYNOPSIS

10       NOTE: For information on AWS's VPC, load balancing, autoscaling and
11       relational databases services, see VM::EC2::VPC, VM::EC2::ELB,
12       VM::EC2::REST::autoscaling, and
13       VM::EC2::REST::relational_database_service
14
15        # set environment variables EC2_ACCESS_KEY, EC2_SECRET_KEY and/or EC2_URL
16        # to fill in arguments automatically
17
18        ## IMAGE AND INSTANCE MANAGEMENT
19        # get new EC2 object
20        my $ec2 = VM::EC2->new(-access_key => 'access key id',
21                               -secret_key => 'aws_secret_key',
22                               -endpoint   => 'http://ec2.amazonaws.com');
23
24        # fetch an image by its ID
25        my $image = $ec2->describe_images('ami-12345');
26
27        # get some information about the image
28        my $architecture = $image->architecture;
29        my $description  = $image->description;
30        my @devices      = $image->blockDeviceMapping;
31        for my $d (@devices) {
32           print $d->deviceName,"\n";
33           print $d->snapshotId,"\n";
34           print $d->volumeSize,"\n";
35        }
36
37        # run two instances
38        my @instances = $image->run_instances(-key_name      =>'My_key',
39                                              -security_group=>'default',
40                                              -min_count     =>2,
41                                              -instance_type => 't1.micro')
42                  or die $ec2->error_str;
43
44        # wait for both instances to reach "running" or other terminal state
45        $ec2->wait_for_instances(@instances);
46
47        # print out both instance's current state and DNS name
48        for my $i (@instances) {
49           my $status = $i->current_status;
50           my $dns    = $i->dnsName;
51           print "$i: [$status] $dns\n";
52        }
53
54        # tag both instances with Role "server"
55        foreach (@instances) {$_->add_tag(Role=>'server');
56
57        # stop both instances
58        foreach (@instances) {$_->stop}
59
60        # find instances tagged with Role=Server that are
61        # stopped, change the user data and restart.
62        @instances = $ec2->describe_instances({'tag:Role'       => 'Server',
63                                               'instance-state-name' => 'stopped'});
64        for my $i (@instances) {
65           $i->userData('Secure-mode: off');
66           $i->start or warn "Couldn't start $i: ",$i->error_str;
67        }
68
69        # create an image from both instance, tag them, and make
70        # them public
71        for my $i (@instances) {
72            my $img = $i->create_image("Autoimage from $i","Test image");
73            $img->add_tags(Name  => "Autoimage from $i",
74                           Role  => 'Server',
75                           Status=> 'Production');
76            $img->make_public(1);
77        }
78
79        ## KEY MANAGEMENT
80
81        # retrieve the name and fingerprint of the first instance's
82        # key pair
83        my $kp = $instances[0]->keyPair;
84        print $instances[0], ": keypair $kp=",$kp->fingerprint,"\n";
85
86        # create a new key pair
87        $kp = $ec2->create_key_pair('My Key');
88
89        # get the private key from this key pair and write it to a disk file
90        # in ssh-compatible format
91        my $private_key = $kp->private_key;
92        open (my $f,'>MyKeypair.rsa') or die $!;
93        print $f $private_key;
94        close $f;
95
96        # Import a preexisting SSH key
97        my $public_key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC8o...';
98        $key = $ec2->import_key_pair('NewKey',$public_key);
99
100        ## SECURITY GROUPS AND FIREWALL RULES
101        # Create a new security group
102        my $group = $ec2->create_security_group(-name        => 'NewGroup',
103                                                -description => 'example');
104
105        # Add a firewall rule
106        $group->authorize_incoming(-protocol  => 'tcp',
107                                   -port      => 80,
108                                   -source_ip => ['192.168.2.0/24','192.168.2.1/24'});
109
110        # Write rules back to Amazon
111        $group->update;
112
113        # Print current firewall rules
114        print join ("\n",$group->ipPermissions),"\n";
115
116        ## VOLUME && SNAPSHOT MANAGEMENT
117
118        # find existing volumes that are available
119        my @volumes = $ec2->describe_volumes({status=>'available'});
120
121        # back 'em all up to snapshots
122        foreach (@volumes) {$_->snapshot('Backup on '.localtime)}
123
124        # find a stopped instance in first volume's availability zone and
125        # attach the volume to the instance using /dev/sdg
126        my $vol  = $volumes[0];
127        my $zone = $vol->availabilityZone;
128        @instances = $ec2->describe_instances({'availability-zone'=> $zone,
129                                               'run-state-name'   => $stopped);
130        $instances[0]->attach_volume($vol=>'/dev/sdg') if @instances;
131
132        # create a new 20 gig volume
133        $vol = $ec2->create_volume(-availability_zone=> 'us-east-1a',
134                                   -size             =>  20);
135        $ec2->wait_for_volumes($vol);
136        print "Volume $vol is ready!\n" if $vol->current_status eq 'available';
137
138        # create a new elastic address and associate it with an instance
139        my $address = $ec2->allocate_address();
140        $instances[0]->associate_address($address);
141

DESCRIPTION

143       This is an interface to the 2014-05-01 version of the Amazon AWS API
144       (http://aws.amazon.com/ec2). It was written provide access to the new
145       tag and metadata interface that is not currently supported by
146       Net::Amazon::EC2, as well as to provide developers with an extension
147       mechanism for the API. This library will also support the Open Stack
148       open source cloud (http://www.openstack.org/).
149
150       The main interface is the VM::EC2 object, which provides methods for
151       interrogating the Amazon EC2, launching instances, and managing
152       instance lifecycle. These methods return the following major object
153       classes which act as specialized interfaces to AWS:
154
155        VM::EC2::BlockDevice               -- A block device
156        VM::EC2::BlockDevice::Attachment   -- Attachment of a block device to an EC2 instance
157        VM::EC2::BlockDevice::EBS          -- An elastic block device
158        VM::EC2::BlockDevice::Mapping      -- Mapping of a virtual storage device to a block device
159        VM::EC2::BlockDevice::Mapping::EBS -- Mapping of a virtual storage device to an EBS block device
160        VM::EC2::Group                     -- Security groups
161        VM::EC2::Image                     -- Amazon Machine Images (AMIs)
162        VM::EC2::Instance                  -- Virtual machine instances
163        VM::EC2::Instance::Metadata        -- Access to runtime metadata from running instances
164        VM::EC2::Region                    -- Availability regions
165        VM::EC2::Snapshot                  -- EBS snapshots
166        VM::EC2::Tag                       -- Metadata tags
167
168       In addition, there is a high level interface for interacting with EC2
169       servers and volumes, including file transfer and remote shell
170       facilities:
171
172         VM::EC2::Staging::Manager         -- Manage a set of servers and volumes.
173         VM::EC2::Staging::Server          -- A staging server, with remote shell and file transfer
174                                               facilities.
175         VM::EC2::Staging::Volume          -- A staging volume with the ability to copy itself between
176                                               availability zones and regions.
177
178       and a few specialty classes:
179
180         VM::EC2::Security::Token          -- Temporary security tokens for granting EC2 access to
181                                               non-AWS account holders.
182         VM::EC2::Security::Credentials    -- Credentials for use by temporary account holders.
183         VM::EC2::Security::Policy         -- Policies that restrict what temporary account holders
184                                               can do with EC2 resources.
185         VM::EC2::Security::FederatedUser  -- Account name information for temporary account holders.
186
187       Lastly, there are several utility classes:
188
189        VM::EC2::Generic                   -- Base class for all AWS objects
190        VM::EC2::Error                     -- Error messages
191        VM::EC2::Dispatch                  -- Maps AWS XML responses onto perl object classes
192        VM::EC2::ReservationSet            -- Hidden class used for describe_instances() request;
193                                               The reservation Ids are copied into the Instance
194                                                object.
195
196       There is also a high-level API called "VM::EC2::Staging::Manager" for
197       managing groups of staging servers and volumes which greatly simplifies
198       the task of creating and updating instances that mount multiple
199       volumes. The API also provides a one-line command for migrating EBS-
200       backed AMIs from one zone to another. See VM::EC2::Staging::Manager.
201
202       The interface provided by these modules is based on that described at
203       http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/. The
204       following caveats apply:
205
206        1) Not all of the Amazon API is currently implemented. Specifically,
207           a handful calls dealing with cluster management and VM importing
208           are missing.  See L</MISSING METHODS> for a list of all the
209           unimplemented API calls. Volunteers to fill in these gaps are
210           most welcome!
211
212        2) For consistency with common Perl coding practices, method calls
213           are lowercase and words in long method names are separated by
214           underscores. The Amazon API prefers mixed case.  So in the Amazon
215           API the call to fetch instance information is "DescribeInstances",
216           while in VM::EC2, the method is "describe_instances". To avoid
217           annoyance, if you use the mixed case form for a method name, the
218           Perl autoloader will automatically translate it to underscores for
219           you, and vice-versa; this means you can call either
220           $ec2->describe_instances() or $ec2->DescribeInstances().
221
222        3) Named arguments passed to methods are all lowercase, use
223           underscores to separate words and start with hyphens.
224           In other words, if the AWS API calls for an argument named
225           "InstanceId" to be passed to the "DescribeInstances" call, then
226           the corresponding Perl function will look like:
227
228                $instance = $ec2->describe_instances(-instance_id=>'i-12345')
229
230           In most cases automatic case translation will be performed for you
231           on arguments. So in the previous example, you could use
232           -InstanceId as well as -instance_id. The exception
233           is when an absurdly long argument name was replaced with an
234           abbreviated one as described below. In this case, you must use
235           the documented argument name.
236
237           In a small number of cases, when the parameter name was absurdly
238           long, it has been abbreviated. For example, the
239           "Placement.AvailabilityZone" parameter has been represented as
240           -placement_zone and not -placement_availability_zone. See the
241           documentation for these cases.
242
243        4) For each of the describe_foo() methods (where "foo" is a type of
244           resource such as "instance"), you can fetch the resource by using
245           their IDs either with the long form:
246
247                 $ec2->describe_foo(-foo_id=>['a','b','c']),
248
249           or a shortcut form:
250
251                 $ec2->describe_foo('a','b','c');
252
253           Both forms are listed in the headings in the documentation.
254
255        5) When the API calls for a list of arguments named Arg.1, Arg.2,
256           then the Perl interface allows you to use an anonymous array for
257           the consecutive values. For example to call describe_instances()
258           with multiple instance IDs, use:
259
260              @i = $ec2->describe_instances(-instance_id=>['i-12345','i-87654'])
261
262        6) All Filter arguments are represented as a -filter argument whose value is
263           an anonymous hash:
264
265              @i = $ec2->describe_instances(-filter=>{architecture=>'i386',
266                                                      'tag:Name'  =>'WebServer'})
267
268           If there are no other arguments you wish to pass, you can omit the
269           -filter argument and just pass a hashref:
270
271              @i = $ec2->describe_instances({architecture=>'i386',
272                                             'tag:Name'  =>'WebServer'})
273
274           For any filter, you may represent multiple OR arguments as an arrayref:
275
276             @i = $ec2->describe-instances({'instance-state-name'=>['stopped','terminated']})
277
278           When adding or removing tags, the -tag argument uses the same syntax.
279
280        7) The tagnames of each XML object returned from AWS are converted into methods
281           with the same name and typography. So the <privateIpAddress> tag in a
282           DescribeInstancesResponse, becomes:
283
284                  $instance->privateIpAddress
285
286           You can also use the more Perlish form -- this is equivalent:
287
288                 $instance->private_ip_address
289
290           Methods that correspond to complex objects in the XML hierarchy
291           return the appropriate Perl object. For example, an instance's
292           blockDeviceMapping() method returns an object of type
293           VM::EC2::BlockDevice::Mapping.
294
295           All objects have a fields() method that will return the XML
296           tagnames listed in the AWS specifications.
297
298             @fields = sort $instance->fields;
299             # 'amiLaunchIndex', 'architecture', 'blockDeviceMapping', ...
300
301        8) Whenever an object has a unique ID, string overloading is used so that
302           the object interpolates the ID into the string. For example, when you
303           print a VM::EC2::Volume object, or use it in another string context,
304           then it will appear as the string "vol-123456". Nevertheless, it will
305           continue to be usable for method calls.
306
307                ($v) = $ec2->describe_volumes();
308                print $v,"\n";                 # prints as "vol-123456"
309                $zone = $v->availabilityZone;  # acts like an object
310
311        9) Many objects have convenience methods that invoke the AWS API on your
312           behalf. For example, instance objects have a current_status() method that returns
313           the run status of the object, as well as start(), stop() and terminate()
314           methods that control the instance's lifecycle.
315
316                if ($instance->current_status eq 'running') {
317                    $instance->stop;
318                }
319
320        10) Calls to AWS that have failed for one reason or another (invalid
321           arguments, communications problems, service interruptions) will
322           return undef and set the VM::EC2->is_error() method to true. The
323           error message and its code can then be recovered by calling
324           VM::EC2->error.
325
326             $i = $ec2->describe_instance('i-123456');
327             unless ($i) {
328                 warn 'Got no instance. Message was: ',$ec2->error;
329             }
330
331           You may also elect to raise an exception when an error occurs.
332           See the new() method for details.
333

ASYNCHRONOUS CALLS

335       As of version 1.24, VM::EC2 supports asynchronous calls to AWS using
336       AnyEvent::HTTP. This allows you to make multiple calls in parallel for
337       a significant improvement in performance.
338
339       In asynchronous mode, VM::EC2 calls that ordinarily wait for AWS to
340       respond and then return objects corresponding to EC2 instances,
341       volumes, images, and so forth, will instead immediately return an
342       AnyEvent condition variable. You can retrieve the result of the call by
343       calling the condition variable's recv() method, or by setting a
344       callback to be executed when the call is complete.
345
346       To make an asynchronous call, you can set the global variable
347       $VM::EC2::ASYNC to a true value
348
349       Here is an example of a normal synchronous call:
350
351        my @instances = $ec2->describe_instances();
352
353       Here is the asynchronous version initiated after setting
354       $VM::EC2::ASYNC (using a local block to limit its effects).
355
356        {
357           local $VM::EC2::ASYNC=1;
358           my $cv = $ec2->describe_instances();   # returns immediately
359           my @instances = $cv->recv;
360        }
361
362       In case of an error recv() will return undef and the error object can
363       be recovered using the condition variable's error() method (this is an
364       enhancement over AnyEvent's standard condition variable class):
365
366        my @instances = $cv->recv
367           or die "No instances found! error = ",$cv->error();
368
369       You may attach a callback CODE reference to the condition variable
370       using its cb() method, in which case the callback will be invoked when
371       the APi call is complete. The callback will be invoked with a single
372       argument consisting of the condition variable. Ordinarily you will call
373       recv() on the variable and then do something with the result:
374
375        {
376          local $VM::EC2::ASYNC=1;
377          my $cv = $ec2->describe_instances();
378          $cv->cb(sub {my $v = shift;
379                       my @i = $v->recv;
380                       print "instances = @i\n";
381                       });
382         }
383
384       For callbacks to be invoked, someone must be run an event loop using
385       one of the event frameworks that AnyEvent supports (e.g. Coro, Tk or
386       Gtk). Alternately, you may simply run:
387
388        AnyEvent->condvar->recv();
389
390       If $VM::EC2::ASYNC is false, you can issue a single asynchronous call
391       by appending "_async" to the name of the method call. Similarly, if
392       $VM::EC2::ASYNC is true, you can make a single normal synchrous call by
393       appending "_sync" to the method name.
394
395       For example, this is equivalent to the above:
396
397        my $cv = $ec2->describe_instances_async();  # returns immediately
398        my @instances = $cv->recv;
399
400       You may stack multiple asynchronous calls on top of one another. When
401       you call recv() on any of the returned condition variables, they will
402       all run in parallel. Hence the three calls will take no longer than the
403       longest individual one:
404
405        my $cv1 = $ec2->describe_instances_async({'instance-state-name'=>'running'});
406        my $cv2 = $ec2->describe_instances_async({'instance-state-name'=>'stopped'});
407        my @running = $cv1->recv;
408        my @stopped = $cv2->recv;
409
410       Same thing with callbacks:
411
412        my (@running,@stopped);
413        my $cv1 = $ec2->describe_instances_async({'instance-state-name'=>'running'});
414        $cv1->cb(sub {@running = shift->recv});
415
416        my $cv2 = $ec2->describe_instances_async({'instance-state-name'=>'stopped'});
417        $cv1->cb(sub {@stopped = shift->recv});
418
419        AnyEvent->condvar->recv;
420
421       And here it is using a group conditional variable to block until all
422       pending describe_instances() requests have completed:
423
424        my %instances;
425        my $group = AnyEvent->condvar;
426        $group->begin;
427        for my $state (qw(pending running stopping stopped)) {
428           $group->begin;
429           my $cv = $ec2->describe_instances_async({'instance-state-name'=>$state});
430           $cv->cb(sub {my @i = shift->recv;
431                        $instances{$state}=\@i;
432                        $group->end});
433        }
434        $group->recv;
435        # when we get here %instances will be populated by all instances,
436        # sorted by their state.
437
438       If this looks mysterious, please consult AnyEvent for full
439       documentation and examples.
440
441       Lastly, be advised that some of the objects returned by calls to
442       VM::EC2, such as the VM::EC2::Instance object, will make their own
443       calls into VM::EC2 for certain methods. Some of these methods will
444       block (be synchronous) of necessity, even if you have set
445       $VM::EC2::ASYNC. For example, the instance object's current_status()
446       method must block in order to update the object and return the current
447       status. Other object methods may behave unpredictably in async mode.
448       Caveat emptor!
449

API GROUPS

451       The extensive (and growing) Amazon API has many calls that you may
452       never need. To avoid the performance overhead of loading the interfaces
453       to all these calls, you may use Perl's import mechanism to load only
454       those modules you care about. By default, all methods are loaded.
455
456       Loading is controlled by the "use" import list, and follows the
457       conventions described in the Exporter module:
458
459        use VM::EC2;                     # load all methods!
460
461        use VM::EC2 'key','elastic_ip';  # load Key Pair and Elastic IP
462                                         # methods only
463
464        use VM::EC2 ':standard';         # load all the standard methods
465
466        use VM::EC2 ':standard','!key';  # load standard methods but not Key Pair
467
468       Related API calls are grouped together using the scheme described at
469       http://docs.aws.amazon.com/AWSEC2/latest/APIReference/OperationList-query.html.
470       The modules that define the API calls can be found in VM/EC2/REST/; you
471       can read their documentation by running perldoc VM::EC2::REST::"name of
472       module":
473
474        perldoc VM::EC2::REST::elastic_ip
475
476       The groups that you can import are as follows:
477
478        :standard => ami, ebs, elastic_ip, instance, keys, general,
479                     monitoring, tag, security_group, security_token, zone
480
481        :vpc      => customer_gateway, dhcp, elastic_network_interface,
482                     private_ip, internet_gateway, network_acl, route_table,
483                     vpc, vpn, vpn_gateway
484
485        :misc     => devpay, monitoring, reserved_instance,
486                     spot_instance, vm_export, vm_import, windows
487
488        :scaling  => elastic_load_balancer,autoscaling
489
490        :hpc      => placement_group
491
492        :all      => :standard, :vpn, :misc
493
494        :DEFAULT  => :all
495
496       The individual modules are:
497
498        ami               -- Control Amazon Machine Images
499        autoscaling       -- Control autoscaling
500        customer_gateway  -- VPC/VPN gateways
501        devpay            -- DevPay API
502        dhcp              -- VPC DHCP options
503        ebs               -- Elastic Block Store volumes & snapshots
504        elastic_ip        -- Elastic IP addresses
505        elastic_load_balancer -- The Elastic Load Balancer service
506        elastic_network_interface -- VPC Elastic Network Interfaces
507        general           -- Get console output and account attributes
508        instance          -- Control EC2 instances
509        internet_gateway  -- VPC connections to the internet
510        keys              -- Manage SSH keypairs
511        monitoring        -- Control instance monitoring
512        network_acl       -- Control VPC network access control lists
513        placement_group   -- Control the placement of HPC instances
514        private_ip        -- VPC private IP addresses
515        reserved_instance -- Reserve instances and view reservations
516        route_table       -- VPC network routing
517        security_group    -- Security groups for VPCs and normal instances
518        security_token    -- Temporary credentials for use with IAM roles
519        spot_instance     -- Request and manage spot instances
520        subnet            -- VPC subnets
521        tag               -- Create and interrogate resource tags.
522        vm_export         -- Export VMs
523        vm_import         -- Import VMs
524        vpc               -- Create and manipulate virtual private clouds
525        vpn_gateway       -- Create and manipulate VPN gateways within VPCs
526        vpn               -- Create and manipulate VPNs within VPCs
527        windows           -- Windows operating system-specific API calls.
528        zone              -- Interrogate availability zones
529

EXAMPLE SCRIPT

531       The script sync_to_snapshot.pl, distributed with this module,
532       illustrates a relatively complex set of steps on EC2 that does
533       something useful. Given a list of directories or files on the local
534       filesystem it copies the files into an EBS snapshot with the desired
535       name by executing the following steps:
536
537       1. Provisions a new EBS volume on EC2 large enough to hold the data.
538
539       2. Spins up a staging instance to manage the network transfer of data
540       from the local machine to the staging volume.
541
542       3. Creates a temporary ssh keypair and a security group that allows an
543       rsync-over-ssh.
544
545       4. Formats and mounts the volume if necessary.
546
547       5. Initiates an rsync-over-ssh for the designated files and
548       directories.
549
550       6. Unmounts and snapshots the volume.
551
552       7. Cleans up.
553
554       If a snapshot of the same name already exists, then it is used to
555       create the staging volume, enabling network-efficient synchronization
556       of the files. A snapshot tag named "Version" is incremented each time
557       you synchronize.
558

CORE METHODS

560       This section describes the VM::EC2 constructor, accessor methods, and
561       methods relevant to error handling.
562
563   $ec2 = VM::EC2->new(-access_key=>$id,-secret_key=>$key,-endpoint=>$url)
564       Create a new Amazon access object. Required arguments are:
565
566        -access_key   Access ID for an authorized user
567
568        -secret_key   Secret key corresponding to the Access ID
569
570        -security_token Temporary security token obtained through a call to the
571                      AWS Security Token Service
572
573        -endpoint     The URL for making API requests
574
575        -region       The region to receive the API requests
576
577        -raise_error  If true, throw an exception.
578
579        -print_error  If true, print errors to STDERR.
580
581       One or more of -access_key or -secret_key can be omitted if the
582       environment variables EC2_ACCESS_KEY and EC2_SECRET_KEY are defined. If
583       no endpoint is specified, then the environment variable EC2_URL is
584       consulted; otherwise the generic endpoint http://ec2.amazonaws.com/ is
585       used. You can also select the endpoint by specifying one of the Amazon
586       regions, such as "us-west-2", with the -region argument. The endpoint
587       specified by -region will override -endpoint.
588
589       -security_token is used in conjunction with temporary security tokens
590       returned by $ec2->get_federation_token() and $ec2->get_session_token()
591       to grant restricted, time-limited access to some or all your EC2
592       resources to users who do not have access to your account. If you pass
593       either a VM::EC2::Security::Token object, or the
594       VM::EC2::Security::Credentials object contained within the token
595       object, then new() does not need the -access_key or -secret_key
596       arguments. You may also pass a session token string scalar to
597       -security_token, in which case you must also pass the access key ID and
598       secret keys generated at the same time the session token was created.
599       See
600       http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/UsingIAM.html
601       and "AWS SECURITY TOKENS".
602
603       To use an Open Stack cloud, please provide the appropriate endpoint
604       URL.
605
606       By default, when the Amazon API reports an error, such as attempting to
607       perform an invalid operation on an instance, the corresponding method
608       will return empty and the error message can be recovered from
609       $ec2->error(). However, if you pass -raise_error=>1 to new(), the
610       module will instead raise a fatal error, which you can trap with eval{}
611       and report with $@:
612
613         eval {
614            $ec2->some_dangerous_operation();
615            $ec2->another_dangerous_operation();
616         };
617         print STDERR "something bad happened: $@" if $@;
618
619       The error object can be retrieved with $ec2->error() as before.
620
621   $access_key = $ec2->access_key([$new_access_key])
622       Get or set the ACCESS KEY. In this and all similar get/set methods,
623       call the method with no arguments to get the current value, and with a
624       single argument to change the value:
625
626        $current_key = $ec2->access_key;
627        $ec2->access_key('XYZZY');
628
629       In the case of setting the value, these methods will return the old
630       value as their result:
631
632        $old_key = $ec2->access_key($new_key);
633
634   $secret = $ec2->secret([$new_secret])
635       Get or set the SECRET KEY
636
637   $secret = $ec2->security_token([$new_token])
638       Get or set the temporary security token. See "AWS SECURITY TOKENS".
639
640   $endpoint = $ec2->endpoint([$new_endpoint])
641       Get or set the ENDPOINT URL.
642
643   $region = $ec2->region([$new_region])
644       Get or set the EC2 region manipulated by this module. This has the side
645       effect of changing the endpoint.
646
647   $ec2->raise_error($boolean)
648       Change the handling of error conditions. Pass a true value to cause
649       Amazon API errors to raise a fatal error. Pass false to make methods
650       return undef. In either case, you can detect the error condition by
651       calling is_error() and fetch the error message using error(). This
652       method will also return the current state of the raise error flag.
653
654   $ec2->print_error($boolean)
655       Change the handling of error conditions. Pass a true value to cause
656       Amazon API errors to print error messages to STDERR. Pass false to
657       cancel this behavior.
658
659   $boolean = $ec2->is_error
660       If a method fails, it will return undef. However, some methods, such as
661       describe_images(), will also return undef if no resources matches your
662       search criteria. Call is_error() to distinguish the two eventualities:
663
664         @images = $ec2->describe_images(-owner=>'29731912785');
665         unless (@images) {
666             die "Error: ",$ec2->error if $ec2->is_error;
667             print "No appropriate images found\n";
668         }
669
670   $err = $ec2->error
671       If the most recently-executed method failed, $ec2->error() will return
672       the error code and other descriptive information. This method will
673       return undef if the most recently executed method was successful.
674
675       The returned object is actually an AWS::Error object, which has two
676       methods named code() and message(). If used in a string context, its
677       operator overloading returns the composite string "$message [$code]".
678
679   $err = $ec2->error_str
680       Same as error() except it returns the string representation, not the
681       object. This works better in debuggers and exception handlers.
682
683   $account_id = $ec2->account_id
684       Looks up the account ID corresponding to the credentials provided when
685       the VM::EC2 instance was created. The way this is done is to fetch the
686       "default" security group, which is guaranteed to exist, and then return
687       its groupId field. The result is cached so that subsequent accesses are
688       fast.
689
690   $account_id = $ec2->userId
691       Same as above, for convenience.
692
693   $new_ec2 = $ec2->clone
694       This method creates an identical copy of the EC2 object. It is used
695       occasionally internally for creating an EC2 object in a different AWS
696       region:
697
698        $singapore = $ec2->clone;
699        $singapore->region('ap-souteast-1');
700

INSTANCES

702       Load the 'instances' module to bring in methods for interrogating,
703       launching and manipulating EC2 instances. This module is part of the
704       ':standard' API group. The methods are described in detail in
705       VM::EC2::REST::instance. Briefly:
706
707        @i = $ec2->describe_instances(-instance_id=>\@ids,-filter=>\%filters)
708        @i = $ec2->run_instances(-image_id=>$id,%other_args)
709        @s = $ec2->start_instances(-instance_id=>\@instance_ids)
710        @s = $ec2->stop_instances(-instance_id=>\@instance_ids,-force=>1)
711        @s = $ec2->reboot_instances(-instance_id=>\@instance_ids)
712        $b = $ec2->confirm_product_instance($instance_id,$product_code)
713        $m = $ec2->instance_metadata
714        @d = $ec2->describe_instance_attribute($instance_id,$attribute)
715        $b = $ec2->modify_instance_attribute($instance_id,-$attribute_name=>$value)
716        $b = $ec2->reset_instance_attribute($instance_id,$attribute)
717        @s = $ec2->describe_instance_status(-instance_id=>\@ids,-filter=>\%filters,%other_args);
718

VOLUMES

720       Load the 'ebs' module to bring in methods specific for elastic block
721       storage volumes and snapshots. This module is part of the ':standard'
722       API group. The methods are described in detail in VM::EC2::REST::ebs.
723       Briefly:
724
725        @v = $ec2->describe_volumes(-volume_id=>\@ids,-filter=>\%filters)
726        $v = $ec2->create_volume(%args)
727        $b = $ec2->delete_volume($volume_id)
728        $a = $ec2->attach_volume($volume_id,$instance_id,$device)
729        $a = $ec2->detach_volume($volume_id)
730        $ec2->wait_for_attachments(@attachment)
731        @v = $ec2->describe_volume_status(-volume_id=>\@ids,-filter=>\%filters)
732        $ec2->wait_for_volumes(@volumes)
733        @d = $ec2->describe_volume_attribute($volume_id,$attribute)
734        $b = $ec2->enable_volume_io(-volume_id=>$volume_id)
735        @s = $ec2->describe_snapshots(-snapshot_id=>\@ids,%other_args)
736        @d = $ec2->describe_snapshot_attribute($snapshot_id,$attribute)
737        $b = $ec2->modify_snapshot_attribute($snapshot_id,-$argument=>$value)
738        $b = $ec2->reset_snapshot_attribute($snapshot_id,$attribute)
739        $s = $ec2->create_snapshot(-volume_id=>$vol,-description=>$desc)
740        $b = $ec2->delete_snapshot($snapshot_id)
741        $s = $ec2->copy_snapshot(-source_region=>$region,-source_snapshot_id=>$id,-description=>$desc)
742        $ec2->wait_for_snapshots(@snapshots)
743

AMAZON MACHINE IMAGES

745       Load the 'ami' module to bring in methods for creating and manipulating
746       Amazon Machine Images. This module is part of the ':standard" group.
747       Full details are in VM::EC2::REST::ami. Briefly:
748
749        @i = $ec2->describe_images(@image_ids)
750        $i = $ec2->create_image(-instance_id=>$id,-name=>$name,%other_args)
751        $i = $ec2->register_image(-name=>$name,%other_args)
752        $r = $ec2->deregister_image($image_id)
753        @d = $ec2->describe_image_attribute($image_id,$attribute)
754        $b = $ec2->modify_image_attribute($image_id,-$attribute_name=>$value)
755        $b = $ec2->reset_image_attribute($image_id,$attribute_name)
756

KEYS

758       Load the 'keys' module to bring in methods for creating and
759       manipulating SSH keypairs. This module is loaded with the ':standard'
760       group and documented in VM::EC2::REST::keys.
761
762        @k = $ec2->describe_key_pairs(@names);
763        $k = $ec2->create_key_pair($name)
764        $k = $ec2->import_key_pair($name,$public_key)
765        $b = $ec2->delete_key_pair($name)
766

TAGS

768       The methods in this module (loaded with ':standard') allow you to
769       create, delete and fetch resource tags. You may find that you rarely
770       need to use these methods directly because every object produced by
771       VM::EC2 supports a simple tag interface:
772
773         $object = $ec2->describe_volumes(-volume_id=>'vol-12345'); # e.g.
774         $tags = $object->tags();
775         $name = $tags->{Name};
776         $object->add_tags(Role => 'Web Server', Status=>'development);
777         $object->delete_tags(Name=>undef);
778
779       See VM::EC2::Generic for a full description of the uniform object
780       tagging interface, and VM::EC2::REST::tag for methods that allow you to
781       manipulate the tags on multiple objects simultaneously. The methods
782       defined by this module are:
783
784        @t = $ec2->describe_tags(-filter=>\%filters);
785        $b = $ec2->create_tags(-resource_id=>\@ids,-tag=>{key1=>value1...})
786        $b = $ec2->delete_tags(-resource_id=>$id1,-tag=>{key1=>value1...})
787

VIRTUAL PRIVATE CLOUDS

789       EC2 virtual private clouds (VPCs) provide facilities for creating
790       tiered applications combining public and private subnetworks, and for
791       extending your home/corporate network into the cloud. VPC-related
792       methods are defined in the customer_gateway, dhcp,
793       elastic_network_interface, private_ip, internet_gateway, network_acl,
794       route_table, vpc, vpn, and vpn_gateway modules, and are loaded by
795       importing ':vpc'. See VM::EC2::REST::vpc for an introduction.
796
797       The VM::EC2::VPC and VM::EC2::VPC::Subnet modules define convenience
798       methods that simplify working with VPC objects. This allows for steps
799       that typically follow each other, such as creating a route table and
800       associating it with a subnet, happen automatically. For example, this
801       series of calls creates a VPC with a single subnet, creates an Internet
802       gateway attached to the VPC, associates a new route table with the
803       subnet and then creates a default route from the subnet to the Internet
804       gateway:
805
806        $vpc       = $ec2->create_vpc('10.0.0.0/16')     or die $ec2->error_str;
807        $subnet1   = $vpc->create_subnet('10.0.0.0/24')  or die $vpc->error_str;
808        $gateway   = $vpc->create_internet_gateway       or die $vpc->error_str;
809        $routeTbl  = $subnet->create_route_table         or die $vpc->error_str;
810        $routeTbl->create_route('0.0.0.0/0' => $gateway) or die $vpc->error_str;
811

ELASTIC LOAD BALANCERS (ELB) AND AUTOSCALING

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

AWS SECURITY POLICY

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

AWS SECURITY TOKENS

828       AWS security tokens provide a way to grant temporary access to
829       resources in your EC2 space without giving them permanent accounts.
830       They also provide the foundation for mobile services and multifactor
831       authentication devices (MFA). These methods are defined in
832       'security_token', which is part of the ':standard' group. See
833       VM::EC2::REST::security_token for details. Here is a quick example:
834
835       Here is an example:
836
837        # on your side of the connection
838        $ec2 = VM::EC2->new(...);  # as usual
839        my $policy = VM::EC2::Security::Policy->new;
840        $policy->allow('DescribeImages','RunInstances');
841        my $token = $ec2->get_federation_token(-name     => 'TemporaryUser',
842                                               -duration => 60*60*3, # 3 hrs, as seconds
843                                               -policy   => $policy);
844        my $serialized = $token->credentials->serialize;
845        send_data_to_user_somehow($serialized);
846
847        # on the temporary user's side of the connection
848        my $serialized = get_data_somehow();
849        my $token = VM::EC2::Security::Credentials->new_from_serialized($serialized);
850        my $ec2   = VM::EC2->new(-security_token => $token);
851        print $ec2->describe_images(-owner=>'self');
852

SPOT AND RESERVED INSTANCES

854       The 'spot_instance' and 'reserved_instance' modules allow you to create
855       and manipulate spot and reserved instances. They are both part of the
856       ':misc' import group. See VM::EC2::REST::spot_instance and
857       VM::EC2::REST::reserved_instance. For example:
858
859        @offerings = $ec2->describe_reserved_instances_offerings(
860                 {'availability-zone'   => 'us-east-1a',
861                  'instance-type'       => 'c1.medium',
862                  'product-description' =>'Linux/UNIX',
863                  'duration'            => 31536000,  # this is 1 year
864                  });
865        $offerings[0]->purchase(5) and print "Five reserved instances purchased\n";
866

WAITING FOR STATE CHANGES

868       VM::EC2 provides a series of methods that allow your script to wait in
869       an efficient manner for desired state changes in instances, volumes and
870       other objects. They are described in detail the individual modules to
871       which they apply, but in each case the method will block until each
872       member of a list of objects transitions to a terminal state (e.g.
873       "completed" in the case of a snapshot). Briefly:
874
875        $ec2->wait_for_instances(@instances)
876        $ec2->wait_for_snapshots(@snapshots)
877        $ec2->wait_for_volumes(@volumes)
878        $ec2->wait_for_attachments(@attachment)
879
880       There is also a generic version of this defined in the VM::EC2 core:
881
882   $ec2->wait_for_terminal_state(\@objects,['list','of','states'] [,$timeout])
883       Generic version of the last four methods. Wait for all members of the
884       provided list of Amazon objects instances to reach some terminal state
885       listed in the second argument, and then return a hash reference that
886       maps each object ID to its final state.
887
888       If a timeout is provided, in seconds, then the method will abort after
889       waiting the indicated time and return undef.
890
891   $timeout = $ec2->wait_for_timeout([$new_timeout]);
892       Get or change the timeout for wait_for_instances(),
893       wait_for_attachments(), and wait_for_volumes(). The timeout is given in
894       seconds, and defaults to 600 (10 minutes). You can set this to 0 to
895       wait forever.
896

INTERNAL METHODS

898       These methods are used internally and are listed here without
899       documentation (yet).
900
901   $underscore_name = $ec2->canonicalize($mixedCaseName)
902   $instance_id = $ec2->instance_parm(@args)
903   @arguments = $ec2->value_parm(ParameterName => \%args)
904   @arguments = $ec2->single_parm(ParameterName => \%args)
905   @parameters = $ec2->prefix_parm($prefix, ParameterName => \%args)
906   @arguments = $ec2->member_hash_parms(ParameterName => \%args)
907       Create a parameter list from a hashref or arrayref of hashes
908
909       Created specifically for the RDS ModifyDBParameterGroup parameter
910       'Parameters', but may be useful for other calls in the future.
911
912       ie:
913
914       The argument would be in the form:
915
916          [
917                  {
918                          ParameterName=>'max_user_connections',
919                          ParameterValue=>24,
920                          ApplyMethod=>'pending-reboot'
921                  },
922                  {
923                          ParameterName=>'max_allowed_packet',
924                          ParameterValue=>1024,
925                          ApplyMethod=>'immediate'
926                  },
927          ];
928
929       The resulting output would be if the argname is '-parameters':
930
931       Parameters.member.1.ParameterName => max_user_connections
932       Parameters.member.1.ParameterValue => 24
933       Parameters.member.1.ApplyMethod => pending-reboot
934       Parameters.member.2.ParameterName => max_allowed_packet
935       Parameters.member.2.ParameterValue => 1024
936       Parameters.member.2.ApplyMethod => immediate
937
938   @arguments = $ec2->list_parm(ParameterName => \%args)
939   @parameters = $ec2->member_list_parm(ParameterName => \%args)
940   @arguments = $ec2->filter_parm(\%args)
941   @arguments =
942       $ec2->key_value_parameters($param_name,$keyname,$valuename,\%args,$skip_undef_values)
943   @arguments =
944       $ec2->member_key_value_parameters($param_name,$keyname,$valuename,\%args,$skip_undef_values)
945   @arguments = $ec2->launch_perm_parm($prefix,$suffix,$value)
946   @arguments = $ec2->iam_parm($args)
947   @arguments = $ec2->block_device_parm($block_device_mapping_string)
948   $version = $ec2->version()
949       Returns the API version to be sent to the endpoint. Calls
950       guess_version_from_endpoint() to determine this.
951
952   $version = $ec2->guess_version_from_endpoint()
953       This method attempts to guess what version string to use when
954       communicating with various endpoints. When talking to endpoints that
955       contain the string "Eucalyptus" uses the old EC2 API "2009-04-04". When
956       talking to other endpoints, uses the latest EC2 version string.
957
958   $ts = $ec2->timestamp
959   @obj = $ec2->call($action,@param);
960       Make a call to Amazon using $action and the passed arguments, and
961       return a list of objects.
962
963       if $VM::EC2::ASYNC is set to true, then will return a AnyEvent::CondVar
964       object instead of a list of objects. You may retrieve the objects by
965       calling recv() or setting a callback:
966
967           $VM::EC2::ASYNC = 1;
968           my $cv  = $ec2->call('DescribeInstances');
969           my @obj = $cv->recv;
970
971       or
972
973           $VM::EC2::ASYNC = 1;
974           my $cv  = $ec2->call('DescribeInstances');
975           $cv->cb(sub { my @objs = shift->recv;
976                         do_something(@objs);
977                       });
978
979   $url = $ec2->login_url(-credentials => $credentials, -issuer =>
980       $issuer_url, -destination => $console_url);
981       Returns an HTTP::Request object that points to the URL to login a user
982       with STS credentials
983
984         -credentials => $fed_token->credentials - Credentials from an $ec2->get_federation_token call
985         -token => $token                        - a SigninToken from $ec2->get_signin_token call
986         -issuer => $issuer_url
987         -destination => $console_url            - URL of the AWS console. Defaults to https://console.aws.amazon.com/console/home
988         -auto_scaling_group_names     List of auto scaling groups to describe
989         -names                        Alias of -auto_scaling_group_names
990
991       -credentials or -token are required for this method to work
992
993       Usage can be:
994
995         my $fed_token = $ec2->get_federation_token(...);
996         my $token = $ec2->get_signin_token(-credentials => $fed_token->credentials);
997         my $url = $ec2->login_url(-token => $token->{SigninToken}, -issuer => $issuer_url, -destination => $console_url);
998
999       Or:
1000
1001         my $fed_token = $ec2->get_federation_token(...);
1002         my $url = $ec2->login_url(-credentials => $fed_token->credentials, -issuer => $issuer_url, -destination => $console_url);
1003
1004   $request = $ec2->_sign(@args)
1005       Create and sign an HTTP::Request.
1006
1007   @param = $ec2->args(ParamName=>@_)
1008       Set up calls that take either method(-resource_id=>'foo') or
1009       method('foo').
1010

OTHER INFORMATION

1012       This section contains technical information that may be of interest to
1013       developers.
1014
1015   Signing and authentication protocol
1016       This module uses Amazon AWS signing protocol version 2, as described at
1017       http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?using-query-api.html.
1018       It uses the HmacSHA256 signature method, which is the most secure
1019       method currently available. For additional security, use "https" for
1020       the communications endpoint:
1021
1022         $ec2 = VM::EC2->new(-endpoint=>'https://ec2.amazonaws.com');
1023
1024   Subclassing VM::EC2 objects
1025       To subclass VM::EC2 objects (or implement your own from scratch) you
1026       will need to override the object dispatch mechanism. Fortunately this
1027       is very easy. After "use VM::EC2" call VM::EC2::Dispatch->register()
1028       one or more times:
1029
1030        VM::EC2::Dispatch->register($call_name => $dispatch).
1031
1032       The first argument, $call_name, is name of the Amazon API call, such as
1033       "DescribeImages".
1034
1035       The second argument, $dispatch, instructs VM::EC2::Dispatch how to
1036       create objects from the parsed XML. There are three possible syntaxes:
1037
1038        1) A CODE references, such as an anonymous subroutine.
1039
1040           In this case the code reference will be invoked to handle the
1041           parsed XML returned from the request. The code will receive
1042           two arguments consisting of the parsed
1043           content of the response, and the VM::EC2 object used to generate the
1044           request.
1045
1046        2) A VM::EC2::Dispatch method name, optionally followed by its arguments
1047           delimited by commas. Example:
1048
1049                  "fetch_items,securityGroupInfo,VM::EC2::SecurityGroup"
1050
1051           This tells Dispatch to invoke its fetch_items() method with
1052           the following arguments:
1053
1054            $dispatch->fetch_items($parsed_xml,$ec2,'securityGroupInfo','VM::EC2::SecurityGroup')
1055
1056           The fetch_items() method is used for responses in which a
1057           list of objects is embedded within a series of <item> tags.
1058           See L<VM::EC2::Dispatch> for more information.
1059
1060           Other commonly-used methods are "fetch_one", and "boolean".
1061
1062        3) A class name, such as 'MyVolume'
1063
1064           In this case, class MyVolume is loaded and then its new() method
1065           is called with the four arguments ($parsed_xml,$ec2,$xmlns,$requestid),
1066           where $parsed_xml is the parsed XML response, $ec2 is the VM::EC2
1067           object that generated the request, $xmlns is the XML namespace
1068           of the XML response, and $requestid is the AWS-generated ID for the
1069           request. Only the first two arguments are really useful.
1070
1071           I suggest you inherit from VM::EC2::Generic and use the inherited new()
1072           method to store the parsed XML object and other arguments.
1073
1074       Dispatch tries each of (1), (2) and (3), in order. This means that
1075       class names cannot collide with method names.
1076
1077       The parsed content is the result of passing the raw XML through a
1078       XML::Simple object created with:
1079
1080        XML::Simple->new(ForceArray    => ['item'],
1081                         KeyAttr       => ['key'],
1082                         SuppressEmpty => undef);
1083
1084       In general, this will give you a hash of hashes. Any tag named 'item'
1085       will be forced to point to an array reference, and any tag named "key"
1086       will be flattened as described in the XML::Simple documentation.
1087
1088       A simple way to examine the raw parsed XML is to invoke any
1089       VM::EC2::Generic's as_string() method:
1090
1091        my ($i) = $ec2->describe_instances;
1092        print $i->as_string;
1093
1094       This will give you a Data::Dumper representation of the XML after it
1095       has been parsed.
1096
1097       The suggested way to override the dispatch table is from within a
1098       subclass of VM::EC2:
1099
1100        package 'VM::EC2New';
1101        use base 'VM::EC2';
1102         sub new {
1103             my $self=shift;
1104             VM::EC2::Dispatch->register('call_name_1'=>\&subroutine1).
1105             VM::EC2::Dispatch->register('call_name_2'=>\&subroutine2).
1106             $self->SUPER::new(@_);
1107        }
1108
1109       See VM::EC2::Dispatch for a working example of subclassing VM::EC2 and
1110       one of its object classes.
1111

DEVELOPING

1113       The git source for this library can be found at
1114       https://github.com/lstein/LibVM-EC2-Perl, To contribute to development,
1115       please obtain a github account and then either:
1116
1117        1) Fork a copy of the repository, make your changes against this repository,
1118           and send a pull request to me to incorporate your changes.
1119
1120        2) Contact me by email and ask for push privileges on the repository.
1121
1122       See http://help.github.com/ for help getting started.
1123

SEE ALSO

1125       Net::Amazon::EC2 VM::EC2::Dispatch VM::EC2::Generic
1126       VM::EC2::BlockDevice VM::EC2::BlockDevice::Attachment
1127       VM::EC2::BlockDevice::EBS VM::EC2::BlockDevice::Mapping
1128       VM::EC2::BlockDevice::Mapping::EBS VM::EC2::Error VM::EC2::Generic
1129       VM::EC2::Group VM::EC2::Image VM::EC2::Instance
1130       VM::EC2::Instance::ConsoleOutput VM::EC2::Instance::Metadata
1131       VM::EC2::Instance::MonitoringState VM::EC2::Instance::PasswordData
1132       VM::EC2::Instance::Set VM::EC2::Instance::State
1133       VM::EC2::Instance::State::Change VM::EC2::Instance::State::Reason
1134       VM::EC2::KeyPair VM::EC2::Region VM::EC2::ReservationSet
1135       VM::EC2::ReservedInstance VM::EC2::ReservedInstance::Offering
1136       VM::EC2::SecurityGroup VM::EC2::Snapshot VM::EC2::Staging::Manager
1137       VM::EC2::Tag VM::EC2::Volume
1138

AUTHOR

1140       Lincoln Stein <lincoln.stein@gmail.com>.
1141
1142       Copyright (c) 2011 Ontario Institute for Cancer Research
1143
1144       This package and its accompanying libraries is free software; you can
1145       redistribute it and/or modify it under the terms of the GPL (either
1146       version 1, or at your option, any later version) or the Artistic
1147       License 2.0.  Refer to LICENSE for the full license text. In addition,
1148       please see DISCLAIMER.txt for disclaimers of warranty.
1149

POD ERRORS

1151       Hey! The above document had some coding errors, which are explained
1152       below:
1153
1154       Around line 1057:
1155           Unterminated L<...> sequence
1156
1157
1158
1159perl v5.32.1                      2021-01-27                        VM::EC2(3)
Impressum