VM::EC...nstance(3pm)
π NAME π
okay so bestie, this is VM::EC2::Instance(3pm) β the manual page for VM::EC2::Instance, which is an object describing an Amazon EC2 instance. β¨ (part 1 of 2, more coming, iykyk π
)
π¦ SYNOPSIS π¦
use VM::EC2;
$ec2 = VM::EC2->new(...);
$instance = $ec2->describe_instances(-instance_id=>'i-12345');
$instanceId = $instance->instanceId;
$ownerId = $instance->ownerId;
$reservationId = $instance->reservationId;
$imageId = $instance->imageId;
$state = $instance->instanceState;
@groups = $instance->groups;
$private_ip = $instance->privateIpAddress;
$public_ip = $instance->ipAddress;
$private_dns = $instance->privateDnsName;
$public_dns = $instance->dnsName;
$time = $instance->launchTime;
$status = $instance->current_status;
$tags = $instance->tags;
$stateChange = $instance->start();
$stateChange = $instance->stop();
$stateChange = $instance->reboot();
$stateChange = $instance->terminate();
$seconds = $instance->up_time;
πΈ DESCRIPTION πΈ
This object represents an Amazon EC2 instance, and is returned by VM::EC2->describe_instances(). In addition to methods to query the instance's attributes, there are methods that allow you to manage the instance's lifecycle, including start, stopping, and terminating it. π
Note that the information about security groups and reservations that is returned by describe_instances() is copied into each instance before returning it, so there is no concept of a "reservation set" in this interface. π«Ά
π METHODS π
These object methods are supported, bestie: β¨
instanceIdβ ID of this instance. πimageIdβ ID of the image used to launch this instance. πΌοΈinstanceStateβ The current state of the instance at the time thatdescribe_instances()was called, as aVM::EC2::Instance::Stateobject. Also see thestatus()method, which re-queries EC2 for the current state of the instance. States are represented in strings as"terminated","running","stopped","stopping", and"shutting-down". πprivateDnsNameβ The private DNS name assigned to the instance within Amazon's EC2 network. This element is defined only for running instances. πdnsNameβ The public DNS name assigned to the instance, defined only for running instances. πreasonβ Reason for the most recent state transition, if applicable. π€keyNameβ Name of the associated key pair, if applicable. πkeyPairβ TheVM::EC2::KeyPairobject, derived from thekeyName. πamiLaunchIndexβ The AMI launch index, which can be used to find this instance within the launch group. π’productCodesβ A list of product codes that apply to this instance. π·οΈinstanceTypeβ The instance type, such as"t1.micro". CHANGEABLE. πͺlaunchTimeβ The time the instance launched. β°placementβ The placement of the instance. Returns aVM::EC2::Instance::Placementobject, which when used as a string is equal to the instance's availability zone. πavailabilityZoneβ Same asplacement. πkernelIdβ ID of the instance's kernel. CHANGEABLE. π§ramdiskIdβ ID of the instance's RAM disk. CHANGEABLE. πΎplatformβ Platform of the instance, either"windows"or empty. πͺmonitoringβ State of monitoring for the instance. One of"disabled","enabled", or"pending". CHANGEABLE: pass true or"enabled"to turn on monitoring. Pass false or"disabled"to turn it off. πsubnetIdβ The Amazon VPC subnet ID in which the instance is running, for Virtual Private Cloud instances only. πΈοΈvpcIdβ The Virtual Private Cloud ID for VPC instances. βοΈprivateIpAddressβ The private (internal Amazon) IP address assigned to the instance. πipAddressβ The public IP address of the instance. πsourceDestCheckβ Whether source destination checking is enabled on this instance. This returns a Perl boolean rather than the string"true". This method is used in conjunction with VPC NAT functionality. See the Amazon VPC User Guide for details. CHANGEABLE. βnetworkInterfaceSetβ Return list ofVM::EC2::ElasticNetworkInterfaceobjects attached to this instance. πiamInstanceProfileβ The IAM instance profile (IIP) associated with this instance. πͺͺebsOptimizedβ True if instance is optimized for EBS I/O. β‘groupSetβ List ofVM::EC2::Groupobjects indicating the VPC security groups in which this instance resides. Not to be confused withgroups(), which returns the security groups of non-VPC instances. π‘οΈstateReasonβ AVM::EC2::Instance::State::Reasonobject which indicates the reason for the instance's most recent state change. Seehttp://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-StateReasonType.html. π§architectureβ The architecture of the image. Either"i386"or"x86_64". ποΈrootDeviceTypeβ The type of the root device used by the instance. One of"ebs"or"instance-store". π½rootDeviceNameβ The name of the the device used by the instance, such as/dev/sda1. CHANGEABLE. πblockDeviceMappingβ The block device mappings for the instance, represented as a list ofVM::EC2::BlockDevice::Mappingobjects. πΊοΈinstanceLifeCycleβ"spot"if this instance is a spot instance, otherwise empty. π―spotInstanceRequestIdβ The ID of the spot instance request, if applicable. πvirtualizationTypeβ Either"paravirtual"or"hvm". π§¬clientTokenβ The idempotency token provided at the time of the AMI launch, if any. ποΈhypervisorβ The instance's hypervisor type, either"ovm"or"xen". π₯οΈuserDataβ User data passed to instance at launch. CHANGEABLE. πdisableApiTerminationβ True if the instance is protected from termination via the console or command-line APIs. CHANGEABLE. πinstanceInitiatedShutdownBehaviorβ Action to take when the instance calls shutdown or halt. One of"stop"or"terminate". CHANGEABLE. π¦sriovNetSupportβ Specifies whether enhanced networking is enabled."simple"if so. πtagSetβ Tags for the instance as a hashref. CHANGEABLE viaadd_tags()anddelete_tags(). π·οΈ
The object also supports the tags() method described in VM::EC2::Generic:
print "ready for production\n" if $image->tags->{Released};
All methods return read-only values except for those marked CHANGEABLE in the list above. For these, you can change the instance attribute on stopped instances by invoking the method with an appropriate new value. For example, to change the instance type from "t1.micro" to "m1.small", you can do this:
my @tiny_instances = $ec2->describe_instances(-filter=>{'instance-type'=>'t1.micro'});
for my $i (@tiny_instances) {
next unless $i->instanceState eq 'stopped';
$i->instanceType('m1.small') or die $ec2->error;
}
When you attempt to change an attribute of an instance, the method will return true on success, false on failure. On failure, the detailed error messages can be recovered from the VM::EC2 object's error() method. π
π« LIFECYCLE METHODS π«
bestie, this is the good stuff. These are the little convenience functions that let you boss your instance around β start it, stop it, reboot it, refresh it, all of it. No cap, these are the ones you'll actually use every day. β¨
$state = $instance->current_statusβ asks AWS what's actually going on with the instance right now and hands you back aVM::EC2::Instance::Stateobject. Which means you can just... poll it until it does what you want:
while ($instance->current_status eq 'pending') { sleep 5 }
$state = $instance->current_stateβ literally just an alias forcurrent_status(). Same vibe, different name, both iconic π$state_change = $instance->start([$wait])β starts the current instance and gives you back aVM::EC2::Instance::State::Changeobject so you can stalk its status. By default it returns right away, but if you pass a true value as the argument, it'll pause execution until the instance is in the"running"state. So patient. So demure.
Here's the polling version:
$state = $instance->start;
while ($state->status eq 'pending') { sleep 5 }
And here's the one that just waits it out:
$instance->start(1);
π¨ If you try to start an instance that's already running, or one that's mid-transition, it will throw a fatal error. Not me finding that out the hard way π
$state_change = $instance->stop([$wait])β same energy asstart(), except it stops a running instance. π$state_change = $instance->terminate([$wait])β also likestart(), except this one terminates the instance. π It can only be called on instances that are either"running"or"stopped".$state_change = $instance->reboot()β reboots the instance. Heads up though: the reboot does not happen immediately β the request gets queued by the Amazon system and might not be satisfied until several minutes later. That's why there's no"wait"argument here, bestie. There's nothing to wait on. π$seconds = $instance->up_time()β how many seconds since the instance was launched. Note that this includes time the instance spent in either the"running"or the"stopped"state. β±οΈ$result = $instance->associate_address($elastic_address)β associates an elastic address with this instance. If you're associating a VPC elastic IP, the result code will indicate theassociationId. Otherwise it's a plain perl truth value ("1") if it worked, andundefif it didn't.
For an ordinary EC2 Elastic IP address, the first argument can be either a plain string (xx.xx.xx.xx format) or a VM::EC2::ElasticAddress object. BUT β if it's a VPC elastic IP address, then the argument must be a VM::EC2::ElasticAddress as returned by describe_addresses(). Why? Because the allocationId has to be pulled out of the object to use in the call. iykyk π«Ά
$bool = $instance->disassociate_addressβ disassociates an elastic IP address from this instance, if there is one. The result is true if the disassociation worked.
β οΈ For a short period of time β up to a few minutes β after disassociation, the instance will have no public IP address and will be completely unreachable from the internet. Plan accordingly, queen π
@list = $instance->network_interfacesβ returns the network interfaces attached to this instance as a set ofVM::EC2::NetworkInterfaceobjects. (VPC only!) π$instance->refreshβ refreshes the object from AWS, updating all the values to their current ones. Super handy to call right after starting an instance so you can grab its IP address. And good news:refresh()gets called automatically for you if you callstart(),stop()orterminate()with a true$waitargument. convenient era β¨$text = $instance->console_outputβ returns the console output of the instance as aVM::EC2::ConsoleOutputobject. That object can be treated like a string, or like an object with methods. π
π¨ CREATING IMAGES π¨
The create_image() method is your handy little shortcut for creating and registering an AMI based on the current state of the instance. Every block device that's currently associated will get snapshotted and attached to the image. Iconic.
Fair warning: this operation can take a long time to finish. You can follow along by calling the returned image object's current_status() method. Patience, bestie π§
create_image($name [,$description])
$imageId = $instance->create_image($name [,$description])
create_image(name,description,no_reboot)
$imageId =
$instance->create_image(-name=>$name,-description=>$description,-no_reboot=>$boolean)
Creates an image from this instance and returns a VM::EC2::Image object. The instance must be in the "stopped" or "running" state. If it's running, Amazon will stop the instance, create the image, and then restart it β unless you pass the -no_reboot argument. π
Arguments:
-nameβ Name for the image that will be created. (required)-descriptionβ Description of the new image.-no_rebootβ If true, don't reboot the instance.
And in the unnamed argument version, you can just provide the name and, optionally, the description of the resulting image. easy peasy π
$boolean = $instance->confirm_product_code($product_code)β returns true if this instance is associated with the given product code. β
πΎ VOLUME MANAGEMENT πΎ
$attachment = $instance->attach_volume($volume_id,$device)
$attachment =
$instance->attach_volume(-volume_id=>$volume_id,-device=>$device)
Attaches volume $volume_id to this instance using virtual device $device. Both arguments are required. The result is a VM::EC2::BlockDevice::Attachment object, which you can monitor by calling current_status():
my $a = $instance->attach_volume('vol-12345'=>'/dev/sdg');
while ($a->current_status ne 'attached') {
sleep 2;
}
print "volume is ready to go\n";
volume is ready to go indeed π
$attachment = $instance->detach_volume($vol_or_device)
$attachment = $instance->detach_volume(-volume_id => $volume_id -device
=> $device, -force => $force);
Detaches the specified volume. In the single-argument form, you can hand over either a volume or a device name. In the named-argument form, you can give both the volume and the device β as a little sanity check that you're detaching exactly the volume you think you are. self-care tbh π«Ά
Optional arguments:
-volume_idβ ID of the instance to detach from.-deviceβ How the device is exposed to the instance.-forceβ Force detachment, even if previous attempts were unsuccessful.
The result is a VM::EC2::BlockDevice::Attachment object which you can monitor by calling current_status():
my $a = $instance->detach_volume('/dev/sdg');
while ($a->current_status ne 'detached') {
sleep 2;
}
print "volume is ready to go\n";
π NETWORK INTERFACE MANAGEMENT π
$attachment_id = $instance->attach_network_interface($interface_id => $device)
$attachment_id =
$instance->attach_network_interface(-network_interface_id=>$id,
-device_index => $device)
Attaches a network interface to the current instance using the indicated device index. You can use either an elastic network interface ID, or a VM::EC2::NetworkInterface object. And for -device_index you can use an integer, or the strings "eth0", "eth1", etc. flexible queen π
Required arguments:
-network_interface_idβ ID of the network interface to attach.-device_indexβ Network device number to use (e.g.0foreth0).
On success, this method returns the attachmentId of the new attachment β not a VM::EC2::NetworkInterface::Attachment object, due to an AWS API inconsistency. not AWS being messy again π
$boolean = $instance->detach_network_interface($interface_id [,$force])
Detaches a network interface from the current instance. If you pass a true second argument, then the detachment will be forced, even if the interface is in use. careful with that one bestie π
On success, this method returns a true value. β
π ACCESSING INSTANCE METADATA π
$meta = $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. β‘ slay
πͺ STRING OVERLOADING πͺ
When you use this object in a string context, it will interpolate the instanceId. That's it, that's the whole trick. π
π SEE ALSO π
VM::EC2 VM::EC2::Generic VM::EC2::BlockDevice VM::EC2::Instance::State VM::EC2::Instance::State::Reason VM::EC2::Instance::Metadata VM::EC2::Instance::Placement VM::EC2::Tag
π 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 a wrap, bestie!! πβ¨ this whole thing was written by perl v5.38.2 on 2024-08-10, and it's part of the VM::EC2::Instance docs. go forth and manage your instances, main character ππ¦π
π¦ 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