1VM::EC2::REST::instanceU(s3e)r Contributed Perl DocumentaVtMi:o:nEC2::REST::instance(3)
2
3
4
6 VM::EC2::REST::instance - VM::EC2 methods for controlling instances
7
9 use VM::EC2 ':standard';
10
12 The methods in this section allow you to retrieve information about EC2
13 instances, launch new instances, control the instance lifecycle (e.g.
14 starting and stopping them), and fetching the console output from
15 instances.
16
17 Implemented:
18 ConfirmProductInstance
19 DescribeInstanceAttribute
20 DescribeInstances
21 DescribeInstanceStatus
22 ModifyInstanceAttribute
23 RebootInstances
24 ResetInstanceAttribute
25 RunInstances
26 StartInstances
27 StopInstances
28 TerminateInstances
29
30 Unimplemented:
31 (none)
32
33 The primary object manipulated by these methods is VM::EC2::Instance.
34 Please see the VM::EC2::Instance manual page for additional methods
35 that allow you to attach and detach volumes, modify an instance's
36 attributes, and convert instances into images.
37
38 @instances = $ec2->describe_instances(@instance_ids)
39 @instances = $ec2->describe_instances(\%filters)
40 @instances =
41 $ec2->describe_instances(-instance_id=>\@ids,-filter=>\%filters)
42 Return a series of VM::EC2::Instance objects. Optional arguments are:
43
44 -instance_id ID of the instance(s) to return information on.
45 This can be a string scalar, or an arrayref.
46
47 -filter Tags and other filters to apply.
48
49 The filter argument is a hashreference in which the keys are the filter
50 names, and the values are the match strings. Some filters accept
51 wildcards.
52
53 A typical filter example:
54
55 $ec2->describe_instances(
56 -filter => {'block-device-mapping.device-name'=>'/dev/sdh',
57 'architecture' => 'i386',
58 'tag:Role' => 'Server'
59 });
60
61 You may omit the -filter argument name if there are no other arguments:
62
63 $ec2->describe_instances({'block-device-mapping.device-name'=>'/dev/sdh',
64 'architecture' => 'i386',
65 'tag:Role' => 'Server'});
66
67 There are a large number of filters, which are listed in full at
68 http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html.
69
70 Here is a alpha-sorted list of filter names: architecture,
71 availability-zone, block-device-mapping.attach-time,
72 block-device-mapping.delete-on-termination,
73 block-device-mapping.device-name, block-device-mapping.status,
74 block-device-mapping.volume-id, client-token, dns-name, group-id,
75 group-name, hypervisor, image-id, instance-id, instance-lifecycle,
76 instance-state-code, instance-state-name, instance-type,
77 instance.group-id, instance.group-name, ip-address, kernel-id, key-
78 name, launch-index, launch-time, monitoring-state, owner-id, placement-
79 group-name, platform, private-dns-name, private-ip-address, product-
80 code, ramdisk-id, reason, requester-id, reservation-id, root-device-
81 name, root-device-type, source-dest-check, spot-instance-request-id,
82 state-reason-code, state-reason-message, subnet-id, tag-key, tag-value,
83 tag:key, virtualization-type, vpc-id.
84
85 Note that the objects returned from this method are the instances
86 themselves, and not a reservation set. The reservation ID can be
87 retrieved from each instance by calling its reservationId() method.
88
89 @i = $ec2->run_instances($ami_id)
90 @i = $ec2->run_instances(-image_id=>$id,%other_args)
91 This method will provision and launch one or more instances given an
92 AMI ID. If successful, the method returns a series of VM::EC2::Instance
93 objects.
94
95 If called with a single argument this will be interpreted as the AMI to
96 launch, and all other arguments will take their defaults. Otherwise,
97 the arguments will be taken as a -parameter=>$argument list.
98
99 Required arguments:
100 -image_id ID of an AMI to launch
101
102 Optional arguments:
103 -min_count Minimum number of instances to launch [1]
104
105 -max_count Maximum number of instances to launch [1]
106
107 -key_name Name of the keypair to use
108
109 -security_group_id Security group ID to use for this instance.
110 Use an arrayref for multiple group IDs
111
112 -security_group Security group name to use for this instance.
113 Use an arrayref for multiple values.
114
115 -user_data User data to pass to the instances. Do NOT base64
116 encode this. It will be done for you.
117
118 -instance_type Type of the instance to use. See below for a
119 list.
120
121 -availability_zone The availability zone you want to launch the
122 instance into. Call $ec2->regions for a list.
123
124 -zone Short version of -availability_aone.
125
126 -placement_zone Deprecated version of -availability_zone.
127
128 -placement_group An existing placement group to launch the
129 instance into. Applicable to cluster instances
130 only.
131
132 -tenancy Specify 'dedicated' to launch the instance on a
133 dedicated server. Only applicable for VPC
134 instances.
135
136 -kernel_id ID of the kernel to use for the instances,
137 overriding the kernel specified in the image.
138
139 -ramdisk_id ID of the ramdisk to use for the instances,
140 overriding the ramdisk specified in the image.
141
142 -block_devices Specify block devices to map onto the instances,
143 overriding the values specified in the image.
144 See below for the syntax of this argument.
145
146 -block_device_mapping Alias for -block_devices.
147
148 -monitoring Pass a true value to enable detailed monitoring.
149
150 -subnet_id ID of the subnet to launch the instance
151 into. Only applicable for VPC instances.
152
153 -termination_protection Pass true to lock the instance so that it
154 cannot be terminated using the API. Use
155 modify_instance() to unset this if youu wish to
156 terminate the instance later.
157
158 -disable_api_termination -- Same as above.
159
160 -shutdown_behavior Pass "stop" (the default) to stop the instance
161 and save its disk state when "shutdown" is called
162 from within the instance. Stopped instances can
163 be restarted later. Pass "terminate" to
164 instead terminate the instance and discard its
165 state completely.
166
167 -instance_initiated_shutdown_behavior -- Same as above.
168
169 -private_ip_address Assign the instance to a specific IP address
170 from a VPC subnet (VPC only).
171
172 -client_token Unique identifier that you can provide to ensure
173 idempotency of the request. You can use
174 $ec2->token() to generate a suitable identifier.
175 See http://docs.amazonwebservices.com/AWSEC2/
176 latest/UserGuide/Run_Instance_Idempotency.html
177
178 -network_interfaces A single network interface specification string
179 or a list of them as an array reference (VPC only).
180 These are described in more detail below.
181
182 -iam_arn The Amazon resource name (ARN) of the IAM Instance Profile (IIP)
183 to associate with the instances.
184
185 -iam_name The name of the IAM instance profile (IIP) to associate with the
186 instances.
187
188 -ebs_optimized Boolean. If true, create an EBS-optimized instance
189 (valid only for certain instance types.
190
191 Instance types
192 The following is the list of instance types currently allowed by
193 Amazon:
194
195 m1.small c1.medium m2.xlarge cc1.4xlarge cg1.4xlarge t1.micro
196 m1.large c1.xlarge m2.2xlarge
197 m1.xlarge m2.4xlarge
198
199 Block device syntax
200 The syntax of -block_devices is identical to what is used by the
201 ec2-run-instances command-line tool. Borrowing from the manual page
202 of that tool:
203
204 The format is '<device>=<block-device>', where 'block-device' can
205 be one of the following:
206
207 - 'none': indicates that a block device that would be exposed at the
208 specified device should be suppressed. For example: '/dev/sdb=none'
209
210 - 'ephemeral[0-3]': indicates that the Amazon EC2 ephemeral store
211 (instance local storage) should be exposed at the specified device.
212 For example: '/dev/sdc=ephemeral0'.
213
214 - 'vol-12345678': A volume ID will attempt to attach the given volume to the
215 instance, contingent on volume state and availability zone.
216
217 - 'none': Suppress this block device, even if it is mapped in the AMI.
218
219 - '[<snapshot-id>][:<size>[:<delete-on-termination>[:<volume-type>[:<iops>]]]]':
220 indicates that an Amazon EBS volume, created from the specified Amazon EBS
221 snapshot, should be exposed at the specified device. The following
222 combinations are supported:
223
224 - '<snapshot-id>': the ID of an Amazon EBS snapshot, which must
225 be owned by or restorable by the caller. May be left out if a
226 <size> is specified, creating an empty Amazon EBS volume of
227 the specified size.
228
229 - '<size>': the size (GiBs) of the Amazon EBS volume to be
230 created. If a snapshot was specified, this may not be smaller
231 than the size of the snapshot itself.
232
233 - '<delete-on-termination>': indicates whether the Amazon EBS
234 volume should be deleted on instance termination. If not
235 specified, this will default to 'true' and the volume will be
236 deleted.
237
238 - '<volume-type>': The volume type. One of "standard", "gp2" or "io1".
239 "gp2" is the new general purpose SSD type.
240
241 - '<iops>': The number of I/O operations per second (IOPS) that
242 the volume suports. A number between 100 to 4000. Only valid
243 for volumes of type "io1".
244
245 Examples: -block_devices => '/dev/sdb=snap-7eb96d16'
246 -block_devices => '/dev/sdc=snap-7eb96d16:80:false'
247 -block_devices => '/dev/sdd=:120'
248 -block_devices => '/dev/sdc=:120:true:io1:500'
249
250 To provide multiple mappings, use an array reference. In this
251 example, we launch two 'm1.small' instance in which /dev/sdb is
252 mapped to ephemeral storage and /dev/sdc is mapped to a new 100 G
253 EBS volume:
254
255 @i=$ec2->run_instances(-image_id => 'ami-12345',
256 -min_count => 2,
257 -block_devices => ['/dev/sdb=ephemeral0',
258 '/dev/sdc=:100:true']
259 )
260
261 Network interface syntax
262 Each instance has a single primary network interface and private IP
263 address that is ordinarily automatically assigned by Amazon. When
264 you are running VPC instances, however, you can add additional
265 elastic network interfaces (ENIs) to the instance and add secondary
266 private IP addresses to one or more of these ENIs. ENIs can exist
267 independently of instances, and be detached and reattached in much
268 the same way as EBS volumes. This is explained in detail at
269 http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/using-instance-addressing.html.
270
271 The network configuration can be specified using the
272 -network_interface parameter:
273
274 -network_interfaces => ['eth0=10.10.0.12:subnet-1234567:sg-1234567:true:My Custom Eth0',
275 'eth1=10.10.1.12,10.10.1.13:subnet-999999:sg-1234567:true:My Custom Eth1']
276
277 or
278
279 -network_interfaces => ['eth0=10.10.0.12:subnet-1234567:sg-1234567:true:My Custom Eth0:true']
280
281 The format is '<device>=<specification>'. The device is an ethernet
282 interface name such as eth0, eth1, eth2, etc. The specification has
283 up to five fields, each separated by the ":" character. All fields
284 are optional and can be left blank. If missing, AWS will choose a
285 default.
286
287 10.10.1.12,10.10.1.13:subnet-999999:sg-1234567:true:My Custom Eth1
288
289 1. IP address(es): A single IP address in standard dot form, or a
290 list of IP addresses separated by commas. The first address in the
291 list will become the primary private IP address for the interface.
292 Subsequent addresses will become secondary private addresses. You
293 may specify "auto" or leave the field blank to have AWS choose an
294 address automatically from within the subnetwork. To allocate
295 several secondary IP addresses and have AWS pick the addresses
296 automatically, give the count of secondary addresses you wish to
297 allocate as an integer following the primary IP address. For
298 example, "auto,3" will allocate an automatic primary IP address and
299 three automatic secondary addresses, while "10.10.1.12,3" will
300 force the primary address to be 10.10.1.12 and create three
301 automatic secondary addresses.
302
303 2. Subnetwork ID: The ID of the VPC subnetwork in which the ENI
304 resides. An instance may have several ENIs associated with it, and
305 each ENI may be attached to a different subnetwork.
306
307 3. Security group IDs: A comma-delimited list of the security group
308 IDs to associate with this ENI.
309
310 4. DeleteOnTerminate: True if this ENI should be automatically
311 deleted when the instance terminates.
312
313 5. Description: A human-readable description of the ENI.
314
315 6. Associate Public Address: Indicates whether to assign a public
316 IP address to the ENI on an instance in a VPC. Can only be
317 specified as true when a single network interface of device index 0
318 is created. Defaults to true when launching in a Default VPC.
319
320 As an alternative syntax, you may specify the ID of an existing ENI
321 in lieu of the primary IP address and other fields. The ENI will be
322 attached to the instance if its permissions allow:
323
324 -network_interfaces => 'eth0=eni-123456'
325
326 Return value
327 On success, this method returns a list of VM::EC2::Instance
328 objects. If called in a scalar context AND only one instance was
329 requested, it will return a single instance object (rather than
330 returning a list of size one which is then converted into numeric
331 "1", as would be the usual Perl behavior).
332
333 Note that this behavior is different from the Amazon API, which
334 returns a ReservationSet. In this API, ask the instances for the
335 the reservation, owner, requester, and group information using
336 reservationId(), ownerId(), requesterId() and groups() methods.
337
338 Tips
339 1. If you have a VM::EC2::Image object returned from
340 Describe_images(), you may run it using run_instances():
341
342 my $image = $ec2->describe_images(-image_id => 'ami-12345');
343 $image->run_instances( -min_count => 10,
344 -block_devices => ['/dev/sdb=ephemeral0',
345 '/dev/sdc=:100:true']
346 )
347
348 2. It may take a short while for a newly-launched instance to be
349 returned by describe_instances(). You may need to sleep for 1-2
350 seconds
351 before current_status() returns the correct value.
352
353 3. Each instance object has a current_status() method which will
354 return the current run state of the instance. You may poll this
355 method to wait until the instance is running:
356
357 my $instance = $ec2->run_instances(...);
358 sleep 1;
359 while ($instance->current_status ne 'running') {
360 sleep 5;
361 }
362
363 4. The utility method wait_for_instances() will wait until all
364 passed instances are in the 'running' or other terminal state.
365
366 my @instances = $ec2->run_instances(...);
367 $ec2->wait_for_instances(@instances);
368
369 @s = $ec2->start_instances(@instance_ids)
370 @s = $ec2->start_instances(-instance_id=>\@instance_ids)
371 Start the instances named by @instance_ids and return one or more
372 VM::EC2::Instance::State::Change objects.
373
374 To wait for the all the instance ids to reach their final state
375 ("running" unless an error occurs), call wait_for_instances().
376
377 Example:
378
379 # find all stopped instances
380 @instances = $ec2->describe_instances(-filter=>{'instance-state-name'=>'stopped'});
381
382 # start them
383 $ec2->start_instances(@instances)
384
385 # pause till they are running (or crashed)
386 $ec2->wait_for_instances(@instances)
387
388 You can also start an instance by calling the object's start() method:
389
390 $instances[0]->start('wait'); # start instance and wait for it to
391 # be running
392
393 The objects returned by calling start_instances() indicate the current
394 and previous states of the instance. The previous state is typically
395 "stopped" and the current state is usually "pending." This information
396 is only current to the time that the start_instances() method was
397 called. To get the current run state of the instance, call its
398 status() method:
399
400 die "ouch!" unless $instances[0]->current_status eq 'running';
401
402 @s = $ec2->stop_instances(@instance_ids)
403 @s = $ec2->stop_instances(-instance_id=>\@instance_ids,-force=>1)
404 Stop the instances named by @instance_ids and return one or more
405 VM::EC2::Instance::State::Change objects. In the named parameter
406 version of this method, you may optionally provide a -force argument,
407 which if true, forces the instance to halt without giving it a chance
408 to run its shutdown procedure (the equivalent of pulling a physical
409 machine's plug).
410
411 To wait for instances to reach their final state, call
412 wait_for_instances().
413
414 Example:
415
416 # find all running instances
417 @instances = $ec2->describe_instances(-filter=>{'instance-state-name'=>'running'});
418
419 # stop them immediately and wait for confirmation
420 $ec2->stop_instances(-instance_id=>\@instances,-force=>1);
421 $ec2->wait_for_instances(@instances);
422
423 You can also stop an instance by calling the object's start() method:
424
425 $instances[0]->stop('wait'); # stop first instance and wait for it to
426 # stop completely
427
428 @s = $ec2->terminate_instances(@instance_ids)
429 @s = $ec2->terminate_instances(-instance_id=>\@instance_ids)
430 Terminate the instances named by @instance_ids and return one or more
431 VM::EC2::Instance::State::Change objects. This method will fail for any
432 instances whose termination protection field is set.
433
434 To wait for the all the instances to reach their final state, call
435 wait_for_instances().
436
437 Example:
438
439 # find all instances tagged as "Version 0.5"
440 @instances = $ec2->describe_instances({'tag:Version'=>'0.5'});
441
442 # terminate them
443 $ec2->terminate_instances(@instances);
444
445 You can also terminate an instance by calling its terminate() method:
446
447 $instances[0]->terminate;
448
449 @s = $ec2->reboot_instances(@instance_ids)
450 @s = $ec2->reboot_instances(-instance_id=>\@instance_ids)
451 Reboot the instances named by @instance_ids and return one or more
452 VM::EC2::Instance::State::Change objects.
453
454 To wait for the all the instances to reach their final state, call
455 wait_for_instances().
456
457 You can also reboot an instance by calling its terminate() method:
458
459 $instances[0]->reboot;
460
461 $boolean =
462 $ec2->confirm_product_instance($instance_id,$product_code,$callback)
463 $boolean =
464 $ec2->confirm_product_instance(-instance_id=>$instance_id,-product_code=>$product_code,-cb=>$callback)
465 Return "true" if the instance indicated by $instance_id is associated
466 with the given product code.
467
468 $meta = VM::EC2->instance_metadata
469 $meta = $ec2->instance_metadata
470 For use on running EC2 instances only: This method returns a
471 VM::EC2::Instance::Metadata object that will return information about
472 the currently running instance using the HTTP:// metadata fields
473 described at
474 http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?instancedata-data-categories.html.
475 This is usually fastest way to get runtime information on the current
476 instance.
477
478 Note that this method can be called as either an instance or a class
479 method.
480
481 @data =
482 $ec2->describe_instance_attribute($instance_id,$attribute,$callback)
483 This method returns instance attributes. Only one attribute can be
484 retrieved at a time. The following is the list of attributes that can
485 be retrieved:
486
487 instanceType -- scalar
488 kernel -- scalar
489 ramdisk -- scalar
490 userData -- scalar
491 disableApiTermination -- scalar
492 instanceInitiatedShutdownBehavior -- scalar
493 rootDeviceName -- scalar
494 blockDeviceMapping -- list of hashref
495 sourceDestCheck -- scalar
496 groupSet -- list of scalar
497 productCodes -- list of hashref
498 ebsOptimized -- scalar
499 sriovNetSupport -- scalar
500
501 All of these values can be retrieved more conveniently from the
502 VM::EC2::Instance object returned from describe_instances(), so there
503 is no attempt to parse the results of this call into Perl objects.
504 Therefore, some of the attributes, in particular 'blockDeviceMapping'
505 will be returned as raw hashrefs.
506
507 $boolean =
508 $ec2->modify_instance_attribute($instance_id,-$attribute_name=>$value)
509 This method changes instance attributes. It can only be applied to
510 stopped instances. The following is the list of attributes that can be
511 set:
512
513 -instance_type -- type of instance, e.g. "m1.small"
514 -kernel -- kernel id
515 -ramdisk -- ramdisk id
516 -user_data -- user data
517 -termination_protection -- true to prevent termination from the console
518 -disable_api_termination -- same as the above
519 -shutdown_behavior -- "stop" or "terminate"
520 -instance_initiated_shutdown_behavior -- same as above
521 -root_device_name -- root device name
522 -source_dest_check -- enable NAT (VPC only)
523 -group_id -- VPC security group
524 -block_devices -- Specify block devices to change
525 deleteOnTermination flag
526 -block_device_mapping -- Alias for -block_devices
527 -ebs_optimization -- EBS Optmization
528 -sriov_net_support -- Enhanced networking support
529
530 Only one attribute can be changed in a single request. For example:
531
532 $ec2->modify_instance_attribute('i-12345',-kernel=>'aki-f70657b2');
533
534 The result code is true if the attribute was successfully modified,
535 false otherwise. In the latter case, $ec2->error() will provide the
536 error message.
537
538 The ability to change the deleteOnTermination flag for attached block
539 devices is not documented in the official Amazon API documentation, but
540 appears to work. The syntax is:
541
542 # turn on deleteOnTermination
543 $ec2->modify_instance_attribute(-block_devices=>'/dev/sdf=v-12345') #
544 turn off deleteOnTermination
545 $ec2->modify_instance_attribute(-block_devices=>'/dev/sdf=v-12345')
546
547 The syntax is slightly different from what is used by -block_devices in
548 run_instances(), and is "device=volumeId:boolean". Multiple block
549 devices can be specified using an arrayref.
550
551 $boolean = $ec2->reset_instance_attribute($instance_id,$attribute
552 [,$callback])
553 This method resets an attribute of the given instance to its default
554 value. Valid attributes are "kernel", "ramdisk" and "sourceDestCheck".
555 The result code is true if the reset was successful.
556
557 @status_list = $ec2->describe_instance_status(@instance_ids);
558 @status_list =
559 $ec2->describe_instance_status(-instance_id=>\@ids,-filter=>\%filters,%other_args);
560 @status_list = $ec2->describe_instance_status(\%filters);
561 This method returns a list of VM::EC2::Instance::Status objects
562 corresponding to status checks and scheduled maintenance events on the
563 instances of interest. You may provide a list of instances to return
564 information on, a set of filters, or both.
565
566 The filters are described at
567 http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceStatus.html.
568 The brief list is:
569
570 availability-zone, event.code, event.description, event.not-after,
571 event.not-before, instance-state-name, instance-state-code,
572 system-status.status, system-status.reachability,
573 instance-status.status, instance-status.reachability.
574
575 Request arguments are:
576
577 -instance_id Scalar or array ref containing the instance ID(s) to return
578 information about (optional).
579
580 -filter Filters to apply (optional).
581
582 -include_all_instances If true, include all instances, including those that are
583 stopped, pending and shutting down. Otherwise, returns
584 the status of running instances only.
585
586 -max_results An integer corresponding to the number of instance items
587 per response (must be greater than 5).
588
589 If -max_results is specified, then the call will return at most the
590 number of instances you requested. You may see whether there are
591 additional results by calling more_instance_status(), and then retrieve
592 the next set of results with additional call(s) to
593 describe_instance_status():
594
595 my @results = $ec2->describe_instance_status(-max_results => 10);
596 do_something(\@results);
597 while ($ec2->more_instance_status) {
598 @results = $ec2->describe_instance_status;
599 do_something(\@results);
600 }
601
602 NOTE: As of 29 July 2012, passing -include_all_instances causes an EC2
603 "unknown parameter" error, indicating some mismatch between the
604 documented API and the actual one.
605
606 $t = $ec2->token
607 Return a client token for use with start_instances().
608
609 $ec2->wait_for_instances(@instances)
610 Wait for all members of the provided list of instances to reach some
611 terminal state ("running", "stopped" or "terminated"), and then return
612 a hash reference that maps each instance ID to its final state.
613
614 Typical usage:
615
616 my @instances = $image->run_instances(-key_name =>'My_key',
617 -security_group=>'default',
618 -min_count =>2,
619 -instance_type => 't1.micro')
620 or die $ec2->error_str;
621 my $status = $ec2->wait_for_instances(@instances);
622 my @failed = grep {$status->{$_} ne 'running'} @instances;
623 print "The following failed: @failed\n";
624
625 If no terminal state is reached within a set timeout, then this method
626 returns undef and sets $ec2->error_str() to a suitable message. The
627 timeout, which defaults to 10 minutes (600 seconds), can be get or set
628 with $ec2->wait_for_timeout().
629
631 VM::EC2
632
634 Lincoln Stein <lincoln.stein@gmail.com>.
635
636 Copyright (c) 2011 Ontario Institute for Cancer Research
637
638 This package and its accompanying libraries is free software; you can
639 redistribute it and/or modify it under the terms of the GPL (either
640 version 1, or at your option, any later version) or the Artistic
641 License 2.0. Refer to LICENSE for the full license text. In addition,
642 please see DISCLAIMER.txt for disclaimers of warranty.
643
644
645
646perl v5.32.1 2021-01-27 VM::EC2::REST::instance(3)