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;
 }
 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'));
 }
示例#3
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 __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]);
 }
 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)]);
 }
 /**
  * @param array $config
  * @param Ec2Client $ec2Client
  *
  * Creates a basic EC2 Client Factory object using config parameters
  */
 function __construct($config = array(), $ec2Client = null)
 {
     $this->config = array_merge($this->config, $config);
     $this->ec2Client = $ec2Client;
     if ($this->ec2Client == null) {
         $this->ec2Client = Ec2Client::factory(array('region' => $this->config['region'], 'version' => $this->config['version'], 'profile' => $this->config['profile']));
     }
 }
示例#7
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');
 }
示例#9
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.");
     }
 }
 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;
 }
示例#11
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;
 }
        }
    }).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'];
            }
        }
示例#13
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)));
 }
#!/usr/bin/php
<?php 
/*
|
| ec2-power-button -- @dustyfresh
| ./ec2-power-button <start/stop> <instanceID> <region>
|
| this will toggle an instance on or off, and it's good
| for cronjerbs!
|
*/
error_reporting(0);
$cmd = $argv[1] or die("please supply a command(start/stop)...\n");
$instanceID = $argv[2] or die("please supply an instance ID\n");
$region = $argv[3] or die("Please specify a region. for example: us-east-1\n");
require_once "awssdkforphp/vendor/autoload.php";
use Aws\Ec2\Ec2Client;
$client = Ec2Client::factory(array('key' => '', 'secret' => '', 'region' => "{$region}"));
if ($cmd == 'start') {
    $result = $client->startInstances(array('InstanceIds' => array($instanceID), 'DryRun' => false));
} elseif ($cmd == 'stop') {
    $result = $client->stopInstances(array('InstanceIds' => array($instanceID), 'DryRun' => false));
}
//print_r($result); // uncomment to see results of request
print "OK\n";
示例#15
0
 public function testFactoryUsesSigV4InCnRegions()
 {
     $description = array('apiVersion' => '2013-10-15', 'endpointPrefix' => 'ec2', 'serviceType' => 'query', 'signatureVersion' => 'v2', 'namespace' => 'Ec2', 'regions' => array('cn-north-1' => array('http' => true, 'https' => true, 'hostname' => 'foo.aws.com')));
     $client = Ec2Client::factory(array('key' => 'foo', 'secret' => 'bar', 'region' => 'cn-north-1', ClientOptions::SERVICE_DESCRIPTION => $description));
     $this->assertInstanceOf('Aws\\Common\\Signature\\SignatureV4', $client->getSignature());
 }
示例#16
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']));
 }
示例#17
0
 /**
  * @param  [type] $id           'primary id of azure_instance table.'
  * @param  $err 				when err>0 then entry in database would be deleted, other updation will take place.
  * @param  $option 				1= start , 4 = stop
  * @return [type]               1 if everything goes right.
  */
 function start_stop_vm($id, $option)
 {
     $query = $this->mysqlDbOb->select_query_multiple_where_args(array('status', 'user_id', 'domain_location', 'InstanceId'), TABLENAME_INSTANCES, array('instancePrimaryId' => $id));
     $no_of_rows = mysqli_num_rows($query);
     if ($no_of_rows > 0) {
         $query_fetch = mysqli_fetch_assoc($query);
     }
     if ($no_of_rows < 1) {
         return 'Virtual machine was not found, wrong input.';
         //virtual machine not found, wrong input.
     } else {
         if ($query_fetch['status'] == 2) {
             return 'Virtual machine is deleted.';
             //DELETED
         } else {
             //GETTING CREDENTIAL FORM AZURE FORM COMMON API CLASS
             $amazon_credentials = $this->get_credentials_from_primary_id($id, 'amazon');
             try {
                 $ec2Client = Ec2Client::factory(array('key' => $amazon_credentials['api_key'], 'secret' => $amazon_credentials['api_secret'], 'region' => $query_fetch['domain_location']));
             } catch (Exception $e) {
                 return 'Problem making connection with Amazon, please check your keys.';
             }
             if ((int) $option == 1) {
                 //start
                 try {
                     $result = $ec2Client->startInstances(array('InstanceIds' => array($query_fetch['InstanceId'])));
                 } catch (Exception $e) {
                     return 'Problem in starting of amazon server.';
                 }
                 return $this->update_status($id, 1);
             } else {
                 //stop
                 try {
                     $result = $ec2Client->stopInstances(array('InstanceIds' => array($query_fetch['InstanceId'])));
                 } catch (Exception $e) {
                     return 'Problem occured while stoping of instance.';
                 }
                 return $this->update_status($id, 4);
             }
         }
     }
 }
