VM::EC...nstance(3pm)
π NAME π
VM::EC2::REST::instance β bestie, this is the part of VM::EC2 that deals with instances. You know, the actual little computers. Controlling them. All of it. This is the VM::EC2::REST::instance manual page, straight from the User Contributed Perl Documentation collection. π«Ά
β¨ SYNOPSIS β¨
use VM::EC2 ':standard';
That's literally it. Pull in the standard stuff and you're off. π
π METHODS π
Okay so here's the vibe: the methods in this section let you grab info about your EC2 instances, launch brand new ones, control their whole lifecycle (like starting and stopping them, the classic), and fetch the console output from them. Basically everything you'd want to do to an instance, short of buying it a lil snack. π
Implemented: β¨
ConfirmProductInstanceDescribeInstanceAttributeDescribeInstancesDescribeInstanceStatusModifyInstanceAttributeRebootInstancesResetInstanceAttributeRunInstancesStartInstancesStopInstancesTerminateInstances
Unimplemented: π
- (none)
Not a single one missing, we ate. π
The primary object these methods are out here manipulating is VM::EC2::Instance. So if you want the extra stuff β attaching and detaching volumes, tweaking an instance's attributes, turning instances into images β go read the VM::EC2::Instance manual page, because that's where all that lives. This page is about the rest of it. π
π @instances = $ec2->describe_instances(@instance_ids)
π @instances = $ec2->describe_instances(\%filters)
π @instances = $ec2->describe_instances(-instance_id=>\@ids,-filter=>\%filters)
@instances = $ec2->describe_instances(@instance_ids)
@instances = $ec2->describe_instances(\%filters)
@instances = $ec2->describe_instances(-instance_id=>\@ids,-filter=>\%filters)
This hands you back a whole series of VM::EC2::Instance objects. The optional arguments are:
-instance_idβ the ID(s) of the instance(s) you want info on. This can be a plain string scalar, or an arrayref if you're feeling greedy. π«Ά-filterβ tags and other filters to apply.
The -filter argument is a hashreference, where the keys are the filter names and the values are the match strings. Some filters accept wildcards. β¨
A typical filter example, bestie:
$ec2->describe_instances(
-filter => {'block-device-mapping.device-name'=>'/dev/sdh',
'architecture' => 'i386',
'tag:Role' => 'Server'
});
And if there are no other arguments hanging around, you can just drop the -filter argument name entirely:
$ec2->describe_instances({'block-device-mapping.device-name'=>'/dev/sdh',
'architecture' => 'i386',
'tag:Role' => 'Server'});
There are a large number of filters, and the full list lives at http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html.
Here's the alpha-sorted list of filter names:
architecture, availability-zone, block-device-mapping.attach-time,
block-device-mapping.delete-on-termination,
block-device-mapping.device-name, block-device-mapping.status,
block-device-mapping.volume-id, client-token, dns-name, group-id, group-name,
hypervisor, image-id, instance-id, instance-lifecycle, instance-state-code,
instance-state-name, instance-type, instance.group-id, instance.group-name,
ip-address, kernel-id, key-name, launch-index, launch-time, monitoring-state,
owner-id, placement-group-name, platform, private-dns-name,
private-ip-address, product-code, ramdisk-id, reason, requester-id,
reservation-id, root-device-name, root-device-type, source-dest-check,
spot-instance-request-id, state-reason-code, state-reason-message, subnet-id,
tag-key, tag-value, tag:key, virtualization-type, vpc-id.
Heads up bestie, this one actually matters: the objects you get back from this method are the instances themselves, not a reservation set. If you want the reservation ID, call each instance's reservationId() method and grab it from there. π§
π¦ @i = $ec2->run_instances($ami_id)
π¦ @i = $ec2->run_instances(-image_id=>$id,%other_args)
@i = $ec2->run_instances($ami_id)
@i = $ec2->run_instances(-image_id=>$id,%other_args)
This is the glow-up moment: it provisions and launches one or more instances from an AMI ID. If it works, you get a series of VM::EC2::Instance objects back. πΈ
If you call it with a single argument, that argument is interpreted as the AMI to launch, and every other argument just takes its default. Otherwise, the arguments get read as a -parameter=>$argument list. Simple as.
Required arguments: (no skipping, bestie)
-image_idβ ID of an AMI to launch.
Optional arguments:
-min_countβ Minimum number of instances to launch[1].-max_countβ Maximum number of instances to launch[1].-key_nameβ Name of the keypair to use.-security_group_idβ Security group ID to use for this instance. Use an arrayref if you've got multiple group IDs.-security_groupβ Security group name to use for this instance. Use an arrayref if you've got multiple values.-user_dataβ User data to pass to the instances. Do NOT base64 encode this yourself, okay? It gets done for you. π-instance_typeβ Type of the instance to use. There's a list further down.-availability_zoneβ The availability zone you want to launch the instance into. Call$ec2->regionsif you want the list.-zoneβ Short version of-availability_aone.-placement_zoneβ Deprecated version of-availability_zone. β οΈ-placement_groupβ An existing placement group to launch the instance into. Applicable to cluster instances only.-tenancyβ Specify'dedicated'to launch the instance on a dedicated server. Only applicable for VPC instances.-kernel_idβ ID of the kernel to use for the instances, overriding the kernel specified in the image.-ramdisk_idβ ID of the ramdisk to use for the instances, overriding the ramdisk specified in the image.-block_devicesβ Specify block devices to map onto the instances, overriding the values specified in the image. The syntax for this argument is further down. π-block_device_mappingβ Alias for-block_devices.-monitoringβ Pass a true value to enable detailed monitoring. π-subnet_idβ ID of the subnet to launch the instance into. Only applicable for VPC instances.-termination_protectionβ Pass true to lock the instance so it can't be terminated through the API. Usemodify_instance()to unset this if youu wish to terminate the instance later.-disable_api_terminationβ Same as above.-shutdown_behaviorβ Pass"stop"(the default) to stop the instance and save its disk state when"shutdown"is called from inside the instance. Stopped instances can be restarted later. Pass"terminate"to instead terminate the instance and completely discard its state. π-instance_initiated_shutdown_behaviorβ Same as above.-private_ip_addressβ Assign the instance to a specific IP address from a VPC subnet (VPC only).-client_tokenβ A unique identifier you can provide to ensure idempotency of the request. You can use$ec2->token()to generate a suitable identifier. Seehttp://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html.-network_interfacesβ A single network interface specification string, or a list of them as an array reference (VPC only). These get described in more detail below.-iam_arnβ The Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instances.-iam_nameβ The name of the IAM instance profile (IIP) to associate with the instances.-ebs_optimizedβ Boolean. If true, create an EBS-optimized instance (valid only for certain instance types).
β Instance types β
Here's the list of instance types Amazon currently allows:
m1.small c1.medium m2.xlarge cc1.4xlarge cg1.4xlarge t1.micro
m1.large c1.xlarge m2.2xlarge
m1.xlarge m2.4xlarge
π Block device syntax π
The syntax of -block_devices is identical to what the ec2-run-instances command-line tool uses. Borrowing straight from that tool's manual page:
The format is '<device>=<block-device>', where 'block-device' can be one of the following:
'none': indicates that a block device that would be exposed at the specified device should be suppressed. For example:'/dev/sdb=none''ephemeral[0-3]': indicates that the Amazon EC2 ephemeral store (instance local storage) should be exposed at the specified device. For example:'/dev/sdc=ephemeral0'.'vol-12345678': A volume ID will attempt to attach the given volume to the instance, contingent on volume state and availability zone.'none': Suppress this block device, even if it is mapped in the AMI.'[<snapshot-id>][:<size>[:<delete-on-termination>[:<volume-type>[:<iops>]]]]': indicates that an Amazon EBS volume, created from the specified Amazon EBS snapshot, should be exposed at the specified device. The following combinations are supported:'<snapshot-id>': the ID of an Amazon EBS snapshot, which must be owned by or restorable by the caller. May be left out if a<size>is specified, creating an empty Amazon EBS volume of the specified size.'<size>': the size (GiBs) of the Amazon EBS volume to be created. If a snapshot was specified, this may not be smaller than the size of the snapshot itself.'<delete-on-termination>': indicates whether the Amazon EBS volume should be deleted on instance termination. If not specified, this will default to'true'and the volume will be deleted.'<volume-type>': The volume type. One of"standard","gp2"or"io1"."gp2"is the new general purpose SSD type.'<iops>': The number of I/O operations per second (IOPS) that the volume supports. A number between100to4000. Only valid for volumes of type"io1".
Examples, bestie β bookmark these:
-block_devices => '/dev/sdb=snap-7eb96d16'
-block_devices => '/dev/sdc=snap-7eb96d16:80:false'
-block_devices => '/dev/sdd=:120'
-block_devices => '/dev/sdc=:120:true:io1:500'
To provide multiple mappings, use an array reference. In this example, we launch two 'm1.small' instance in which /dev/sdb is mapped to ephemeral storage and /dev/sdc is mapped to a new 100 G EBS volume:
@i=$ec2->run_instances(-image_id => 'ami-12345',
-min_count => 2,
-block_devices => ['/dev/sdb=ephemeral0',
'/dev/sdc=:100:true']
)
π¦ Network interface syntax π¦
Every instance gets one primary network interface and a private IP address, and Amazon usually just hands those out automatically, no input needed from you. But when you're running VPC instances, bestie, you get to add extra elastic network interfaces (ENIs) to the instance AND tack secondary private IP addresses onto one or more of those ENIs. π
ENIs can exist independently of instances, and they can be detached and reattached pretty much the same way you'd do with EBS volumes. The whole thing is explained in detail at http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/using-instance-addressing.html.
You specify the network configuration with the -network_interface parameter:
-network_interfaces => ['eth0=10.10.0.12:subnet-1234567:sg-1234567:true:My Custom Eth0',
'eth1=10.10.1.12,10.10.1.13:subnet-999999:sg-1234567:true:My Custom Eth1']
or
-network_interfaces => ['eth0=10.10.0.12:subnet-1234567:sg-1234567:true:My Custom Eth0:true']
The format is '<device>=<specification>'. The device is an ethernet interface name like eth0, eth1, eth2, etc. The specification has up to five fields, each separated by the ":" character. All fields are optional and can be left blank. If missing, AWS will choose a default.
10.10.1.12,10.10.1.13:subnet-999999:sg-1234567:true:My Custom Eth1
- IP address(es): A single IP address in standard dot form, or a list of IP addresses separated by commas. The first address in the list becomes the primary private IP address for the interface. Everything after that becomes a secondary private address. You may specify
"auto"or leave the field blank to have AWS choose an address automatically from within the subnetwork. π To allocate several secondary IP addresses and have AWS pick them automatically, give the count of secondary addresses you want as an integer following the primary IP address. So like,"auto,3"will allocate an automatic primary IP address plus three automatic secondary addresses, while"10.10.1.12,3"forces the primary address to be10.10.1.12and creates three automatic secondary addresses. Slay. - Subnetwork ID: The ID of the VPC subnetwork in which the ENI resides. An instance may have several ENIs associated with it, and each ENI may be attached to a different subnetwork.
- Security group IDs: A comma-delimited list of the security group IDs to associate with this ENI.
- DeleteOnTerminate: True if this ENI should be automatically deleted when the instance terminates.
- Description: A human-readable description of the ENI.
- Associate Public Address: Indicates whether to assign a public IP address to the ENI on an instance in a VPC. Can only be specified as
truewhen a single network interface of device index 0 is created. Defaults totruewhen launching in a Default VPC.
As an alternative syntax, you may specify the ID of an existing ENI in lieu of the primary IP address and other fields. The ENI will be attached to the instance if its permissions allow:
-network_interfaces => 'eth0=eni-123456'
π Return value π
On success, this method returns a list of VM::EC2::Instance objects. If called in a scalar context AND only one instance was requested, it will return a single instance object β rather than returning a list of size one which then gets converted into numeric 1, like normal Perl would do. π
Heads up bestie: this behavior is different from the Amazon API, which returns aReservationSet. In this API, ask the instances for the the reservation, owner, requester, and group information usingreservationId(),ownerId(),requesterId()andgroups()methods. iykyk π
β Tips β
- If you have a
VM::EC2::Imageobject returned fromDescribe_images(), you may run it usingrun_instances():
my $image = $ec2->describe_images(-image_id => 'ami-12345');
$image->run_instances( -min_count => 10,
-block_devices => ['/dev/sdb=ephemeral0',
'/dev/sdc=:100:true']
)
- It may take a short while for a newly-launched instance to be returned by
describe_instances(). You may need to sleep for 1-2 seconds beforecurrent_status()returns the correct value. π΄ - Each instance object has a
current_status()method which returns the current run state of the instance. You may poll this method to wait until the instance is running:
my $instance = $ec2->run_instances(...);
sleep 1;
while ($instance->current_status ne 'running') {
sleep 5;
}
- The utility method
wait_for_instances()will wait until all passed instances are in the'running'or other terminal state.
my @instances = $ec2->run_instances(...);
$ec2->wait_for_instances(@instances);
π₯ @s = $ec2->start_instances(@instance_ids) π₯
π₯ @s = $ec2->start_instances(-instance_id=>\@instance_ids) π₯
Start the instances named by @instance_ids and return one or more VM::EC2::Instance::State::Change objects. π
To wait for the all the instance ids to reach their final state ("running" unless an error occurs), call wait_for_instances().
Example:
# find all stopped instances
@instances = $ec2->describe_instances(-filter=>{'instance-state-name'=>'stopped'});
# start them
$ec2->start_instances(@instances)
# pause till they are running (or crashed)
$ec2->wait_for_instances(@instances)
You can also start an instance by calling the object's start() method:
$instances[0]->start('wait'); # start instance and wait for it to
# be running
The objects returned by calling start_instances() indicate the current and previous states of the instance. The previous state is typically "stopped" and the current state is usually "pending." This information is only current to the time that the start_instances() method was called. To get the current run state of the instance, call its status() method:
die "ouch!" unless $instances[0]->current_status eq 'running';
π @s = $ec2->stop_instances(@instance_ids) π
π @s = $ec2->stop_instances(-instance_id=>\@instance_ids,-force=>1) π
Stop the instances named by @instance_ids and return one or more VM::EC2::Instance::State::Change objects. In the named parameter version of this method, you may optionally provide a -force argument, which if true, forces the instance to halt without giving it a chance to run its shutdown procedure β the equivalent of pulling a physical machine's plug. π±
That's the plug-pull one, bestie. Dramatic and irreversible-feeling. Use it with intention.
To wait for instances to reach their final state, call wait_for_instances().
Example:
# find all running instances
@instances = $ec2->describe_instances(-filter=>{'instance-state-name'=>'running'});
# stop them immediately and wait for confirmation
$ec2->stop_instances(-instance_id=>\@instances,-force=>1);
$ec2->wait_for_instances(@instances);
You can also stop an instance by calling the object's start() method:
$instances[0]->stop('wait'); # stop first instance and wait for it to
# stop completely
π @s = $ec2->terminate_instances(@instance_ids) π
π @s = $ec2->terminate_instances(-instance_id=>\@instance_ids) π
Terminate the instances named by @instance_ids and return one or more VM::EC2::Instance::State::Change objects. This method will fail for any instances whose termination protection field is set. π
To wait for the all the instances to reach their final state, call wait_for_instances().
Example:
# find all instances tagged as "Version 0.5"
@instances = $ec2->describe_instances({'tag:Version'=>'0.5'});
# terminate them
$ec2->terminate_instances(@instances);
You can also terminate an instance by calling its terminate() method:
$instances[0]->terminate;
π«Ά @s = $ec2->reboot_instances(@instance_ids) π«Ά
π«Ά @s = $ec2->reboot_instances(-instance_id=>\@instance_ids) π«Ά
Reboot the instances named by @instance_ids and return one or more VM::EC2::Instance::State::Change objects. π
To wait for the all the instances to reach their final state, call wait_for_instances().
You can also reboot an instance by calling its terminate() method:
$instances[0]->reboot;
πΈ $boolean = $ec2->confirm_product_instance($instance_id,$product_code,$callback) πΈ
πΈ $boolean = $ec2->confirm_product_instance(-instance_id=>$instance_id,-product_code=>$product_code,-cb=>$callback) πΈ
Return "true" if the instance indicated by $instance_id is associated with the given product code. β
π§ $meta = VM::EC2->instance_metadata π§
π§ $meta = $ec2->instance_metadata π§
For use on running EC2 instances only: This method returns a VM::EC2::Instance::Metadata object that will return information about the currently running instance using the HTTP:// metadata fields described at http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?instancedata-data-categories.html. This is usually the fastest way to get runtime information on the current instance. β‘
Note: this method can be called as either an instance or a class method.
π @data = $ec2->describe_instance_attribute($instance_id,$attribute,$callback) π
This method returns instance attributes. Only one attribute can be retrieved at a time. Here's the list of attributes you can retrieve:
instanceTypeβ scalarkernelβ scalarramdiskβ scalaruserDataβ scalardisableApiTerminationβ scalarinstanceInitiatedShutdownBehaviorβ scalarrootDeviceNameβ scalarblockDeviceMappingβ list of hashrefsourceDestCheckβ scalargroupSetβ list of scalarproductCodesβ list of hashrefebsOptimizedβ scalarsriovNetSupportβ scalar
Okay so real quick, before we get into the rest: every single one of these values is way easier to grab off the VM::EC2::Instance object you get back from describe_instances() π«Ά. This call makes zero attempt to parse its results into Perl objects for you, so a couple of the attributes β 'blockDeviceMapping' being the main character here π β come back as raw hashrefs. That's just the vibe, bestie.
$boolean = $ec2->modify_instance_attribute($instance_id,-$attribute_name=>$value)
This one β¨changesβ¨ instance attributes. Big caveat tho: it can only be applied to stopped instances. Not running. Stopped. Periodt π
Here's the whole list of attributes you're allowed to set:
-instance_typeβ type of instance, e.g."m1.small"-kernelβ kernel id-ramdiskβ ramdisk id-user_dataβ user data-termination_protectionβ true to prevent termination from the console-disable_api_terminationβ same as the above-shutdown_behaviorβ"stop"or"terminate"-instance_initiated_shutdown_behaviorβ same as above-root_device_nameβ root device name-source_dest_checkβ enable NAT (VPC only)-group_idβ VPC security group-block_devicesβ Specify block devices to changedeleteOnTerminationflag-block_device_mappingβ Alias for-block_devices-ebs_optimizationβ EBS Optimization-sriov_net_supportβ Enhanced networking support
Only one attribute can be changed in a single request. One. Singular. No multitasking π«
Like so:
$ec2->modify_instance_attribute('i-12345',-kernel=>'aki-f70657b2');
The result code comes back true if the attribute was successfully modified, and false otherwise π. In that second case, $ec2->error() will hand you the error message.
Okay so this next bit is lowkey iconic: the ability to change the deleteOnTermination flag for attached block devices is not documented in the official Amazon API documentation, but it appears to work. The syntax is:
# turn on deleteOnTermination
$ec2->modify_instance_attribute(-block_devices=>'/dev/sdf=v-12345')
# turn off deleteOnTermination
$ec2->modify_instance_attribute(-block_devices=>'/dev/sdf=v-12345')
The syntax is slightly different from what's used by -block_devices in run_instances(), and it goes "device=volumeId:boolean". You can specify multiple block devices with an arrayref π
$boolean = $ec2->reset_instance_attribute($instance_id,$attribute [,$callback])
This one resets an attribute of the given instance back to its default value, bestie. Valid attributes are "kernel", "ramdisk" and "sourceDestCheck" β¨ The result code is true if the reset was successful.
@status_list = $ec2->describe_instance_status(@instance_ids);
@status_list = $ec2->describe_instance_status(-instance_id=>@ids,-filter=>%filters,%other_args);
@status_list = $ec2->describe_instance_status(%filters);
This method returns a list of VM::EC2::Instance::Status objects corresponding to status checks and scheduled maintenance events on the instances you care about π¦. You can hand it a list of instances to return info on, a set of filters, or both. Your call, queen.
The filters are described at http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstanceStatus.html
The brief list is:
availability-zone, event.code, event.description, event.not-after, event.not-before, instance-state-name, instance-state-code, system-status.status, system-status.reachability, instance-status.status, instance-status.reachability.
Request arguments are:
-instance_idβ Scalar or array ref containing the instance ID(s) to return information about (optional).-filterβ Filters to apply (optional).-include_all_instancesβ If true, include all instances, including those that are stopped, pending and shutting down. Otherwise, returns the status of running instances only.-max_resultsβ An integer corresponding to the number of instance items per response (must be greater than 5).
If -max_results is specified, then the call will return at most the number of instances you requested. You can peek at whether there are additional results by calling more_instance_status(), and then grab the next set of results with additional call(s) to describe_instance_status():
my @results = $ec2->describe_instance_status(-max_results => 10);
do_something(\@results);
while ($ec2->more_instance_status) {
@results = $ec2->describe_instance_status;
do_something(\@results);
}
NOTE: As of 29 July 2012, passing-include_all_instancescauses an EC2"unknown parameter"error, indicating some mismatch between the documented API and the actual one. π So like, documented β real. Classic.
$t = $ec2->token
Return a client token for use with start_instances() ποΈ
$ec2->wait_for_instances(@instances)
Wait for all members of the provided list of instances to reach some terminal state β "running", "stopped" or "terminated" β and then return a hash reference that maps each instance ID to its final state π
Typical usage:
my @instances = $image->run_instances(-key_name =>'My_key',
-security_group=>'default',
-min_count =>2,
-instance_type => 't1.micro')
or die $ec2->error_str;
my $status = $ec2->wait_for_instances(@instances);
my @failed = grep {$status->{$_} ne 'running'} @instances;
print "The following failed: @failed\n";
If no terminal state is reached within a set timeout, then this method returns undef and sets $ec2->error_str() to a suitable message π The timeout defaults to 10 minutes (600 seconds), and you can get or set it with $ec2->wait_for_timeout().
π SEE ALSO π
VM::EC2
π AUTHOR π
Lincoln Stein <lincoln.stein@gmail.com>.
Copyright (c) 2011 Ontario Institute for Cancer Research
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. π
And that's the whole page, bestie!! π«Ά This cutie was documented by the Perl gods themselves (perl v5.38.2), stamped 2024-08-10, and it lives under the name VM::EC...nstance(3pm). Go forth and instance, you absolute icon πβ¨
π¦ where this page comes from
- debian trixie: libvm-ec2-perl 1.28-5 Β· Artistic-2.0 OR GPL-1.0-or-later
- ubuntu resolute: libvm-ec2-perl 1.28-5 Β· Artistic-2.0 OR GPL-1.0-or-later
- ubuntu stonking: libvm-ec2-perl 1.28-5 Β· Artistic-2.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms