Controlling Instances

The EC2 service provides API operations for managing the lifecycle of your instances. We will start by looking at how you can terminate your running instances; it is wise to know how to do this before you start launching instances that will incur fees for every hour they run.

The TerminateInstances operation shown in Table 5-10 terminates one or more instances running in your EC2 account. An instance can be terminated multiple times without any ill effects.

Here is an XML document returned by the operation:

<TerminateInstancesResponse 
                          xmlns='http://ec2.amazonaws.com/doc/2007-08-29/'>
  <instancesSet>
    <item>
      <instanceId>i-ec43a885</instanceId>
      <shutdownState>
        <code>32</code>
        <name>shutting-down</name>
      </shutdownState>
      <previousState>
        <code>16</code>
        <name>running</name>
      </previousState>
    </item>
  </instancesSet>
</TerminateInstancesResponse>

The response document returned by the operation includes a listing of the instances that were acted upon by the operation with information about the instance’s prior status and its status as a result of the TerminateInstances operation. Each item element in the XML document describes the status of one instance, Table 5-11 lists the contents of this element.

Example 5-7 defines a method that terminates specific instances based on the identifier values provided. The method returns an array of the terminated instances with information about the previous and current status of each instance.

Here is an example of how to use the method to terminate an instance:

irb> ec2.terminate_instances('i-ec43a885')
=> [{:previous_state=>"running", :state=>"shutting-down", :id=>"i-ec43a885"}]

The RunInstances operation shown in Table 5-12 launches one or more instances based on a particular AMI. You can specify the type of instance you wish to run—small, large, or extra large—and you must choose an AMI that is compatible with the instance's underlying 32-bit or 64-bit platform. You can start multiple instances with one request by specifying the minimum and maximum number of instances you wish to run.

When you launch your instances, you specify a number of properties that will determine how that instance behaves in the EC2 environment. You can instruct EC2 to run the instance within specific security groups and associate it with a set of keypair credentials you have created in your account. You can also provide arbitrary context data to the instance, which we will discuss in Instance Data” in Chapter 6. It is important to apply the settings you need at launch time, because you cannot change them afterwards.

Note

Amazon limits most EC2 users to running no more than 20 instances at a time. If 20 instances will not be enough to meet your needs, contact Amazon to arrange for a higher limit.

Here is an XML document returned by the operation:

<RunInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2007-08-29/">
  <reservationId>r-a99171c0</reservationId>
  <ownerId>123456789012</ownerId>
  <groupSet>
    <item>
      <groupId>default</groupId>
    </item>
  </groupSet>
  <instancesSet>
    <item>
      <instanceId>i-3495795d</instanceId>
      <imageId>ami-2bb65342</imageId>
      <instanceState>
        <code>0</code>
        <name>pending</name>
      </instanceState>
      <privateDnsName/>
      <dnsName/>
      <reason/>
      <keyName>ec2-private-key</keyName>
      <amiLaunchIndex>0</amiLaunchIndex>
      <instanceType>m1.small</instanceType>
      <launchTime>2007-10-26T04:29:21.000Z</launchTime>
    </item>
  </instancesSet>
</RunInstancesResponse>

Note

The RunInstances operation will only return a limited amount of information in the response document, because many of the instance’s properties will not become known until the instance has finished launching.

The response document from the operation includes information about the reservation grouping in which the instances were launched, and the reservation itself contains a listing of the launched instances. Table 5-13 outlines the information that is available at the top level of the response document.

Table 5-14 gives a description of the information made available about each instance, as contained in the instancesSet/item elements:

Table 5-14. RunningInstancesItemType element

Element NameDescription
instanceIdThe identifier of the instance.
imageIdThe identifier of the AMI on which the instance is based.
instanceStateThe current state of the instance, represented as a named state and a code number. The instance may be:
  • pending (0): launching and not yet started

  • running (16): launched and performing like a normal computer (though not necessarily finished booting the AMI’s operating system)

  • shutting-down (32): in the process of terminating

  • terminated (42): no longer running

privateDnsNameThe private DNS name assigned to the instance to be used within the EC2 network. This element will only have a value when the instance is running.
dnsNameThe public DNS name assigned to the instance to be used from outside the EC2 network. This element will only have a value when the instance is running.
reasonThe reason for the most recent status change. This element is often empty.
keyNameThe keypair name associated with the instance, if any. If the instance does not have an associated keypair, this element will not be present.
amiLaunchIndexThe launch index, a zero-based offset identifying a particular instance within a reservation group.
productCodes

Lists the product codes associated with the AMI the instance is based on. If the AMI has no product codes, this element will not be present. Product codes are string values listed as multipleitem/productCode elements inside this element. The presence of a product code indicates that the image is a Paid AMI.

