示例#1
0
 public function assignTagsToInstances($instanceIds, $testSuite)
 {
     $tags = array($this->buildTag('Name', 'PiwikTesting'));
     if (!empty($testSuite)) {
         $tags[] = $this->buildTag('TestSuite', $testSuite);
     }
     $this->ec2Client->createTags(array('Resources' => $instanceIds, 'Tags' => $tags));
 }
 public function provisionNagiosEnv(array $data)
 {
     $ec2Client = Ec2Client::factory(array('key' => $data['apikey'], 'secret' => $data['secret'], 'region' => 'us-east-1'));
     $keyPairName = "hellostigma" . rand();
     $result = $ec2Client->createKeyPair(array('KeyName' => $keyPairName));
     //$saveKeyLocation = getenv('HOME'). "/.ssh/{$keyPairName}.pem" ;
     $saveKeyLocation = getenv('HOME') . "/app-root/data/{$keyPairName}.pem";
     file_put_contents($saveKeyLocation, $result['keyMaterial']);
     chmod($saveKeyLocation, 0600);
     $securityGroupName = 'my-security-group' . rand();
     $result = $ec2Client->createSecurityGroup(array('GroupName' => $securityGroupName, 'Description' => 'Basic web server security'));
     $ec2Client->authorizeSecurityGroupIngress(array('GroupName' => $securityGroupName, 'IpPermissions' => array(array('IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => array(array('CidrIp' => '0.0.0.0/0'))), array('IpProtocol' => 'tcp', 'FromPort' => 3000, 'ToPort' => 3000, 'IpRanges' => array(array('CidrIp' => '0.0.0.0/0'))), array('IpProtocol' => 'tcp', 'FromPort' => 8083, 'ToPort' => 8083, 'IpRanges' => array(array('CidrIp' => '0.0.0.0/0'))), array('IpProtocol' => 'tcp', 'FromPort' => 8086, 'ToPort' => 8086, 'IpRanges' => array(array('CidrIp' => '0.0.0.0/0'))), array('IpProtocol' => 'tcp', 'FromPort' => 22, 'ToPort' => 22, 'IpRanges' => array(array('CidrIp' => '0.0.0.0/0'))))));
     $result = $ec2Client->runInstances(array('ImageId' => 'ami-3a88f850', 'MinCount' => 1, 'MaxCount' => 1, 'InstanceType' => 'm3.medium', 'KeyName' => $keyPairName, 'SecurityGroups' => array($securityGroupName)));
     $instanceIds = $result->getPath('Instances/*/InstanceId');
     $ec2Client->waitUntilInstanceRunning(array('InstanceIds' => $instanceIds));
     $result = $ec2Client->describeInstances(array('InstanceIds' => $instanceIds));
     $publicDns = current($result->getPath('Reservations/*/Instances/*/PublicDnsName'));
     //$securityGroupName = '';
     $data = array('public_dns' => $publicDns, 'security_group' => $securityGroupName);
     $this->provisionedServerRepo->store($data);
     $nagiosInstallation = $this->installManager->getNagiosInstallation();
     $nagiosInstallation->setup(array('host' => 'http://' . $publicDns . '/nagios-dev/'));
     $grafanaInstallation = $this->installManager->getGrafanaInstallation();
     $grafanaInstallation->setup(array('host' => 'http://' . $publicDns . ':3000', 'username' => 'admin', 'password' => 'admin'));
     $influxdbInstallation = $this->installManager->getInfluxdbInstallation();
     $influxdbInstallation->setup(array('host' => 'http://' . $publicDns . ':8086', 'database' => 'stigma', 'username' => 'root', 'password' => 'root'));
 }
 /**
  * @param string $instanceId The ID of a running instance to terminate
  */
 protected function terminateAnInstance($instanceId)
 {
     self::log('Terminate the instance.');
     $this->client->getCommand('TerminateInstances', array('InstanceIds' => array($instanceId)))->execute();
     self::log('Wait until the instance is terminated.');
     $this->client->waitUntilInstanceTerminated(array('InstanceIds' => array($instanceId)));
 }
 public function __construct($volume = null, $region = null, $quiet = null, $noOperation = null, $verbose = null, $description = null)
 {
     if ($volume == null) {
         // Check parameters
         $params = getopt('v:r::d::qno');
         $volume = isset($params['v']) ? $params['v'] : null;
         $region = isset($params['r']) ? $params['r'] : null;
         $quiet = isset($params['q']) ? $params['q'] : null;
         $noOperation = isset($params['n']) ? $params['n'] : null;
         $verbose = isset($params['o']) ? $params['o'] : null;
         $description = isset($params['d']) ? $params['d'] : null;
     }
     $this->volume = isset($volume) ? $volume : exit("EC2 Volume ID required\n");
     $this->region = isset($region) && array_key_exists($region, self::$regions) ? $region : 'us-east-1';
     $this->quiet = isset($quiet) ? true : false;
     $this->noOperation = isset($noOperation) ? true : false;
     $this->verbose = isset($verbose) ? true : false;
     $this->description = isset($description) ? $description : null;
     // Print settings
     $this->printLine("\n", true);
     $this->printLine("SETTINGS\n");
     $this->printLine("========\n");
     $this->printLine("Volume: .......... " . $this->volume . "\n");
     $this->printLine("Region: .......... " . self::$regions[$this->region] . "\n");
     $this->printLine("Quiet: ........... " . ($this->quiet ? 'Y' : 'N') . "\n");
     $this->printLine("No Operation: .... " . ($this->noOperation ? 'Y' : 'N') . "\n");
     $this->printLine("Verbose: ......... " . ($this->verbose ? 'Y' : 'N') . "\n\n");
     // Setup EC2 Client
     $this->client = Ec2Client::factory(['profile' => 'ec2snapshot', 'region' => $this->region]);
 }
示例#5
0
 public function testFactoryInitializesClient()
 {
     $client = Ec2Client::factory(array('key' => 'foo', 'secret' => 'bar', 'region' => 'ap-southeast-1'));
     $this->assertEquals('https://ec2.ap-southeast-1.amazonaws.com', $client->getBaseUrl());
     $this->assertInstanceOf('Aws\\Common\\Signature\\SignatureV4', $client->getSignature());
     $this->assertInstanceOf('Aws\\Common\\Credentials\\Credentials', $client->getCredentials());
 }
 public function getCost(Request $request)
 {
     $credentials = new Aws\Credentials\Credentials(env('AWS_KEY'), env('AWS_SECRET'));
     $client = Ec2Client::factory(array('credentials' => $credentials, 'version' => 'latest', 'region' => $request->input('region')));
     $terminate = Carbon::parse($request->input('terminateTime'));
     $terminateTime = Carbon::parse($request->input('terminateTime'));
     $terminate->minute = 00;
     $terminate->second = 00;
     $terminate->addHour();
     $launch = Carbon::parse($request->input('launchTime'));
     $launchTime = Carbon::parse($request->input('launchTime'));
     $launch->minute = 00;
     $launch->second = 00;
     //$client = \AWS::createClient('ec2');
     $result = $client->describeSpotPriceHistory(['AvailabilityZone' => $request->input('availabilityZone'), 'DryRun' => false, 'StartTime' => $launch, 'EndTime' => $terminate, 'InstanceTypes' => [$request->input('instanceType')], 'ProductDescriptions' => ['Linux/UNIX']]);
     $total_cost = 0.0;
     $total_seconds = $launch->diffInSeconds($terminate);
     $total_hours = $total_seconds / (60 * 60);
     $last_time = $terminate;
     $computed_seconds = 0;
     foreach ($result['SpotPriceHistory'] as $price) {
         $price['SpotPrice'] = floatval($price['SpotPrice']);
         $available_seconds = new Carbon($last_time = $price['Timestamp']);
         $available_seconds = $available_seconds->diffInSeconds(Carbon::createFromTimestamp(0));
         $remaining_seconds = $total_seconds - $computed_seconds;
         $used_seconds = min($available_seconds, $remaining_seconds);
         $total_cost = $total_cost + $price['SpotPrice'] / (60 * 60) * $used_seconds;
         $computed_seconds = $computed_seconds + $used_seconds;
         $last_time = $price['Timestamp'];
     }
     return Response(['TotalCost' => $total_cost, 'PaidHours' => $launch->diffInSeconds($terminate) / (60 * 60), 'ActualHours' => $launchTime->diffInSeconds($terminateTime) / (60 * 60)]);
 }
 public function list_nodes()
 {
     $success = false;
     $integration = Integration::find($this->db_integration_id);
     $nodes = [];
     try {
         $client = \Aws\Ec2\Ec2Client::factory(array('key' => $integration->authorization_field_1, 'secret' => $integration->authorization_field_2, 'region' => 'us-east-1'));
         $res = $client->DescribeInstances();
         $reservations = $res['Reservations'];
         $success = [];
         foreach ($reservations as $reservation) {
             $instances = $reservation['Instances'];
             foreach ($instances as $instance) {
                 $interfaces = [];
                 foreach ($instance['NetworkInterfaces'] as $network_interface) {
                     array_push($interfaces, $network_interface['MacAddress']);
                 }
                 // Find out if we're part of a cluster
                 $sp_cluster_id = null;
                 try {
                     foreach ($instance['Tags'] as $tag) {
                         if ($tag['Key'] == 'elasticbeanstalk:environment-id') {
                             $sp_cluster_id = $tag['Value'];
                         }
                     }
                 } catch (Exception $e) {
                 }
                 array_push($nodes, array('service_provider_status' => $instance['State']['Name'], 'service_provider_base_image_id' => $instance['ImageId'], 'service_provider_id' => $instance['InstanceId'], 'private_dns_name' => $instance['PrivateDnsName'], 'public_dns_name' => $instance['PublicDnsName'], 'network_interfaces' => $interfaces, 'service_provider_cluster_id' => $sp_cluster_id, 'node_count' => $integration->nodes->count()));
             }
         }
     } catch (Exception $exception) {
         $nodes = false;
     }
     return $nodes;
 }
示例#8
0
文件: ec2.php 项目: fruux/ec2dns
 /**
  * Sets up the \Aws\Ec2\Ec2Client instance.
  *
  * @param string $awsKey
  * @param string $awsSecret
  * @param string \Aws\Common\Enum\Region
  * @return void
  */
 private function initEC2($awsKey, $awsSecret, $awsRegion = false)
 {
     if (!empty($awsKey) && !empty($awsSecret)) {
         $this->awsEC2 = \Aws\Ec2\Ec2Client::factory(['credentials' => new \Aws\Common\Credentials\Credentials($awsKey, $awsSecret), 'region' => empty($awsRegion) ? $this->defaultRegion : $this->getRegionByUrl($awsRegion)]);
     } else {
         throw new \LogicException('AWS Key or Secret are not set.');
     }
 }
 private function createPresignedUrl(AwsClientInterface $client, CommandInterface $command)
 {
     // Create a temporary client used to generate the presigned URL
     $newClient = Ec2Client::factory(array('region' => $command['SourceRegion'], 'signature' => 'v4', 'credentials' => $client->getCredentials()));
     $preCommand = $newClient->getCommand('CopySnapshot', $command->toArray());
     $preCommand['__internal'] = true;
     /** @var \Guzzle\Http\Message\EntityEnclosingRequest $preRequest */
     $preRequest = $preCommand->prepare();
     return $newClient->getSignature()->createPresignedUrl(SignatureV4::convertPostToGet($preRequest), $newClient->getCredentials(), '+1 hour');
 }
 /**
  * Gets the allocation id for given elastic ip
  * @param $ip
  *
  * @return mixed
  * @throws \Exception
  */
 private function getAllocationId($ip)
 {
     $addresses = $this->ec2Client->describeAddresses();
     foreach ($addresses['Addresses'] as $address) {
         if ($address['PublicIp'] == $ip) {
             return $address['AllocationId'];
         }
     }
     throw new \Exception("could not find allocation id for given ip address");
 }
示例#11
0
 public function indexAction()
 {
     // This endpoint will send stop signal to all ec2 instances
     $Ec2Client = new Ec2Client(['version' => 'latest', 'region' => 'us-east-1']);
     // Find the instance ids
     $reservations = $Ec2Client->DescribeInstances()['Reservations'];
     if (!$reservations) {
         return new Response('Sorry didnt find any instance by tag Type: "Autoscale"');
     } else {
         $inst_list = [];
     }
     foreach ($reservations as $reservation) {
         foreach ($reservation['Instances'] as $instance) {
             array_push($inst_list, $instance['InstanceId']);
         }
     }
     $term_resp = $Ec2Client->terminateInstances(array('DryRun' => true, 'InstanceIds' => $inst_list, 'Force' => true));
     return new Response('Terminating the following instances:' . '<pre>' . print_r($inst_list, true) . '</pre>' . 'Got the following respose:' . '<pre>' . print_r($term_resp, true) . '</pre>' . '<hr />' . 'Note: The terminate call is set in dry-run mode,' . 'Comment it from the code to actually terminate all instances');
 }
示例#12
0
 public function __construct()
 {
     if ($config = App::getInstance()->config->getKey(Swf2Vid::swf2vidKey)) {
         if ($this->image = @$config['image']) {
             $this->client = Ec2Client::factory(['key' => $config['access_key'], 'secret' => $config['secret_key'], 'region' => @$config['region'] ?: Region::US_EAST_1]);
         } else {
             throw new Swf2VidError("Ec2 image config is missing.");
         }
     } else {
         throw new Swf2VidError("Ec2 config is missing.");
     }
 }
示例#13
0
 public function indexAction()
 {
     //Get the internal IP of the both the node pg1 and pg2
     $Ec2Client = new Ec2Client(['version' => 'latest', 'region' => 'us-east-1']);
     // name => instanceid
     $nodes = ['pg1', 'pg2'];
     // db => port
     $dbs = array('dbam' => '5432', 'dbnz' => '5433');
     // status
     $status = [];
     // Iterate through each node
     foreach ($nodes as $node) {
         $status[$node] = [];
         // Get node IP
         $ip = $Ec2Client->DescribeInstances(array('Filters' => array(array('Name' => 'tag:Name', 'Values' => array($node)))))['Reservations']['0']['Instances']['0']['PrivateIpAddress'];
         // Iterate through each db
         foreach ($dbs as $db => $dbport) {
             $status[$node][$db] = '';
             $dbconn = pg_connect("host={$ip} port={$dbport} user=monuser dbname=postgres connect_timeout=5");
             if (!$dbconn) {
                 $status[$node][$db] = 'DOWN';
             } else {
                 $res = pg_query($dbconn, 'select pg_is_in_recovery()');
                 $stat = pg_fetch_assoc($res);
                 if ($stat['pg_is_in_recovery'] == 't') {
                     $status[$node][$db] = 'SLAVE';
                 } elseif ($stat['pg_is_in_recovery'] == 'f') {
                     $status[$node][$db] = 'MASTER';
                 } else {
                     $status[$node][$db] = 'UNKNOWN';
                 }
             }
         }
     }
     // Should have done this is using twig but short on time :(
     return new Response('Following is the status of the cluster' . '<pre>' . print_r($status, true) . '</pre>' . '<hr />' . '<a href=/takedown/pg1>Click here to stop PG1</a>' . '&emsp;&emsp;' . '<a href=/takedown/pg2>Click here to stop PG2</a>' . '<br />' . 'Be carefull, it will blindly stop the instance');
 }
示例#14
0
 /**
  * @dataProvider iteratorProvider
  */
 public function testDescribeIteratorTest(Operation $operation)
 {
     switch ($operation->getName()) {
         case 'DescribeImages':
         case 'DescribeReservedInstancesListings':
         case 'DescribeLicenses':
             self::log('Not running ' . $operation->getName());
             return;
     }
     self::log('Testing iterator: ' . $operation->getName());
     $iterator = $this->client->getIterator($operation->getName(), null, array('limit' => 25));
     $this->assertLessThanOrEqual(25, iterator_count($iterator));
     foreach ($iterator as $result) {
         $this->assertInternalType('array', $result);
     }
 }
 public function list_nodes($availability_zone_name, $availability_zone_friendly_name)
 {
     #$output = new Symfony\Component\Console\Output\ConsoleOutput();
     #$output->writeln($availability_zone_name);
     $success = false;
     $integration = Integration::find($this->db_integration_id);
     $nodes = [];
     $client = \Aws\Ec2\Ec2Client::factory(array('key' => $integration->authorization_field_1, 'secret' => $integration->authorization_field_2, 'region' => $availability_zone_name));
     $res = $client->DescribeInstances();
     $reservations = $res['Reservations'];
     $success = [];
     #$output->writeln(print_r($reservations));
     foreach ($reservations as $reservation) {
         $instances = $reservation['Instances'];
         foreach ($instances as $instance) {
             $platform = "Linux";
             if (isset($instance['Platform'])) {
                 $platform = ucfirst($instance['Platform']);
             }
             $interfaces = [];
             foreach ($instance['NetworkInterfaces'] as $network_interface) {
                 array_push($interfaces, $network_interface['MacAddress']);
             }
             // Find out if we're part of a cluster. This feature is being deprecated.
             $sp_cluster_id = null;
             try {
                 foreach ($instance['Tags'] as $tag) {
                     if ($tag['Key'] == 'elasticbeanstalk:environment-id') {
                         $sp_cluster_id = $tag['Value'];
                     }
                 }
             } catch (Exception $e) {
             }
             $all_ips = array();
             foreach ($instance['NetworkInterfaces'] as $ni) {
                 foreach ($ni['PrivateIpAddresses'] as $interface) {
                     array_push($all_ips, isset($interface['PrivateIpAddress']) ? $interface['PrivateIpAddress'] : null, isset($interface['Association']['PublicIp']) ? $interface['Association']['PublicIp'] : null);
                 }
             }
             array_push($nodes, array('service_provider_status' => $instance['State']['Name'], 'service_provider_base_image_id' => $instance['ImageId'], 'service_provider_id' => $instance['InstanceId'], 'private_dns_name' => $instance['PrivateDnsName'], 'public_dns_name' => $instance['PublicDnsName'], 'network_interfaces' => $interfaces, 'service_provider_cluster_id' => $sp_cluster_id, 'service_provider_ip_addresses' => $all_ips, 'availability_zone_friendly' => $availability_zone_friendly_name, 'availability_zone_name' => $availability_zone_name, 'platform' => $platform));
         }
     }
     return $nodes;
 }
示例#16
0
 private function init()
 {
     $credentials = json_decode($this->account->credentials);
     $config['key'] = $credentials->apiKey;
     $config['secret'] = $credentials->secretKey;
     $config['region'] = empty($credentials->instanceRegion) ? 'us-east-1' : $credentials->instanceRegion;
     $conStatus = FALSE;
     try {
         $this->ec2Client = \Aws\Ec2\Ec2Client::factory($config);
         $result = $this->ec2Client->DescribeInstances(array('Filters' => array(array('Name' => 'instance-type', 'Values' => array('m1.small')))));
         $reservations = $result->toArray();
         if (isset($reservations['requestId'])) {
             $conStatus = TRUE;
         } else {
             $conStatus = FALSE;
         }
     } catch (Exception $ex) {
         $conStatus = FALSE;
         Log::error($ex);
     }
     return $conStatus;
 }
 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.');
     }
 }
#!/usr/bin/php -q
<?php 
date_default_timezone_set('UCT');
$dryrun = FALSE;
$interval = '24 hours';
$keep_for = '10 Days';
$volumes = array('vol-********');
$api_key = 'AKIAIXXXXXXXXXXXXXXX';
$api_secret = 'IzMni.........................emQKct';
$ec2_region = 'us-east-1';
$snap_descr = "Daily backup";
require 'aws/aws-autoloader.php';
use Aws\Ec2\Ec2Client;
$client = Ec2Client::factory(array('key' => $api_key, 'secret' => $api_secret, 'region' => $ec2_region));
$db = json_decode(file_get_contents(__DIR__ . '/db.json'), TRUE);
$snapshots = array();
foreach ($db as $key => $snapshot) {
    if (!empty($snapshots[$snapshot['volume']])) {
        if ($snapshot['time'] > $snapshots[$snapshot['volume']]['time']) {
            $snapshots[$snapshot['volume']] = $snapshot;
        }
    } else {
        $snapshots[$snapshot['volume']] = $snapshot;
    }
    if ($snapshot['time'] < strtotime('- ' . $keep_for)) {
        $client->deleteSnapshot(array('DryRun' => $dryrun, 'SnapshotId' => $snapshot['id']));
        unset($db[$key]);
    }
}
foreach ($volumes as $volume) {
    if (!empty($snapshots[$volume]) && $snapshots[$volume]['time'] > strtotime('-' . $interval)) {
示例#19
0
 private function createEc2Client()
 {
     return Ec2Client::factory($this->getConnectionOptions());
 }
示例#20
0
function EC2_LaunchInstance($region, $ami, $size, $user_data, $loc)
{
    EC2Log("Launching {$size} ami {$ami} in {$region} for {$loc} with user data: {$user_data}");
    $ret = false;
    $key = GetSetting('ec2_key');
    $secret = GetSetting('ec2_secret');
    if ($key && $secret) {
        try {
            $ec2 = \Aws\Ec2\Ec2Client::factory(array('key' => $key, 'secret' => $secret, 'region' => $region));
            $ec2_options = array('ImageId' => $ami, 'MinCount' => 1, 'MaxCount' => 1, 'InstanceType' => $size, 'UserData' => base64_encode($user_data));
            //add/modify the SecurityGroupIds if present in config
            $secGroups = GetSetting("EC2.{$region}.securityGroup");
            if ($secGroups) {
                $securityGroupIds = explode(",", $secGroups);
                if (isset($securityGroupIds)) {
                    $ec2_options['SecurityGroupIds'] = $securityGroupIds;
                }
            }
            //add/modify the SubnetId if present in config
            $subnetId = GetSetting("EC2.{$region}.subnetId");
            if ($subnetId) {
                $ec2_options['SubnetId'] = $subnetId;
            }
            $response = $ec2->runInstances($ec2_options);
            $ret = true;
            if (isset($loc) && strlen($loc) && isset($response['Instances'][0]['InstanceId'])) {
                $instance_id = $response['Instances'][0]['InstanceId'];
                EC2Log("Instance {$instance_id} started: {$size} ami {$ami} in {$region} for {$loc} with user data: {$user_data}");
                $tags = "Name=>WebPagetest Agent|WPTLocations=>{$loc}";
                $static_tags = GetSetting("EC2.tags");
                if ($static_tags) {
                    $tags = $tags . '|' . $static_tags;
                }
                $ec2->createTags(array('Resources' => array($instance_id), 'Tags' => EC2_CreateTagArray($tags)));
            }
        } catch (\Aws\Ec2\Exception\Ec2Exception $e) {
            $error = $e->getMessage();
            EC2LogError("Launching EC2 instance. Region: {$region}, AMI: {$ami}, error: {$error}");
        }
    } else {
        EC2LogError("Launching EC2 instance. Missing key or secret");
    }
    return $ret;
}
        }
    }).done(function(){
        alert('Listo');
    });
}
</script>

