我无法弄清楚如何查看 CloudWatch 中正在运行的实例数量。所以我决定通过 AWS PHP SDK 自己测量它们,结果证明它比我想象的要容易得多。
这是我的 cron 命令中的代码,供任何想知道的人使用:
public function fire(){
$client = AWS::get('CloudWatch');
$containers = [
'production',
'staging'
];
foreach($containers as $container){
$client->putMetricData([
'Namespace' => 'Company',
'MetricData' => [
[
'MetricName' => 'NumberOfInstances',
'Timestamp' => time(),
'Value' => $this->_getInstanceCount($container),
'Dimensions' => [
[
'Name' => 'Environment',
'Value' => AwsHelper::getEnvironment($container)
],
[
'Name' => 'Container',
'Value' => $container
]
]
]
]
]);
}
}
protected function _getInstanceCount($container){
$beanstalk = AWS::get('ElasticBeanstalk');
$resources = $beanstalk->describeEnvironmentResources([
'EnvironmentName' => AwsHelper::getEnvironment($container)
])->get('EnvironmentResources');
return count($resources['Instances']);
}
AwsHelper 是一个自定义类,此处仅用于检索容器的环境。AWS 是用于 PHP 的官方 AWS 开发工具包:http: //aws.amazon.com/sdkforphp/
我使用了这些文档:
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.CloudWatch.CloudWatchClient.html#_putMetricData