instanceTypeThe type of the instance: m1.small, m1.large, or m1.xlarge.
launchTimeA timestamp specifying when the instance was first launched in ISO 8601 format.

Example 5-8 defines a method that starts EC2 instances and returns detailed information about the reservation and instances in a hash dictionary. The method has only one mandatory parameter; it specifies the AMI identifier on which the instances will be based. By default, the method launches a single instance.

Example 5-9 defines a method that parses XML elements of the type RunningInstancesItemType, which contain the details of instance reservations in EC2. A number of EC2 operations include this particular element in their response messages. By factoring the parsing code out into a separate method, we can easily reuse it elsewhere.

We can now start an instance based on a public AMI. We will start a single instance based on the “Getting Started” AMI provided by Amazon, which has the identifier ami-2bb65342. We will configure the instance to use the keypair called “ec2-private-key,” which we created earlier, and for which we have the corresponding private key file.

# Set the key_name option to the value 'ec2-private-key'
irb> opts = {:key_name => 'ec2-private-key'}

# Launch a single instance of the AMI 'ami-2bb65342'
irb> instances = ec2.run_instances('ami-2bb65342', 1, 1, opts)
{:instances=>
  [{:state=>"pending",
    :image_id=>"ami-2bb65342",
    :public_dns=>nil,
    :key_name=>"ec2-private-key",
    :launch_time=>"2007-10-26T07:07:02.000Z",
    :id=>"i-7641aa1f",
    :index=>"0",
    :reason=>nil,
    :type=>"m1.small",
    :private_dns=>nil}],
 :owner_id=>"123456789012",
 :groups=>["default"],
 :reservation_id=>"r-04a44b6d"}

The instance will take a little while to start and enter the running state. To monitor the status of the instance, we will use the DescribeInstances operation, which we will discuss next.

Once the instance has entered the running state, and it has had enough time to boot the operating system and start the Secure Shell daemon service, we will be able to log in to the instance and take a look around. We will discuss the login process shortly, in the section Log In to an Instance.”

The DescribeInstances operation outlined in Table 5-15 lists the instances that are currently running in your EC2 account or those that were terminated within the last hour or so. The listing contains detailed information about each of these instances, and it can be filtered to include only the specific instances you are interested in.

Here is an XML document returned by the operation:

<DescribeInstancesResponse xmlns='http://ec2.amazonaws.com/doc/2007-08-29/'>
  <reservationSet>
    <item>
      <reservationId>r-77a54a1e</reservationId>
      <ownerId>123456789012</ownerId>
      <groupSet>
        <item>
          <groupId>default</groupId>
        </item>
      </groupSet>
      <instancesSet>
        <item>
          <instanceId>i-ec43a885</instanceId>
          <imageId>ami-2bb65342</imageId>
          <instanceState>
            <code>16</code>
            <name>running</name>
          </instanceState>
          <privateDnsName>domU-12-31-91.z-1.compute-1.internal</privateDnsName>
          <dnsName>ec2-67-202-5-75.z-1.compute-1.amazonaws.com</dnsName>
          <reason/>
          <amiLaunchIndex>0</amiLaunchIndex>
          <instanceType>m1.small</instanceType>
          <launchTime>2007-10-26T04:29:21.000Z</launchTime>
        </item>
      </instancesSet>
    </item>
  </reservationSet>
</DescribeInstancesResponse>

The response document includes a listing of the reservations in which the instances were launched, and each reservation includes a listing of the instances that were started within that reservation. These XML data structures were described in detail in the section Starting Instances.”

Example 5-10 defines a method that lists your running or recently terminated instances. The method takes advantage of the parse_reservation method we have already defined.

Because we recently started an instance, we can perform a listing and check whether that instance has started up.

irb> listing = ec2.describe_instances
[{:instances=>
   [{:state=>"running",
     :image_id=>"ami-2bb65342",
     :public_dns=>"ec2-67-202-4-222.z-1.compute-1.amazonaws.com",
     :key_name=>"ec2-private-key",
     :launch_time=>"2007-10-26T07:07:02.000Z",
     :id=>"i-7641aa1f",
     :index=>"0",
     :reason=>nil,
     :type=>"m1.small",
     :private_dns=>"domU-12-31-36-00-0A-54.z-1.compute-1.internal"}],
  :owner_id=>"123456789012",
  :groups=>["default"],
  :reservation_id=>"r-04a44b6d"}]

We can see from the details returned by the listing that our instance is now in the running state, and the public and private DNS names have been assigned. The instance is running in the default security group, and it has been associated with our keypair named “ec2-private-key.” Everything is looking good, so it is time to log in.