LoginSignup
2
2

More than 5 years have passed since last update.

AWS SDK for PHPを使って自ホストのEIPを取得するよ

Last updated at Posted at 2015-02-03
Util.php
<?php
namespace Model\Common\Util;

use Aws\Ec2\Ec2Client;

class Ec2Util
{
    private $ec2;
    private $ips = array();

    public function __construct($key, $secret, $region)
    {
        try {
             $this->ec2 = Ec2Client::factory(array(
                 'key' => $key,
                 'secret' => $secret,
                 'region' => $region
             ));
             $response = $this->ec2->describeAddresses();
             if ($response) {
                 $instances = $response->toArray();
                 $address = $instances['Addresses'];
                 foreach ($address as $data) {
                     $this->ips[$data['PrivateIpAddress']] = $data['PublicIp'];
                 }
             }
         } catch (\Exception $e) {
         }
    }

    public function getPublicIp($privateIp)
    {
        if (isset($this->ips[$privateIp])) {
            return $this->ips[$privateIp];
        } else {
            return '';
        }
    }
}

もちろんComposerでSDKをいれておく

composer.json
{
    "require" : {
        "aws/aws-sdk-php" : "2.*"
    }
}

Ec2Utilは適当にインスタンス化して(必要な情報を渡して)
getPublicIpメソッドを呼べばOK

引数のIPはプライベートIP
PrivateなIPを簡単に取得できるはず($_SERVER[ 'SERVER_ADDR' ]とか?)

2
2
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
2
2