Get a list of running ec2 instances programmatically

amazon ec2amazon-web-services

Hi i have started with aws and found out that we can get a list of running servers with the aws php sdk. Is there any other way to get the list of all ec2 instances? after getting the list i want to sync the data from one main instances to all the instances. Something like a button click can also do the operation. Are rsync, incron the only options, or it can be done by aws php sdk also. Please provide some tutorial links.

Best Answer

I think you would use the AWS php sdk;
http://aws.amazon.com/sdkforphp/

Run through the getting started guide to setup your keys;
http://aws.amazon.com/articles/4261?_encoding=UTF8&jiveRedirect=1

And then use the describe_instances function to collect an array of instances;
http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#m=AmazonEC2/describe_instances

It looks like you could either construct and filter to return only running instances, or then loop over the returned like to to get more detailed information using the describe_instance_status function;
http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#m=AmazonEC2/describe_instance_status

Something tlike the following will work...

<?php
require_once "/home/XXX/src/php-aws-sdk-1.5.3/sdk.class.php";
CFCredentials::set(array(
    'testing' => array(
        'key' => 'XXX',
        'secret' => '+YYY+',
        'default_cache_config' => '',
        'certificate_authority' => false
    ),
    // Specify a default credential set to use if there are more than one.
    '@default' => 'testing'
));
$ec2 = new AmazonEC2();
$response = $ec2->describe_instances(array( "Filter" => array(
  array("Name"=>"instance-state-code", "Value" => "16"))));
foreach($response as $res){
 var_dump( $res );
}
?>

instance state code 16 is for "running"