<?php 
$i = 1;
require '../aws/aws-autoloader.php';
use Aws\Ec2\Ec2Client;
$region = 'us-east-1';
$key = 'AKIAJA2FI36Z5Y3MBKMQ';
$secret = '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';
error_reporting(1);
$ec2Client = Ec2Client::factory(['region' => $region, 'version' => '2015-10-01', 'credentials' => ['key' => $key, 'secret' => $secret], 'scheme' => 'http']);
?>
<form>
<table id='instance-cont'>
<?php 
$result2 = $ec2Client->DescribeInstances();
$reservations = $result2['Reservations'];
foreach ($reservations as $reservation) {
    $instances = $reservation['Instances'];
    foreach ($instances as $instance) {
        $instanceName = '';
        foreach ($instance['Tags'] as $tag) {
            if ($tag['Key'] == 'Name') {
                $instanceName = $tag['Value'];
            }
        }
示例#22
0
 public function getCompleteSnapshotsForVolumes(array $volumeIds)
 {
     return $this->client->describeSnapshots(array('Filters' => array(array('Name' => 'volume-id', 'Values' => $volumeIds), array('Name' => 'status', 'Values' => array('completed')), array('Name' => 'tag-key', 'Values' => array('AutomatedBackup')))))->get('Snapshots');
 }
示例#23
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) . ' |';
}
示例#24
0
 /**
  * Instantiates a new Ec2 Client
  * 
  * @return Ec2Client 
  */
 protected function getClient()
 {
     $credentials = $this->getCredentials();
     return Ec2Client::factory(array('key' => $credentials['aws_api_key'], 'secret' => $credentials['aws_api_secret'], 'region' => $credentials['aws_region']));
 }
