Scroll to navigation

VM::EC2::Instance(3pm) User Contributed Perl Documentation VM::EC2::Instance(3pm)

NAME

VM::EC2::Instance - Object describing an Amazon EC2 instance

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:

 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
                   that describe_instances() was called, as a
                   VM::EC2::Instance::State object. Also
                   see the status() 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        -- The VM::EC2::KeyPair object, derived from the keyName
 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 a
                   VM::EC2::Instance::Placement object, which when used
                   as a string is equal to the instance's
                   availability zone.
 availabilityZone -- Same as placement.
 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 of VM::EC2::ElasticNetworkInterface objects
                   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 of VM::EC2::Group objects indicating the VPC
                   security groups in which this instance resides. Not to be
                   confused with groups(), which returns the security groups
                   of non-VPC instances. 
 stateReason    -- A VM::EC2::Instance::State::Reason object which
                   indicates the reason for the instance's most recent
                   state change. See http://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 of L<VM::EC2::BlockDevice::Mapping> objects.
 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 via add_tags()
                   and delete_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

In addition, the following convenience functions are provided

$state = $instance->current_status

This method queries AWS for the instance's current state and returns it as a VM::EC2::Instance::State object. This enables you to poll the instance until it is in the desired state:

 while ($instance->current_status eq 'pending') { sleep 5 }

$state = $instance->current_state

An alias for current_status().

$state_change = $instance->start([$wait])

This method will start the current instance and returns a VM::EC2::Instance::State::Change object that can be used to monitor the status of the instance. By default the method returns immediately, but you can pass a true value as an argument in order to pause execution until the instance is in the "running" state.

Here's a polling example:

  $state = $instance->start;
  while ($state->status eq 'pending') { sleep 5 }

Here's an example that will pause until the instance is running:

  $instance->start(1);

Attempting to start an already running instance, or one that is in transition, will throw a fatal error.

$state_change = $instance->stop([$wait])

This method is similar to start(), except that it can be used to stop a running instance.

$state_change = $instance->terminate([$wait])

This method is similar to start(), except that it can be used to terminate an instance. It can only be called on instances that are either "running" or "stopped".

$state_change = $instance->reboot()

Reboot the instance. Rebooting doesn't occur immediately; instead the request is queued by the Amazon system and may be satisfied several minutes later. For this reason, there is no "wait" argument.

$seconds = $instance->up_time()

Return the number of seconds since the instance was launched. Note that this includes time that the instance was either in the "running" or "stopped" state.

$result = $instance->associate_address($elastic_address)

Associate an elastic address with this instance. If you are associating a VPC elastic IP address with the instance, the result code will indicate the associationId. Otherwise it will be a simple perl truth value ("1") if successful, undef if false.

In the case of an ordinary EC2 Elastic IP address, the first argument may either be an ordinary string (xx.xx.xx.xx format) or a VM::EC2::ElasticAddress object. However, if it is a VPC elastic IP address, then the argument must be a VM::EC2::ElasticAddress as returned by describe_addresses(). The reason for this is that the allocationId must be retrieved from the object in order to use in the call.

$bool = $instance->disassociate_address

Disassociate an elastic IP address from this instance. if any. The result will be true if disassociation was successful. Note that for a short period of time (up to a few minutes) after disassociation, the instance will have no public IP address and will be unreachable from the internet.

@list = $instance->network_interfaces

Return the network interfaces attached to this instance as a set of VM::EC2::NetworkInterface objects (VPC only).

$instance->refresh

This method will refresh the object from AWS, updating all values to their current ones. You can call it after starting an instance in order to get its IP address. Note that refresh() is called automatically for you if you call start(), stop() or terminate() with a true $wait argument.

$text = $instance->console_output

Return the console output of the instance as a VM::EC2::ConsoleOutput object. This object can be treated as a string, or as an object with methods

CREATING IMAGES

The create_image() method provides a handy way of creating and registering an AMI based on the current state of the instance. All currently-associated block devices will be snapshotted and associated with the image.

Note that this operation can take a long time to complete. You may follow its progress by calling the returned image object's current_status() method.

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)

Create an image from this instance and return a VM::EC2::Image object. The instance must be in the "stopped" or "running" state. In the latter case, Amazon will stop the instance, create the image, and then restart it unless the -no_reboot argument is provided.

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.

In the unnamed argument version you can provide the name and optionally the description of the resulting image.

$boolean = $instance->confirm_product_code($product_code)

Return 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)

Attach 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";

$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 may provide either a volume or a device name. In the named-argument form, you may provide both the volume and the device as a check that you are detaching exactly the volume you think you are.

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)

This method 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. You may use an integer for -device_index, or use the strings "eth0", "eth1" etc.

Required arguments:

 -network_interface_id ID of the network interface to attach.
 -device_index         Network device number to use (e.g. 0 for eth0).

On success, this method returns the attachmentId of the new attachment (not a VM::EC2::NetworkInterface::Attachment object, due to an AWS API inconsistency).

$boolean = $instance->detach_network_interface($interface_id [,$force])

This method detaches a network interface from the current instance. If a true second argument is provided, then the detachment will be forced, even if the interface is in use.

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 fastest way to get runtime information on the current instance.

STRING OVERLOADING

When used in a string context, this object will interpolate the instanceId.

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.

2022-10-14 perl v5.34.0