示例#1
0
 public function setup($instanceIds)
 {
     $awsCloudWatch = new CloudWatch($this->config);
     $awsCloudWatch->terminateInstanceIfIdleForTooLong($instanceIds);
     $awsTags = new Tags($this->client);
     $awsTags->assignTagsToInstances($instanceIds, $this->testSuite);
     $instances = $this->client->describeInstances(array('InstanceIds' => $instanceIds));
     $host = $this->getHostFromDescribedInstances($instances);
     return $host;
 }
 public function getInstanceByHostname($hostname)
 {
     $instances = $this->client->describeInstances(array('Filters' => array(array('Name' => 'private-dns-name', 'Values' => array("*{$hostname}*")))))->get('Reservations');
     if (count($instances) === 0) {
         throw new Exception('No matching instance found');
     } elseif (count($instances) > 1) {
         var_dump($instances);
         exit;
         throw new Exception(count($instances) . ' instance(s) found');
     }
     return array_shift($instances[0]['Instances']);
 }
 /**
  * Gets public ip address of currently active spot instance
  * @param null $instanceId
  *
  * @return mixed
  * @throws \Exception
  */
 public function getIp($instanceId = null)
 {
     if ($instanceId == null) {
         $instanceId = $this->getActiveInstanceId();
         if ($instanceId == null) {
             throw new \Exception("Active instance not found to assign ip");
         }
     }
     $instances = $this->ec2Client->describeInstances(['Filters' => [['Name' => 'instance-id', 'Values' => [$instanceId]]]]);
     return $instances['Reservations'][0]['Instances'][0]['PublicIpAddress'];
 }
 /**
  * Fetch instance data.
  * @param array $regions
  * @param Credentials|null $credentials
  * @return array
  */
 protected function getInstancesData($regions = [], Credentials $credentials = null)
 {
     $result = [];
     foreach ($regions as $region) {
         $this->progress->setMessage("Fetching instances from {$region}...");
         $this->progress->advance();
         $ec2 = new Ec2Client(['version' => 'latest', 'region' => $region, 'credentials' => $credentials]);
         $instances = $ec2->describeInstances();
         $path = "Reservations[].Instances[].{name: Tags[?Key == 'Name'].Value | [0], id: InstanceId, state: State.Name, ip: PublicIpAddress}";
         $result = array_merge($result, $instances->search($path));
     }
     return $result;
 }
 public function handle()
 {
     $this->info('Initializing Leader Selection...');
     // Only do cron setup if environment is configured to use it (This way we don't accidentally run on workers)
     if (getenv('USE_CRON') == 'true') {
         //check to see if we are in an instance
         $ch = curl_init('http://169.254.169.254/latest/meta-data/instance-id');
         //magic ip from AWS
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         if ($result = curl_exec($ch)) {
             $this->info('Instance ID: ' . $result);
             // Get this instance metadata so we can find the environment it's running in
             $tags = $info = $this->ecClient->describeInstances(['Filters' => [['Name' => 'instance-id', 'Values' => [$result]]]])->get('Reservations')[0]['Instances'][0]['Tags'];
             // Get environment name
             $environmentName = F\first($tags, function ($tagArray) {
                 return $tagArray['Key'] == 'elasticbeanstalk:environment-name';
             })['Value'];
             $this->info('Environment: ' . $environmentName);
             $this->info('Getting Instances with Environment: ' . $environmentName);
             // Get instances that have this environment tagged
             $info = $this->ecClient->describeInstances(['Filters' => [['Name' => 'tag-value', 'Values' => [$environmentName]]]]);
             $instances = F\map($info->get('Reservations'), function ($i) {
                 return current($i['Instances']);
             });
             $this->info('Getting potential instances...');
             // Only want instances that are running
             $candidateInstances = F\select($instances, function ($instanceMeta) {
                 return $instanceMeta['State']['Code'] == 16;
             });
             $leader = false;
             if (!empty($candidateInstances)) {
                 //there are instances running
                 if (count($candidateInstances) > 1) {
                     // if there is more than one we sort by launch time and get the oldest
                     $this->info('More than one instance running, finding the oldest...');
                     $oldestInstance = F\sort($candidateInstances, function ($left, $right) {
                         return $left['LaunchTime'] > $right['LaunchTime'];
                     })[0];
                 } else {
                     $this->info('Only one instance running...');
                     $oldestInstance = reset($candidateInstances);
                 }
                 if ($oldestInstance['InstanceId'] == $result) {
                     // if this instance is the oldest instance it's the leader
                     $leader = true;
                 }
             } else {
                 $this->info('No candidate instances found. \'O Brave New World!');
                 $leader = true;
             }
             // No leader is running so we'll setup this one as the leader
             // and create a cron entry to run the scheduler
             if ($leader) {
                 $this->info('We are the Leader! Initiating Cron Setup');
                 $this->call('system:start:cron');
             } else {
                 // Instance was found, don't do any cron stuff
                 $this->info('We are not a leader instance :( Maybe next time...');
                 $this->info('Leader should be running on Instance ' . $leader['InstanceId']);
             }
             $this->info('Leader Selection Done!');
         } else {
             // Probably be run from your local machine
             $this->error('Did not detect an ec2 environment. Exiting.');
         }
     } else {
         $this->info('USE_CRON env var not set. Exiting.');
     }
 }
