run_instances ( $image_id, $min_count, $max_count, $opt )

The RunInstances operation launches a specified number of instances.

If Amazon EC2 cannot launch the minimum number AMIs you request, no instances launch. If there is insufficient capacity to launch the maximum number of AMIs you request, Amazon EC2 launches as many as possible to satisfy the requested maximum values.

Every instance is launched in a security group. If you do not specify a security group at launch, the instances start in your default security group. For more information on creating security groups, see CreateSecurityGroup.

An optional instance type can be specified. For information about instance types, see Instance Types.

You can provide an optional key pair ID for each image in the launch request (for more information, see CreateKeyPair). All instances that are created from images that use this key pair will have access to the associated public key at boot. You can use this key to provide secure access to an instance of an image on a per-instance basis. Amazon EC2 public images use this feature to provide secure access without passwords.

Launching public images without a key pair ID will leave them inaccessible.

The public key material is made available to the instance at boot time by placing it in the openssh_id.pub file on a logical device that is exposed to the instance as /dev/sda2 (the ephemeral store). The format of this file is suitable for use as an entry within ~/.ssh/authorized_keys (the OpenSSH format). This can be done at boot (e.g., as part of rc.local) allowing for secure access without passwords.

Optional user data can be provided in the launch request. All instances that collectively comprise the launch request have access to this data For more information, see Instance Metadata.

If any of the AMIs have a product code attached for which the user has not subscribed, the RunInstances call will fail.

We strongly recommend using the 2.6.18 Xen stock kernel with the c1.medium and c1.xlarge instances. Although the default Amazon EC2 kernels will work, the new kernels provide greater stability and performance for these instance types. For more information about kernels, see Kernels, RAM Disks, and Block Device Mappings.

Access

public

Parameters

Parameter

Type

Required

Description

$image_id

string

Required

Unique ID of a machine image, returned by a call to DescribeImages.

$min_count

integer

Required

Minimum number of instances to launch. If the value is more than Amazon EC2 can launch, no instances are launched at all.

$max_count

integer

Required

Maximum number of instances to launch. If the value is more than Amazon EC2 can launch, the largest possible number above minCount will be launched instead. Between 1 and the maximum number allowed for your account (default: 20).

$opt

array

Optional

