How to get list of EC2 instances with Amazon PHP SDK 2?

Use DescribeInstances method for this. Let's cover this with some more details.

You need to get Ec2Client instance first. The easiest way to initialize the client:

$config = array();
$config['key'] = 'key';
$config['secret'] = 'secret';
$config['region'] = 'us-east-1';
$config['version'] = 'latest'; // Or Specified
$ec2Client = \Aws\Ec2\Ec2Client::factory($config);

And then just call DescribeInstances method.

$result = $ec2Client->DescribeInstances(array(
        'Filters' => array(
                array('Name' => 'instance-type', 'Values' => array('m1.small')),
        )
));

You can get list of available filters on the Amazon DescribeInstances API method page.

But wait, what might be difficult here?

  • Note the parameter name Filters. In the API it is called Filter
  • Parameter Values is called different from API and it is an array

Yes, this is all described in the documentation. But if you look at some Old API usage samples you can see that the syntax has changed and this might be really hard to notice what have to be updated in that examples to make things working.

And to complete the example let me show some simple output of the results.

$reservations = $result['Reservations'];
foreach ($reservations as $reservation) {
    $instances = $reservation['Instances'];
    foreach ($instances as $instance) {

        $instanceName = '';
        foreach ($instance['Tags'] as $tag) {
            if ($tag['Key'] == 'Name') {
                $instanceName = $tag['Value'];
            }
        }


        echo 'Instance Name: ' . $instanceName . PHP_EOL;
        echo '---> State: ' . $instance['State']['Name'] . PHP_EOL;
        echo '---> Instance ID: ' . $instance['InstanceId'] . PHP_EOL;
        echo '---> Image ID: ' . $instance['ImageId'] . PHP_EOL;
        echo '---> Private Dns Name: ' . $instance['PrivateDnsName'] . PHP_EOL;
        echo '---> Instance Type: ' . $instance['InstanceType'] . PHP_EOL;
        echo '---> Security Group: ' . $instance['SecurityGroups'][0]['GroupName'] . PHP_EOL;
    }

}

Victor's answer is great, but it wasn't working for me because I was missing one line:

$reservations=$result->toArray();

The Amazon PHP SDK 2 returns Guzzle Model objects for many things (including this), and they need to be converted to arrays before foreach will work. More info here:

http://guzzlephp.org/api/class-Guzzle.Service.Resource.Model.html

Tags:

Php

Amazon Ec2