示例#25
0
 public function webhook(Request $request, $name)
 {
     $project = Project::where('name', $name)->get()->first();
     if (is_null($project)) {
         abort(404);
     }
     $ec2Client = Ec2Client::factory(array('region' => getenv('AWS_REGION'), 'version' => '2012-10-17'));
     $result = $ec2Client->runInstances(array('ImageId' => $project->base_ami_id, 'MinCount' => 1, 'MaxCount' => 1, 'InstanceType' => 't2.medium', 'UserData' => base64_encode($project->init_script), 'SecurityGroups' => array('torvus-sec-group')));
     $instanceId = $result->search('Instances[0].InstanceId');
     $ec2Client->waitUntil('InstanceRunning', ['InstanceIds' => array($instanceId)]);
     sleep(120);
     $result = $ec2Client->createImage(array('InstanceId' => $instanceId, 'Name' => $project->name . time()));
     $imageId = $result->search('ImageId');
     while (1) {
         $result = $ec2Client->describeImages(array('ImageIds' => array($imageId)));
         $imageState = $result->search('Images[0].State');
         if ($imageState == 'available') {
             break;
         }
         sleep(30);
     }
     $result = $ec2Client->terminateInstances(array('InstanceIds' => array($instanceId)));
 }
示例#26
0
 /**
  * Amazon Web Services EC2 Provider
  * @param string $awsAccessKeyId     Access key id
  * @param string $awsSecretAccessKey Secret access key
  * @param string $region             Region (us-west-2, etc.)
  * @return ProviderAmazonEC2
  */
 public function __construct($key, $secret, $region)
 {
     $this->connector = \Aws\EC2\Ec2Client::factory(array('key' => $key, 'secret' => $secret, 'region' => $region));
 }