An associative array of parameters that can have the following keys:

  • KeyName - string - Optional - The name of the key pair.
  • SecurityGroup - string|array - Optional - The names of the security groups into which the instances will be launched. Pass a string for a single value, or an indexed array for multiple values.
  • SecurityGroupId - string|array - Optional - Pass a string for a single value, or an indexed array for multiple values.
  • UserData - string - Optional - Specifies additional information to make available to the instance(s).
  • InstanceType - string - Optional - Specifies the instance type for the launched instances. [Allowed values: t1.micro, m1.small, m1.medium, m1.large, m1.xlarge, m2.xlarge, m2.2xlarge, m2.4xlarge, m3.xlarge, m3.2xlarge, c1.medium, c1.xlarge, hi1.4xlarge, hs1.8xlarge, cc1.4xlarge, cc2.8xlarge, cg1.4xlarge]
  • Placement - array - Optional - Specifies the placement constraints (Availability Zones) for launching the instances.
    • x - array - Optional - This represents a simple array index.
      • AvailabilityZone - string - Optional - The availability zone in which an Amazon EC2 instance runs.
      • GroupName - string - Optional - The name of the PlacementGroup in which an Amazon EC2 instance runs. Placement groups are primarily used for launching High Performance Computing instances in the same group to ensure fast connection speeds.
      • Tenancy - string - Optional - The allowed tenancy of instances launched into the VPC. A value of default means instances can be launched with any tenancy; a value of dedicated means all instances launched into the VPC will be launched as dedicated tenancy regardless of the tenancy assigned to the instance at launch.
  • KernelId - string - Optional - The ID of the kernel with which to launch the instance.
  • RamdiskId - string - Optional - The ID of the RAM disk with which to launch the instance. Some kernels require additional drivers at launch. Check the kernel requirements for information on whether you need to specify a RAM disk. To find kernel requirements, go to the Resource Center and search for the kernel ID.
  • BlockDeviceMapping - array - Optional - Specifies how block devices are exposed to the instance. Each mapping is made up of a virtualName and a deviceName.
    • x - array - Optional - This represents a simple array index.
      • VirtualName - string - Optional - Specifies the virtual device name.
      • DeviceName - string - Optional - Specifies the device name (e.g., /dev/sdh).
      • Ebs - array - Optional - Specifies parameters used to automatically setup Amazon EBS volumes when the instance is launched.
        • x - array - Optional - This represents a simple array index.
          • SnapshotId - string - Optional - The ID of the snapshot from which the volume will be created.
          • VolumeSize - integer - Optional - The size of the volume, in gigabytes.
          • DeleteOnTermination - boolean - Optional - Specifies whether the Amazon EBS volume is deleted on instance termination.
          • VolumeType - string - Optional - [Allowed values: standard, io1]
          • Iops - integer - Optional -
      • NoDevice - string - Optional - Specifies the device name to suppress during instance launch.
  • Monitoring.Enabled - boolean - Optional - Enables monitoring for the instance.
  • SubnetId - string - Optional - Specifies the subnet ID within which to launch the instance(s) for Amazon Virtual Private Cloud.
  • DisableApiTermination - boolean - Optional - Specifies whether the instance can be terminated using the APIs. You must modify this attribute before you can terminate any “locked” instances from the APIs.
  • InstanceInitiatedShutdownBehavior - string - Optional - Specifies whether the instance’s Amazon EBS volumes are stopped or terminated when the instance is shut down.
  • License - array - Optional - Specifies active licenses in use and attached to an Amazon EC2 instance.
    • x - array - Optional - This represents a simple array index.
      • Pool - string - Optional - The license pool from which to take a license when starting Amazon EC2 instances in the associated RunInstances request.
  • PrivateIpAddress - string - Optional - If you’re using Amazon Virtual Private Cloud, you can optionally use this parameter to assign the instance a specific available IP address from the subnet.
  • ClientToken - string - Optional - Unique, case-sensitive identifier you provide to ensure idempotency of the request. For more information, go to How to Ensure Idempotency in the Amazon Elastic Compute Cloud User Guide.
  • NetworkInterface - array - Optional -
    • x - array - Optional - This represents a simple array index.
      • NetworkInterfaceId - string - Optional -
      • DeviceIndex - integer - Optional -
      • SubnetId - string - Optional -
      • Description - string - Optional -
      • PrivateIpAddress - string - Optional -
      • SecurityGroupId - string|array - Optional - Pass a string for a single value, or an indexed array for multiple values.
      • DeleteOnTermination - boolean - Optional -
      • PrivateIpAddresses - array - Optional -
        • x - array - Optional - This represents a simple array index.
          • PrivateIpAddress - string - Required -
          • Primary - boolean - Optional -
      • SecondaryPrivateIpAddressCount - integer - Optional -
  • IamInstanceProfile - array - Optional -
    • x - array - Optional - This represents a simple array index.
      • Arn - string - Optional -
      • Name - string - Optional -
  • EbsOptimized - boolean - Optional -
  • curlopts - array - Optional - A set of values to pass directly into curl_setopt(), where the key is a pre-defined CURLOPT_* constant.
  • returnCurlHandle - boolean - Optional - A private toggle specifying that the cURL handle be returned rather than actually completing the request. This toggle is useful for manually managed batch requests.

Returns

Type

Description

CFResponse

A CFResponse object containing a parsed HTTP response.

Examples

Launch an EC2 instance.

// Instantiate the class
$ec2 = new AmazonEC2();

// Boot an instance of the image
$response = $ec2->run_instances('ami-84db39ed', 1, 1, array(
	'InstanceType' => 'm1.small'
));

