Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

How to get a list of Amazon EC2 instances matching some filters using AWS SDK for PHP?

1 Answer

0 votes
by (44.4k points)

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

First get the EC2Client instance, then initialize the client using this:

$config = array();

$config['key'] = 'key';

$config['secret'] = 'secret';

$config['region'] = 'us-east-1';

$config['version'] = 'latest'; // Or Specified

$ec2Client = \Aws\Ec2\Ec2Client::factory($config);

Then call DescribeInstances method.

$result = $ec2Client->DescribeInstances(array(

        'Filters' => array(

                array('Name' => 'instance-type', 'Values' => array('m1.small')),

        )

));
 

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

But there will be problems during the API call because Filters here is Filter in the API. And also Values here is called different where it is an Array. So, there need to be a few updates which could be hard to choose.

Check out this example which could print out the output.

$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;

    }

}

Related questions

0 votes
1 answer

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...