class AWS::EC2::Instance

Represents an EC2 instance.

@attr [String] user_data Arbitrary metadata that is available

to the instance while it is running.  This interface handles
the details of encoding the user data for transmission; you
should set the user data exactly as you want it to be made
available to the instance.

The instance must be in a stopped state to change user data;
for example:

  i.user_data             # => "HELLO"
  i.status                # => :running
  i.user_data = "GOODBYE" # raises an exception
  i.stop; sleep 1 until i.status == :stopped
  i.user_data = "GOODBYE" # => "GOODBYE"

@attr [String] instance_type The instance type,

e.g. "m1.small".  The instance must be in a stopped state to
change the instance type.

@attr [Boolean] ebs_optimized The instance must be in a stopped state to

change the ebs_optimized state.

@attr [Boolean] api_termination_disabled True if the instance

cannot be terminated using the {#terminate} method.  This
attribute can be changed at any time.

@attr [String] instance_initiated_shutdown_behavior Valid

values are:

["stop"] When the instance shuts down, it will go into a
         "stopped" state.

["terminate"] When the instance shuts down, it will be
              terminated.

@attr_reader [String] image_id Image ID of the AMI used to

launch the instance.

@attr_reader [String] key_name The name of the key pair with

which this instance was associated at launch.

@attr [String] kernel_id The ID of the kernel that the image

currently uses.  The instance must be in a stopped state to
change this attribute.

@attr [String] ramdisk_id The ID of the RAM disk that the

image currently uses.  The instance must be in a stopped
state to change this attribute.

@attr_reader [Symbol] root_device_type The root device type

used by the AMI. The AMI can use an Amazon EBS or instance
store root device.  Valid values:
* +:ebs+
* +:instance_store+

@attr_reader [String] root_device_name The name of the root

device.

@attr_reader [String] private_dns_name The DNS name of the

instance within the EC2 network.

@attr_reader [String] dns_name The DNS name of the instance on

the internet.

@attr_reader [Integer] ami_launch_index The AMI launch index,

which can be used to find this instance within the launch
group.

@attr_reader [String] private_ip_address The private IP

address assigned to the instance.

@attr_reader [String] ip_address The IP address of the

instance.

@attr_reader [Symbol] status The instance status. Valid values are:

* +:pending+
* +:running+
* +:shutting_down+
* +:terminated+
* +:stopping+
* +:stopped+

@attr_reader [Integer] status_code The numeric instance status code.

@attr_reader [Symbol] architecture The architecture of the

image.

@attr_reader [Symbol] virtualization_type The instance's

virtualization type.  Valid values:
* +:paravirtual+
* +:hvm+

@attr_reader [String] reservation_id The ID of the reservation

in which this instance was launched.

@attr_reader [String] requester_id ID of the requester that

launched the instance on your behalf (e.g., AWS Management
Console, Auto Scaling).

@attr_reader [String] owner_id ID of the AWS account that owns

the reservation in which the instance was launched.

@attr_reader [Symbol] monitoring The status of CloudWatch

monitoring for the instance.  Valid values:
* +:enabled+
* +:disabled+
* +:pending+

@attr_reader [String] state_transition_reason A string

describing the reason for the last state transition.

@attr_reader [Time] launch_time The time at which the instance

was launched.

@attr_reader [String] platform A string describing the

platform of the image (e.g. "windows").

@attr_reader [Symbol] hypervisor The instance's hypervisor

type.  Valid values:
* +:ovm+
* +:xen+

@attr_reader [String] client_token Idempotency token you

provided when you launched the instance.

@attr_reader [String,nil] vpc_id Instances launched in a VPC have

a vpc_id.  Normal EC2 instances return nil.

@attr_reader [String,nil] subnet_id Instances launched in a VPC have

a subnet_id.  Normal EC2 instances return nil.

@attr_reader [String,nil] iam_instance_profile_id

@attr_reader [String,nil] iam_instance_profile_arn

Attributes

id[R]

@return [String] Returns the instance id.

instance_id[R]

@return [String] Returns the instance id.

Public Class Methods

describe_call_attribute(name, options = {}) click to toggle source

@private

# File lib/aws/ec2/instance.rb, line 193
def self.describe_call_attribute name, options = {}, &block
  attr = attribute(name, options, &block)
  describe_call_attributes[attr.name] = attr
end
describe_call_attributes() click to toggle source

@private

# File lib/aws/ec2/instance.rb, line 183
def self.describe_call_attributes
  @describe_call_attributes ||= {}
end
mutable_describe_attribute(name, options = {}) click to toggle source

@private

# File lib/aws/ec2/instance.rb, line 205
def self.mutable_describe_attribute name, options = {}, &block
  attr = mutable_attribute(name, options, &block)
  mutable_describe_attributes[attr.name] = attr
end
mutable_describe_attributes() click to toggle source

@private

# File lib/aws/ec2/instance.rb, line 188
def self.mutable_describe_attributes
  @mutable_describe_attributes ||= {}
end
mutable_describe_call_attribute(name, options = {}) click to toggle source

@private

# File lib/aws/ec2/instance.rb, line 199
def self.mutable_describe_call_attribute name, options = {}, &block
  attr = mutable_attribute(name, options, &block)
  describe_call_attributes[attr.name] = attr
end
new(instance_id, opts = {}) click to toggle source

Creates an object that represents the instance with the given ID. It's usually easier to get an instance of this class by calling {InstanceCollection#[]} or {InstanceCollection#each}.

Calls superclass method
# File lib/aws/ec2/instance.rb, line 162
def initialize(instance_id, opts = {})
  super
  @id = instance_id
end
reservation_attribute(name, options = {}) click to toggle source

@private

# File lib/aws/ec2/instance.rb, line 177
def self.reservation_attribute name, options = {}, &block
  attr = attribute(name, options, &block)
  reservation_attributes[attr.name] = attr
end
reservation_attributes() click to toggle source

@private

# File lib/aws/ec2/instance.rb, line 172
def self.reservation_attributes
  @reservation_attributes ||= {}
end

Public Instance Methods

associate_elastic_ip(elastic_ip) click to toggle source

Associates the elastic IP address with this instance.

@overload #associate_elastic_ip(elastic_ip)

@param [ElasticIp,String] elastic_ip An Elastic ip address
  (VPC or non-VPC) or a public ip address string (non-VPC only).

@overload #associate_elastic_ip(allocation_id)

@param [String] allocation_id The allocation id of a
  VPC elastic ip address.

@return [nil]

# File lib/aws/ec2/instance.rb, line 594
def associate_elastic_ip elastic_ip

  client_opts = {}
  client_opts[:instance_id] = self.id

  if vpc?
    client_opts[:allocation_id] = elastic_ip.is_a?(ElasticIp) ?
      elastic_ip.allocation_id :
      elastic_ip.to_s
  else
    client_opts[:public_ip] = elastic_ip.to_s
  end

  client.associate_address(client_opts)
  nil

end
Also aliased as: ip_address=
attach_network_interface(network_interface, options = {}) click to toggle source

Attaches a network interface to this instance (VPC only).

@param [NetworkInterface,String] network_interface A network interface

(or network interface id string) to attach to this vpc instance.

@param [Hash] options

@option (see AWS::EC2::NetworkInterface#attach)

@return [nil]

# File lib/aws/ec2/instance.rb, line 422
def attach_network_interface network_interface, options = {}
  if network_interface.is_a?(NetworkInterface)
    network_interface.attach(self, options)
  else
    i = NetworkInterface.new(network_interface, :config => config)
    i.attach(self, options)
  end
  nil
end
attachments() click to toggle source

@return [Hash<String,Attachment>] Returns a hash of attachments.

The keys are device name strings (e.g. '/dev/sda') and the values
are {Attachment} objects.

@note This method will not return data for ephemeral volumes. @see {#block_devices}

# File lib/aws/ec2/instance.rb, line 446
def attachments
  (block_device_mapping || []).inject({}) do |m, mapping|
    if mapping[:ebs]
      device = mapping[:device_name]
      volume = Volume.new(mapping[:ebs][:volume_id], :config => config)
      attachment = Attachment.new(volume, self, device, :config => config)
      m[device] = attachment
    end
    m
  end
end
Also aliased as: block_device_mappings
availability_zone() click to toggle source

@return [String] The availability zone where the instance is

running.
# File lib/aws/ec2/instance.rb, line 518
def availability_zone
  if p = placement
    p.availability_zone
  end
end
block_device_mappings()
Alias for: attachments
block_devices() click to toggle source

Returns a list of block device mappings.

instance.block_devices
#=>
[
  {
    :device_name => "/dev/sda2",
    :ebs => {
      :volume_id => "vol-123",
      :status => "attaching",
      :attach_time => time,
      :delete_on_termination => true
    }
  }, {
    :device_name => "/dev/sdb",
    :virtual_name => "ephemeral0",
  }
]

@return [Array<Hash>] Returns a list of block device mappings. This

list may contain ephemeral volumes.
# File lib/aws/ec2/instance.rb, line 480
def block_devices
  block_device_mapping.to_a
end
console_output() click to toggle source

Retrieves the console output for the instance.

@return [String] the console output.

# File lib/aws/ec2/instance.rb, line 577
def console_output
  output = client.get_console_output(:instance_id => self.id).output
  Base64.decode64(output) if output
end
create_image(name, options = {}) click to toggle source

Creates an AMI from this instance.

@param [String] name A name for the new image you're

creating.  Constraints: 3-128 alphanumeric characters,
parenthesis (()), commas (,), slashes (/), dashes (-), or
underscores(_)

@param [Hash] options Additional options for creating the

image.

@option options [String] :description A description of the

new image.

@option options [Boolean] :no_reboot By default this

option is set to +false+, which means Amazon EC2
attempts to cleanly shut down the instance before image
creation and reboots the instance afterwards. When the
option is set to +true+, Amazon EC2 does not shut down
the instance before creating the image. When this option
is used, file system integrity on the created image cannot
be guaranteed.

@return [Image] The newly created image.

# File lib/aws/ec2/instance.rb, line 569
def create_image name, options = {}
  images = ImageCollection.new(:config => config)
  images.create(options.merge(:instance_id => id, :name => name))
end
dedicated_tenancy?() click to toggle source

@return [Boolean] Returns true if the instance has dedicated tenancy.

This will be false for all non-VPC instances.  Dedicated Tenancy
comes at extra cost.
# File lib/aws/ec2/instance.rb, line 527
def dedicated_tenancy?
  if p = placement
    p.tenancy == 'dedicated'
  else
    false
  end
end
delete()
Alias for: terminate
disable_monitoring() click to toggle source

Disables monitoring for this instance. @return [nil]

# File lib/aws/ec2/instance.rb, line 493
def disable_monitoring
  client.unmonitor_instances(:instance_ids => [id])
  nil
end
disassociate_elastic_ip() click to toggle source

Disassociates an attached elastic IP address from this instance. Raises an exception if there is no elastic IP address associated with this instance.

# File lib/aws/ec2/instance.rb, line 617
def disassociate_elastic_ip
  if ip = self.elastic_ip
    ip.disassociate
  else
    raise "instance #{id} does not have an associated elastic ip"
  end
end
elastic_ip() click to toggle source

@return [ElasticIp,nil] Returns an elastic IP address if one

is associated with this instance, nil otherwise.
# File lib/aws/ec2/instance.rb, line 627
def elastic_ip
  ips = ElasticIpCollection.new(:config => config)
  ips.filter('instance-id', id).first
end
enable_monitoring() click to toggle source

Enables monitoring for this instance. @return [nil]

# File lib/aws/ec2/instance.rb, line 486
def enable_monitoring
  client.monitor_instances(:instance_ids => [id])
  nil
end
exists?() click to toggle source

@return [Boolean] Returns true if the instance exists according to

EC2.
# File lib/aws/ec2/instance.rb, line 640
def exists?
  client.describe_instances(:filters => [
    { :name => "instance-id", :values => [id] }
  ]).instance_index.key?(id)
end
export_to_s3(bucket, options = {}) click to toggle source

This produces an image of an EC2 instance for use in another virtualization environment and then writes the image to a S3 bucket.

Granting EC2 write access to your bucket ↑

Before you can export an image to an S3 bucket, you must modify the bucket ACL. You only need to do this once per bucket.

s3.buckets['bucket-name'].acl.change do |acl|
  acl.grant(:read_acp).to(:amazon_customer_email => 'vm-import-export@amazon.com')
  acl.grant(:write).to(:amazon_customer_email => 'vm-import-export@amazon.com')
end

Performing the export ↑

Simply call export_to_s3 on your instance. Only instances derived from your own ImportInstance tasks may be exported.

task = ec2.instances['i-12345678'].export_to_s3('bucket-name')

Downloading the results ↑

Given a completed export task you can download the final image:

File.open('image.ova', 'w') {|f| f.write(task.s3_object.read) }

@param [S3::Bucket,String] bucket The destination bucket. May

be the name of the bucket (string) or a {S3::Bucket} object. The
bucket must exist and grant write permissiosn to the AWS account
'vm-import-export@amazon.com.'.

@param [Hash] options

@option options [String] :target_environment ('vmware') The target

virtualization environment.  Valid values include: 'vmware', 'citrix'
and 'microsoft'.

@option options [String] :disk_image_format The format for the exported

image.  Defaults to 'vmdk' if +:target_environemnt+ is 'vmware',
otherwise, 'vhd'.

@option options [String] :container_format The container format used to

combine disk images with metadata (such as OVF). If absent, only
the disk image will be exported.  Defaults to 'ova' if
+:target_environment+ is 'vmware', otherwise ommited.

@option options [String] :description Description of the conversion

task or the resource being exported.

@option options [String] :prefix (nil) The image is written to a

single object in the bucket at the key:

  "#{prefix}#{export_task_id}.#{disk_image_format}"

@return [ExportTask]

# File lib/aws/ec2/instance.rb, line 741
def export_to_s3 bucket, options = {}

  bucket_name = bucket.is_a?(S3::Bucket) ? bucket.name : bucket.to_s

  opts = {}
  opts[:instance_id] = instance_id
  opts[:description] = options[:description] if options[:description]
  opts[:target_environment] = options[:target_environment] || 'vmware'
  opts[:export_to_s3] = {}
  opts[:export_to_s3][:s3_bucket] = bucket_name
  [:disk_image_format, :container_format, :s3_prefix].each do |opt|
    opts[:export_to_s3][opt] = options[opt] if options.key?(opt)
  end

  resp = client.create_instance_export_task(opts)

  ExportTask.new_from(
    :create_instance_export_task,
    resp[:export_task],
    resp[:export_task][:export_task_id],
    :config => config)

end
groups()
Alias for: security_groups
has_elastic_ip?() click to toggle source

@return [Boolean] Returns true if an elastic IP address is

associated with this instance, false otherwise.
# File lib/aws/ec2/instance.rb, line 634
def has_elastic_ip?
  !elastic_ip.nil?
end
image() click to toggle source

@return [Image] The AMI used to launch the instance.

# File lib/aws/ec2/instance.rb, line 536
def image
  Image.new(image_id, :config => config)
end
ip_address=(elastic_ip)
key_pair() click to toggle source

@return [KeyPair] The key pair with which this instance was

associated at launch.
# File lib/aws/ec2/instance.rb, line 542
def key_pair
  KeyPair.new(key_name, :config => config) if key_name
end
monitoring_enabled=(state) click to toggle source

Enables or disables monitoring for this instance. @param [Boolean] state A true or false value. Enables monintoring

for a true value, disables it for a false value.
# File lib/aws/ec2/instance.rb, line 501
def monitoring_enabled= state
  state ? enable_monitoring : disable_monitoring
end
monitoring_enabled?() click to toggle source

@return [Booelan] Returns true if CloudWatch monitoring is

enabled for this instance.
# File lib/aws/ec2/instance.rb, line 507
def monitoring_enabled?
  monitoring == :enabled
end
network_interfaces() click to toggle source

@return [Array<NetworkInterface>] Returns a list of elastic network

interfaces attached to this instance (VPC only).  Non-vpc
instance may not have attached network interfaces.
# File lib/aws/ec2/instance.rb, line 404
def network_interfaces
  network_interface_set.collect do |ni|
    NetworkInterface.new_from(:describe_network_interfaces, ni,
      ni.network_interface_id, :config => config)
  end
end
reboot() click to toggle source

Reboots the instance. @return [nil]

# File lib/aws/ec2/instance.rb, line 667
def reboot
  instance_action :reboot
end
reset_kernel_id() click to toggle source

Resets the kernel to its default value.

# File lib/aws/ec2/instance.rb, line 647
def reset_kernel_id
  client.reset_instance_attribute(
    :instance_id => id, :attribute => "kernel").return
end
reset_ramdisk_id() click to toggle source

Resets the RAM disk to its default value.

# File lib/aws/ec2/instance.rb, line 653
def reset_ramdisk_id
  client.reset_instance_attribute(
    :instance_id => id, :attribute => "ramdisk").return
end
security_groups() click to toggle source

@return [Array<SecurityGroup>] Returns a list of security

groups the instance belongs to.
# File lib/aws/ec2/instance.rb, line 434
def security_groups
  (group_set || []).collect do |g|
    SecurityGroup.new(g.group_id, :name => g.group_name, :config => config)
  end
end
Also aliased as: groups
spot_instance?() click to toggle source

@return [Boolean] true if the instance is a Spot instance.

# File lib/aws/ec2/instance.rb, line 512
def spot_instance?
  instance_lifecycle == :spot
end
start() click to toggle source

Starts the instance, assuming it is in a stopped state. @see stop @return [nil]

# File lib/aws/ec2/instance.rb, line 674
def start
  instance_action :start
end
stop() click to toggle source

Stops the instance, eventually putting it into a stopped state. @return [nil]

# File lib/aws/ec2/instance.rb, line 680
def stop
  instance_action :stop
end
subnet() click to toggle source

@return [Subnet,nil] Returns the VPC subnet this instance was

launched in.  Returns nil if this was not launched in a VPC.
# File lib/aws/ec2/instance.rb, line 395
def subnet
  if subnet_id
    Subnet.new(subnet_id, :vpc_id => vpc_id, :config => config)
  end
end
terminate() click to toggle source

Terminates the instance. @return [nil]

# File lib/aws/ec2/instance.rb, line 660
def terminate
  instance_action :terminate
end
Also aliased as: delete
vpc() click to toggle source

@return [VPC,nil] Returns the VPC this instance was launched in.

If this instance was not launched inside a VPC, nil is returned.
# File lib/aws/ec2/instance.rb, line 387
def vpc
  if vpc_id
    VPC.new(vpc_id, :config => config)
  end
end
vpc?() click to toggle source

@return [Boolean] Returns true if this is an EC2 VPC instance.

# File lib/aws/ec2/instance.rb, line 381
def vpc?
  !!vpc_id
end

Protected Instance Methods

attributes_from_response_object(obj) click to toggle source
Calls superclass method
# File lib/aws/ec2/instance.rb, line 784
def attributes_from_response_object(obj)
  if atts = super(obj)
    if obj[:instance_state]
      atts[:status] = obj[:instance_state].name.tr("-","_").to_sym
    end
    atts
  end
end
find_in_response(resp) click to toggle source
# File lib/aws/ec2/instance.rb, line 767
def find_in_response resp
  resp.instance_index[id]
end
get_resource(attribute) click to toggle source
# File lib/aws/ec2/instance.rb, line 776
def get_resource attribute
  if self.class.mutable_describe_attributes.include?(attribute.name)
    describe_attribute_call(attribute)
  else
    describe_call
  end
end
instance_action(name) click to toggle source
# File lib/aws/ec2/instance.rb, line 771
def instance_action name
  client.send("#{name}_instances", :instance_ids => [id])
  nil
end