// Success?
var_dump($response->isOK());
Result:
bool(true)

Run an instance in the VPC under a subnet

// Dependencies
require_once dirname(__FILE__) . '/../../sdk.class.php';
require_once dirname(__FILE__) . '/../testutil.inc.php';

// Instantiate the class
$ec2 = new AmazonEC2();

// Boot an instance of the image into the subnet in the VPC
$response = $ec2->run_instances($image_id, 1, 1, array(
	'InstanceType' => 'm1.small',
        'SubnetId' => $subnet_id,
));

// Temporarily cache the InstanceID
if ($response->isOK() && isset($response->body->instancesSet->item->instanceId))
{
        $instance_id = (string) $response->body->instancesSet->item->instanceId;
	file_put_contents(dirname(__FILE__) . '/cache/instance_id_subnet.cache', $instance_id);
}

// Success?
var_dump($response->isOK());

    // Block until it's available
    if (isset($instance_id))
    {
        // If it's not running yet, sleep for 20 seconds and check again
        do
        {
            echo '.'; // Output something so we don't get a processing timeout from the test runner
            sleep(10);

            // Update the status of the instance
            $status_check = $ec2->describe_instances(array(
                'InstanceId' => $instance_id
            ));
        }
        while ((int) $status_check->body->reservationSet->item->instancesSet->item->instanceState->code !== AmazonEC2::STATE_RUNNING);

        echo 'done';
    }

Related Methods

Source

Method defined in services/ec2.class.php | Toggle source view (72 lines) | View on GitHub

public function run_instances($image_id, $min_count, $max_count, $opt = null)
{
    if (!$opt) $opt = array();
    $opt['ImageId'] = $image_id;
    $opt['MinCount'] = $min_count;
    $opt['MaxCount'] = $max_count;
    
    // Optional list (non-map)
    if (isset($opt['SecurityGroup']))
    {
        $opt = array_merge($opt, CFComplexType::map(array(
            'SecurityGroup' => (is_array($opt['SecurityGroup']) ? $opt['SecurityGroup'] : array($opt['SecurityGroup']))
        )));
        unset($opt['SecurityGroup']);
    }
    
    // Optional list (non-map)
    if (isset($opt['SecurityGroupId']))
    {
        $opt = array_merge($opt, CFComplexType::map(array(
            'SecurityGroupId' => (is_array($opt['SecurityGroupId']) ? $opt['SecurityGroupId'] : array($opt['SecurityGroupId']))
        )));
        unset($opt['SecurityGroupId']);
    }
    
    // Optional map (non-list)
    if (isset($opt['Placement']))
    {
        $opt = array_merge($opt, CFComplexType::map(array(
            'Placement' => $opt['Placement']
        )));
        unset($opt['Placement']);
    }
    
    // Optional list + map
    if (isset($opt['BlockDeviceMapping']))
    {
        $opt = array_merge($opt, CFComplexType::map(array(
            'BlockDeviceMapping' => $opt['BlockDeviceMapping']
        )));
        unset($opt['BlockDeviceMapping']);
    }
    
    // Optional map (non-list)
    if (isset($opt['License']))
    {
        $opt = array_merge($opt, CFComplexType::map(array(
            'License' => $opt['License']
        )));
        unset($opt['License']);
    }
    
    // Optional list + map
    if (isset($opt['NetworkInterface']))
    {
        $opt = array_merge($opt, CFComplexType::map(array(
            'NetworkInterface' => $opt['NetworkInterface']
        )));
        unset($opt['NetworkInterface']);
    }
    
    // Optional map (non-list)
    if (isset($opt['IamInstanceProfile']))
    {
        $opt = array_merge($opt, CFComplexType::map(array(
            'IamInstanceProfile' => $opt['IamInstanceProfile']
        )));
        unset($opt['IamInstanceProfile']);
    }

    return $this->authenticate('RunInstances', $opt);
}

Copyright © 2010–2013 Amazon Web Services, LLC


Feedback