読者です 読者をやめる 読者になる 読者になる

PHPでVPC内にEC2インスタンスを作成

AWS SDK for PHPを使ってVPC内にEC2インスタンスを作成するサンプルプログラムが見当たらなかったので作成


この本のサンプルをVPC用に書きなおしただけです。

Amazon Web Services ガイドブック クラウドでWebサービスを作ろう!

Amazon Web Services ガイドブック クラウドでWebサービスを作ろう!

ソースコード
#!/usr/bin/php
<?php

error_reporting(E_ALL);

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

$region           = AmazonEC2::REGION_US_E1;
$subnetId         = 'subnet-1ccaeXXX'; // VPCサブネット
$ami              = 'ami-009c3XXX';
$instanceType     = 'm1.small';
$securityGroupId  = array('sg-3dd9cXXX', 'sg-6d9c8XXX'); // VPCのセキュリティグループID
$serverName       = 'test01';
$privateIpAddress = '192.168.1.101'; // プライベートIP
$sshKey           = 'mikedakey';


$ec2 = new AmazonEC2();
$ec2->set_region($region);

// インスタンス作成
$options = array(
  'KeyName'          => $sshKey,
  'InstanceType'     => $instanceType,
  'SubnetId'         => $subnetId,
  'PrivateIpAddress' => $privateIpAddress,
  'SecurityGroupId'  => $securityGroupId,
);
$res = $ec2->run_instances($ami, 1, 1, $options);

if (!$res->isOK())
{
  exit("Could not launch instance: " . $res->body->Errors->Error->Message . "\n");
}

// インスタンス情報の取得
$instances  = $res->body->instancesSet;
$instanceId = (string)$instances->item->instanceId;
print("Launched instance ${instanceId}/${privateIpAddress}\n");

// インスタンス起動待ち
do
{
  $options    = array('InstanceId.1' => $instanceId);
  $res       = $ec2->describe_instances($options);
  $instances = $res->body->reservationSet->item->instancesSet;
  $state     = $instances->item->instanceState->name;
  $running   = ($state == 'running');

  if (!$running)
  {
    print("Instance is currently in " . "state ${state}, waiting 10 seconds\n");
    sleep(10);
  }
}
while (!$running);

// インスタンスにタグを設定
$response = $ec2->create_tags($instanceId, array(
  array('Key' => 'Name', 'Value' => $serverName),
));


// ElasticIPの取得
$res = $ec2->allocate_address(array('Domain' => 'vpc'));
if (!$res->isOK())
{
  exit("Could not allocate public IP address.\n");
}
$publicIP     = (string)$res->body->publicIp;
$allocationId = (string)$res->body->allocationId;
print("Assigned Elastic IP ${publicIP}/${allocationId}.\n");

// ElasticIPをインスタンスに関連付け
$res = $ec2->associate_address(
  $instanceId,
  null, // public_ipはnullにする
  array('AllocationId' => $allocationId)
);
if (!$res->IsOK())
{
  exit("Could not associate IP address ${publicIP}/${allocationId} " .
       "with instance ${instanceId}.\n");
}

print("Associated IP address ${publicIP}/${allocationId} " .
      "with instance ${instanceId}.\n");


exit;
実行結果
[admin@mikeda aws]$ php create_instance.php
Launched instance i-9fe5dXXX/192.168.1.101
Instance is currently in state pending, waiting 10 seconds
Instance is currently in state pending, waiting 10 seconds
Instance is currently in state pending, waiting 10 seconds
Assigned Elastic IP 107.23.4.106/eipalloc-9883aXXX.
Associated IP address 107.23.4.106/eipalloc-9883aXXX with instance i-9fe5dXXX.