capistranoで特定のELBに紐づくEC2 instanceに対してスクリプトを実行させたかったので、書きました。
参考URL(http://docs.aws.amazon.com/aws-sdk-php/v2/api/index.html)
まず、aws-sdk-phpは最新の3系を使用
composer.json
{
"require": {
"aws/aws-sdk-php": "3.3.3"
}
}
util_ec2.php
<?php
require_once('vendor/autoload.php');
use Aws\ElasticLoadBalancing\ElasticLoadBalancingClient;
use Aws\Ec2\Ec2Client;
class Util_Ec2 {
private $elb_client = null;
private $ec2_client = null;
function __construct() {
date_default_timezone_set("Asia/Tokyo");
$config = [
'version' => 'latest',
'region' => region,
'credentials' => [
'key' => access_key,
'secret' => secret_key,
]
];
$this->elb_client = new ElasticLoadBalancingClient($config);
$this->ec2_client = new Ec2Client($config);
}
public function get_instances() {
$elb_name = elb name;
$instance_ids = [];
$instances = $this->elb_client->describeInstanceHealth([
'LoadBalancerName'=> $elb_name
]);
foreach ($instances['InstanceStates'] as $instanceState) {
$instance_ids[] = $instanceState['InstanceId'];
}
$instances = $this->ec2_client->describeInstances([
'InstanceIds' => $instance_ids
]);
return $instances;
}
}
$util_ec2 = new Util_Ec2();
$instances = $util_ec2->get_instances();