#!/usr/bin/php
<?php
/**
* @file
* @brief ec2-describe-instances-sample
*
* @note
* - encoding: utf-8
* - 環境
*   - OS: CentOS release 6.3 x86_64
*   - PHP: 5.3.3
*   - AWS SDK for PHP: 1.5.11 http://aws.amazon.com/jp/sdkforphp/
*/
require_once('/opt/aws/lib/php/sdk.class.php');

define('AWS_ACCESS_KEY', '');
define('AWS_SECRET_KEY', '');

mb_http_input('pass');
mb_http_output('pass');
mb_internal_encoding('utf-8');

$ec2 = new AmazonEC2(array('key' => AWS_ACCESS_KEY, 'secret' => AWS_SECRET_KEY));
$ec2->set_region(AmazonEC2::REGION_APAC_NE1);
$ret = $ec2->describe_instances( array(
	'Filter' => array(
		array("Name" => "instance-state-name", "Value" => array("running", "stopped") ), // Valid Values: pending | running | shutting-down | terminated | stopping | stopped
//		array("Name" => "instance-id", "Value" => "i-xxxxxxxx"), // インスタンスを指定する場合
//		array("Name" => "tag:Name", "Value" => "*.example.com"), // tagを指定する場合
	)
) );

if( !$ret->isOK() ) {
	echo "Error: [" . $ret->body->Errors->Error->Code . "] " . $ret->body->Errors->Error->Message;
	exit(1);
}

// 複数インスタンス同時起動した場合は、reservationSet->itemが複数ある
foreach ($ret->body->reservationSet->item as $reservationSet_item) {
	foreach($reservationSet_item->instancesSet->item as $instancesSet_item){
		$instanceId = $instancesSet_item->instanceId;
		$tag_name = '';
		if(isset($instancesSet_item->tagSet->item)) {
			foreach($instancesSet_item->tagSet->item as $tag){
				$tag_value = trim($tag->value);
				if($tag->key == "Name" && $tag->value != null && $tag_value != ""){
					$tag_name = $tag_value;
					break;
				}
			}
		}
		echo "instanceId: $instanceId, tag: $tag_name\n";
	}
}
