LoginSignup
4
1

More than 5 years have passed since last update.

AWS SDK for PHPで特定のELBのEC2 instanceを取得

Last updated at Posted at 2016-02-01

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();
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1