示例#18
0
function EC2_LaunchInstance($region, $ami, $size, $user_data, $loc)
{
    $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));
            $response = $ec2->runInstances(array('ImageId' => $ami, 'MinCount' => 1, 'MaxCount' => 1, 'InstanceType' => $size, 'UserData' => base64_encode($user_data)));
            $ret = true;
            if (isset($loc) && strlen($loc) && isset($response['Instances'][0]['InstanceId'])) {
                $instance_id = $response['Instances'][0]['InstanceId'];
                $ec2->createTags(array('Resources' => array($instance_id), 'Tags' => array(array('Key' => 'Name', 'Value' => 'WebPagetest Agent'), array('Key' => 'WPTLocations', 'Value' => $loc))));
            }
        } catch (\Aws\Ec2\Exception\Ec2Exception $e) {
            $error = $e->getMessage();
            logError("Error launching EC2 instance. Region: {$region}, AMI: {$ami}, error: {$error}");
        }
    }
    return $ret;
}
示例#19
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));
 }
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();
示例#21
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;
}
示例#22
0
<?php

// Require the PHP SDK of AWS
require 'vendor/autoload.php';
use Aws\Ec2\Ec2Client;
// Begin EC2Client
$ec2 = Ec2Client::factory(array('region' => $aws_credentials['region'], 'version' => 'latest', 'credentials' => array('key' => $aws_credentials['aws_access_key_id'], 'secret' => $aws_credentials['aws_secret_access_key'])));
// Test if Ec2Client is working
/*
$result = $ec2->describeInstanceStatus([
  'IncludeAllInstances' => true,
  'InstanceIds' => [ $instanceID ],
]);
*/
// Get new address
$allocation = $ec2->allocateAddress(['Domain' => $vpc_id]);
$allocation = reset($allocation);
// Disassociate if the instance is attached with EIP
$get_ip = true;
try {
    $describeEIP = $ec2->describeAddresses(['PublicIps' => [$elasticIP]]);
    $describeEIP = reset($describeEIP);
} catch (Exception $e) {
    $get_ip = false;
}
// IF EIP is attached, run disassociate.
if ($get_ip) {
    $result = $ec2->disassociateAddress(['PublicIp' => $elasticIP]);
}
// Assoicate new EIP
$result = $ec2->associateAddress(['AllocationId' => $allocation["AllocationId"], 'InstanceId' => $instanceID]);
require_once 'aws-autoloader.php';
require_once 'config.php';
use Aws\AutoScaling\AutoScalingClient;
use Aws\Ec2\Ec2Client;
# Downloads the latest from remote without trying to merge or rebase anything
# Resets the master branch to what you just fetched
if (isset($_POST['deploy']) and $_POST['deploy'] == 1) {
    exec('cd ' . $doc_root . ' && git fetch --all && git reset --hard origin/master');
} elseif (isset($argc) and $argc == 2 and $argv[1] == 'update') {
    exec('cd ' . $doc_root . ' && git fetch --all && git reset --hard origin/master');
} elseif (isset($_REQUEST['payload'])) {
    # Create a autoscaling client object
    $as_client = AutoScalingClient::factory(array('key' => $access_key, 'secret' => $secret_key, 'region' => $region));
    # Create a ec2 client object
    $ec2_client = Ec2Client::factory(array('key' => $access_key, 'secret' => $secret_key, 'region' => $region));
    # EC2 instance id
    $ec2_id = array();
    # This includes all Amazon EC2 instances that are members of the group
    $result = $as_client->describeAutoScalingGroups(array('AutoScalingGroupNames' => array($as_group)));
    $result = $result['AutoScalingGroups'];
    foreach ($result as $value) {
        $instance = $value['Instances'];
        # Append ec2 instance id
        foreach ($instance as $id) {
            array_push($ec2_id, $id['InstanceId']);
        }
    }
    # This includes all information about instance id in $ec2_id which are currently running
    $result = $ec2_client->describeInstances(array('InstanceIds' => $ec2_id, 'Filters' => array(array('Name' => 'instance-state-name', 'Values' => array('running')))));
    $result = $result['Reservations'];
示例#24
0
 public function getEc2Client()
 {
     return Ec2Client::factory($this->getCredentials());
 }
示例#25
0
 private function createEc2Client()
 {
     return Ec2Client::factory($this->getConnectionOptions());
 }
示例#26
0
 /**
  * コンストラクタ
  *
  * @return void
  **/
 public function __construct()
 {
     parent::__construct();
     $this->client = Ec2Client::factory($this->getConfig());
 }
示例#27
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)) {
#!/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)) {
示例#29
0
<?php

session_start();
require 'vendor/autoload.php';
require 'dbConnection.php';
use Aws\Ec2\Ec2Client;
use Aws\Common\Enum\Region;
$query_creds = "select aws_access_id, aws_secret_id from company where company_id='{$_SESSION['companyId']}';";
$result_creds = mysql_query($query_creds);
while ($row = mysql_fetch_assoc($result_creds)) {
    if ($row['aws_access_id'] == null || $row['aws_secret_id'] == null) {
        echo "<script>alert('Could Not Load AWS Configuration')\nwindow.location.href='configuration.php';\n</script>";
    } else {
        $key = $row['aws_access_id'];
        $secret = $row['aws_secret_id'];
    }
}
$aws = Ec2Client::factory(array('version' => 'latest', 'region' => 'us-east-1', 'credentials' => array('key' => $key, 'secret' => $secret)));
return $aws;