2012-07-03 239 views

回答

8

下面是一個定義AMI啓動機器的一個基本的例子:

$image_id = 'ami-3d4ff254'; //Ubuntu 12.04 
$min  = 1;    //the minimum number of instances to start 
$max  = 1;    //the maximum number of instances to start 
$options = array(
    'SecurityGroupId' => 'default', //replace with your security group id 
    'InstanceType' => 't1.micro', 
    'KeyName'   => 'keypair', //the name of your keypair for auth 
    'InstanceInitiatedShutdownBehavior' => 'terminate' //terminate on shutdown 
); 

require_once('AWSSDKforPHP/sdk.class.php'); 

$ec2 = new AmazonEC2(); 

$response = $ec2->run_instances($image_id, $min, $max, $options); 

if(!$response->isOK()){ 
    echo "Start failed\n"; 
} 

這是假設你有你的AWS憑據設置正確......希望這可以讓你在正確的方向...

+0

謝謝你的這個有用的代碼。是否有可能啓動一個現有的實例?我似乎無法找到這些信息。 –

+0

@SSHThis try startInstances –

+0

它實際上是「start_instances」http://docs.aws.amazon.com/AWSSDKforPHP/latest/#m=AmazonEC2/start_instances –

3

這裏是一個更詳細的腳本,如果你有興趣:

// Sleep time to allow EC2 instance to start up 
$sleeptime = 15; 
$username = "ec2-user"; 

// For AWS PHP SDK 
putenv('HOME=/home/ec2-user/'); 
require_once 'AWSSDKforPHP/sdk.class.php'; 

// Get data from HTTP POST 
$ami = $_POST['amis']; 
$instancetype = $_POST['instancetype']; 
$keyname = $_POST['key']; 
$securitygroup = $_POST['securitygroups']; 

// Instantiate the AmazonEC2 class 
$ec2 = new AmazonEC2(); 

// Boot an instance of the image 
$response = $ec2->run_instances($ami, 1, 1, array(
    'KeyName' => $keyname, 
    'InstanceType' => $instancetype, 
    'SecurityGroupId' => $securitygroup, 
)); 
if (!($response->isOK())) { 
    echo "<p class='error'>ERROR! Could not create new instance!</p>"; 
    return; 
} 
$instance = $response->body->instancesSet->item->instanceId; 
$message = "<p>Your instance has been successfully created.</p>"; 
$message .= ("<p>Instance ID is: <b>$instance</b></p>"); 

// Give instance some time to start up 
sleep ($sleeptime); 

// Get the hostname from a call to the DescribeImages operation. 
$response = $ec2->describe_instances(array(
    'Filter' => array(
     array('Name' => 'instance-id', 'Value' => "$instance"), 
    ) 
)); 
if (!($response->isOK())) { 
    echo "<p class='error'>ERROR! Could not retrieve hostname for instance!</p>"; 
    return; 
} 
$hostname = $response->body->reservationSet->item->instancesSet->item->dnsName; 

// Output the message 
$message .= "<p>Your instance hostname is: <b>$hostname</b></p>"; 
$message .= "<p>You can connect to your instance using this command:<br>" . 
    "<b>ssh -i $keyname.pem [email protected]" . $hostname . "</b></p>"; 

echo $message; 

差不多一樣@ dleiftah的,除了它輸出新的主機名完成後的立場。

+3

但是我怎樣才能阻止這個實例與SDK? – Mohyt

+1

要停止實例,請http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.Ec2.Ec2Client.html#_stopInstances單擊以展開基本格式示例,因此代碼爲$客戶端 - > stopInstances() – fedmich