- $ aws elb describe-load-balancers --load-balancer-name "XXX"
- $ aws ec2 describe-instances --instance-ids "XXX"
為了高移植性,我採用下載 aws.phar 的模式:
- 簡介
- 安裝
- http://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html
- http://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.phar
- 文件
- http://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Ec2.Ec2Client.html
- http://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.ElasticLoadBalancing.ElasticLoadBalancingClient.html
- 除錯
- 對 PHP 5.3 的來說,有機會碰到 phar 讀進來就 syntax error (yield),這時就改去下載 2.8 版吧
- 錯誤訊息
- PHP Parse error: syntax error, unexpected T_VARIABLE in phar
- https://github.com/aws/aws-sdk-php/releases
<?php
require 'aws.phar';
$config = array(
'version' => 'latest',
'credentials' => array(
'key' => 'key',
'secret' => 'secret',
),
'region' => 'us-west-2',
);
列出 EC2 - m1.small instance:
<?php
$ec2Client = Aws\Ec2\Ec2Client::factory($config);
// http://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Ec2.Ec2Client.html
$result = $ec2Client->DescribeInstances(array(
'Filters' => array(
array('Name' => 'instance-type', 'Values' => array('m1.small')),
)
));
print_r($result);
想要列出 EC2 - 指定 Load Balancer 下的機器:
<?php
$client = Aws\ElasticLoadBalancing\ElasticLoadBalancingClient::factory($config);
$result = $client->DescribeLoadBalancers( array(
'LoadBalancerNames' => array('Load Balancer Name')
));
print_r($result['LoadBalancerDescriptions'][0]['Instances']);
print_r($result);
其中,雖然 $result 都是 Aws\Result Object ,且裡頭都是 [data:Aws\Result:private] => Array ,但可以透過 array access 的方式去存取囉。
接下來就可以試試連續動作,從 ELB 得知機器後,再得到機器的 public ip:
<?php
require 'aws.phar';
$ELB_NAME = 'XXXX';
$client = Aws\ElasticLoadBalancing\ElasticLoadBalancingClient::factory($config);
$result = $client->DescribeLoadBalancers( array('LoadBalancerNames' => array($ELB_NAME)));
if (isset($result['LoadBalancerDescriptions']) && is_array($result['LoadBalancerDescriptions']) && count($result['LoadBalancerDescriptions']) && isset($result['LoadBalancerDescriptions'][0]['Instances'])) {
$instances = $result['LoadBalancerDescriptions'][0]['Instances'];
//print_r($instances);
$ec2_id = array();
foreach($instances as $ec2)
if (isset($ec2['InstanceId']))
array_push($ec2_id, $ec2['InstanceId']);
if (count($ec2_id) > 0) {
$client = Aws\Ec2\Ec2Client::factory($setup);
$result = $client->DescribeInstances(array(
'Filters' => array(
array('Name' => 'instance-id', 'Values' => $ec2_id),
)
));
}
$public_ip = array();
if (isset($result['Reservations'])) {
foreach($result['Reservations'] as $target) {
//print_r($target['Instances'][0]['PublicIpAddress']);
array_push($public_ip, $target['Instances'][0]['PublicIpAddress']);
}
}
//print_r($result['Reservations']);
print_r($public_ip);
}
沒有留言:
張貼留言