示例#6
0
 * PHP versions 5
 * @package		develop
 * @author		Yoshikazu Suzuki <*****@*****.**>
 * @copyright	2015 bellact
 * 
 * ※要事前準備 : aws configure
*/
//error_reporting(0);
date_default_timezone_set('Asia/Tokyo');
require_once 'vendor/autoload.php';
use Aws\Ec2\Ec2Client;
use Aws\Rds\RdsClient;
$now = Date('Y-m-d H:i:s');
//EC2情報取得
$ec2 = new Ec2Client(['region' => 'ap-northeast-1', 'version' => '2015-04-15']);
$instances = $ec2->describeInstances();
$columns = sprintf("InstanceId," . "ImageId," . "State.Name," . "PublicDnsName," . "KeyName," . "InstanceType," . "LaunchTime," . "Placement.AvailabilityZone," . "SubnetId," . "VpcId," . "PrivateIpAddress," . "PublicIpAddress," . "SecurityGroups[].GroupId");
$ec2_infos = $instances->search('Reservations[].Instances[].[' . $columns . ']');
$ec2_outlist = array();
$index_list = array('instance_id', 'image_id', 'dns_name', 'kname', 'instance_type', 'launch_dtime', 'region', 'subnet_id', 'vpc_id', 'local_ip', 'public_ip', 'security_group', 'status');
$ec2_outlist[] = '| ' . implode(' | ', $index_list) . ' |';
foreach ($ec2_infos as $info) {
    $launch_dtime = $info[6]->__toString();
    $launch_dtime = substr($launch_dtime, 0, 19);
    $launch_dtime = str_replace('T', ' ', $launch_dtime);
    $dt = new DateTime($launch_dtime, new DateTimeZone('UTC'));
    $launch_dtime = $dt->setTimeZone(new DateTimeZone('Asia/Tokyo'))->format('Y-m-d H:i:s');
    $tmp = array('instance_id' => $info[0], 'image_id' => $info[1], 'dns_name' => $info[3], 'kname' => $info[4], 'instance_type' => $info[5], 'launch_dtime' => $launch_dtime, 'region' => $info[7], 'subnet_id' => $info[8], 'vpc_id' => $info[9], 'local_ip' => $info[10], 'public_ip' => $info[11], 'security_group' => implode(',', $info[12]), 'status' => $info[2]);
    $ec2_outlist[] = '| ' . implode(' | ', $tmp) . ' |';
}
print "###EC2\n";
示例#7
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $configuration = $this->configuration->read();
     if (!$configuration) {
         $output->writeln('<error>No credentials stored. Run "ec2ssh config" first.</error>');
         return 1;
         // stops the runner from continuing
     }
     $client = new Ec2Client(['credentials' => ['key' => $configuration['accessKey'], 'secret' => $configuration['secretKey']], 'region' => $configuration['region'], 'version' => 'latest']);
     $response = $client->describeInstances();
     $instances = [];
     foreach ($response['Reservations'] as $reservation) {
         foreach ($reservation['Instances'] as $instance) {
             $key = $instance['KeyName'];
             $id = $instance['InstanceId'];
             $dns = $instance['PublicDnsName'];
             $zone = $instance['Placement']['AvailabilityZone'];
             $type = $instance['InstanceType'];
             $name = '';
             $role = '';
             $system = '';
             foreach ($instance['Tags'] as $tag) {
                 if ($tag['Key'] === 'System') {
                     $system = $tag['Value'];
                 }
                 if ($tag['Key'] === 'Name') {
                     $name = $tag['Value'];
                 }
                 if ($tag['Key'] === 'Role') {
                     $role = $tag['Value'];
                 }
             }
             $instances[$role . ' ' . $id] = compact('key', 'id', 'dns', 'zone', 'type', 'name', 'role', 'system');
         }
     }
     ksort($instances);
     $instances = array_values($instances);
     $table = new Table($output);
     $table->setHeaders(['', 'Role', 'ID', 'Size', 'DNS']);
     $lastRole = null;
     foreach ($instances as $i => $instance) {
         if ($instance['role'] !== $lastRole && $lastRole !== null) {
             $table->addRow(new TableSeparator());
         }
         $table->addRow([$i + 1, '<options=bold>' . $instance['role'] . '</>', $instance['id'], $instance['type'], $instance['dns']]);
         $lastRole = $instance['role'];
     }
     $table->render();
     $range = range(1, count($instances));
     $question = (new Question('Which box to SSH to? '))->setAutocompleterValues($range)->setValidator(function ($value) use($range) {
         if (!in_array($value, $range)) {
             throw new \Exception('Invalid choice');
         }
         return $value;
     });
     $choice = $this->getHelper('question')->ask($input, $output, $question);
     $instance = $instances[$choice - 1];
     $name = $instance['role'] . ' (' . $instance['id'] . ')';
     file_put_contents('/tmp/ec2ssh-tmp-server', 'ubuntu@' . $instance['dns']);
     $output->writeln('');
     $output->writeln('<info>Connecting to ' . $name . '...</info>');
 }