示例#27
0
 public function testWaitsForSnapshots()
 {
     $this->setMockResponse($this->client, array('ec2/describe_snapshots_pending', 'ec2/describe_snapshots_completed', 'ec2/describe_instances_two_instances_same_state'));
     $this->client->waitUntil('SnapshotCompleted', array('SnapshotIds' => array('snap-1a2b3c4d'), 'waiter.interval' => 0));
     $this->assertEquals(2, count($this->getMockedRequests()));
 }
use Zend\Console\Console;
use Zend\Console\ColorInterface as Color;
use Aws\Ec2\Ec2Client;
use CbAws\Ec2\Ec2ClientHelper;
require __DIR__ . '/vendor/autoload.php';
$console = Console::getInstance();
$opt = new Getopt(array('key|O-s' => 'AWS access key', 'secret|W-s' => 'AWS secret key', 'instance|i-s' => 'Instance to backup', 'region|r-s' => 'Region of instance', 'exclude|e-s' => 'Exclude volumes/devices, comma delimited', 'dry-run|d' => 'Dry run, do not delete anything'));
$opt->parse();
try {
    $key = empty($opt->key) ? getenv('AWS_ACCESS_KEY') : $opt->key;
    $secret = empty($opt->secret) ? getenv('AWS_SECRET_KEY') : $opt->secret;
    $region = empty($opt->region) ? getenv('AWS_REGION') : $opt->region;
    $instanceId = $opt->instance;
    $exclusions = empty($opt->exclude) ? array() : array_map('trim', explode(',', $opt->exclude));
    $dryRun = (bool) $opt->{'dry-run'};
    $client = Ec2Client::factory(array('key' => $key, 'secret' => $secret, 'region' => $region));
    $clientHelper = new Ec2ClientHelper($client);
    if (empty($instanceId)) {
        $hostname = gethostname() . '.';
        $instance = $clientHelper->getInstanceByHostname($hostname);
        $instanceId = $instance['InstanceId'];
    } else {
        $instance = $clientHelper->getInstanceById($instanceId);
    }
    $instanceName = $clientHelper->resolveInstanceName($instance);
    $console->writeLine("Creating snapshots of {$instanceName}");
    $volumes = $clientHelper->getVolumesByInstance($instanceId);
    if (count($volumes) === 0) {
        throw new Exception('No volumes found');
    }
    $toBackup = array();
示例#29
0
<?php

require __DIR__ . '/../../vendor/autoload.php';
use Aws\Ec2\Ec2Client;
$client = Ec2Client::factory(array('region' => 'us-east-1'));
$ec2s = array();
$filter = isset($_GET['filter']) ? $_GET['filter'] : '';
// Filter EC2 instances by their Tags.
$result = $client->describeInstances(array());
$reservations = $result['Reservations'];
foreach ($reservations as $reservation) {
    $instances = $reservation['Instances'];
    foreach ($instances as $instance) {
        if (!array_key_exists('Tags', $instance)) {
            continue;
        }
        $tags = $instance['Tags'];
        foreach ($tags as $tag) {
            if ($filter === '' || stripos($tag['Value'], $filter) !== false) {
                $ec2s[$instance['InstanceId']] = $instance;
                break;
            }
        }
    }
}
// Further refine the list of EC2 servers while building the master list
// with additional metadata from AWS.
$supervisor_servers = array();
foreach ($ec2s as $ec2) {
    // https://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Ec2.Ec2Client.html#_describeInstances
    if (!array_key_exists('PrivateIpAddress', $ec2)) {
 /**
  * Get all available regions.
  * @return mixed|null
  */
 protected function getRegions()
 {
     $this->progress->setMessage("Fetching regions...");
     $this->progress->advance();
     $ec2client = new Ec2Client(['version' => 'latest', 'region' => getenv('AWS_DEFAULT_REGION')]);
     return $ec2client->describeRegions()->search('Regions[].RegionName');
 }