LoginSignup
12
13

More than 5 years have passed since last update.

EC2インスタンスを業務時間だけ自動起動する処理をAWS SDK for PHP 2で作成する

Last updated at Posted at 2015-04-28

AWS SDK for PHP 2をインストールして、サンプルコードを動かすでサンプルコードが動作する所から始めます。

いきなり以下の自動起動プログラムをコピペする

サンプルフォルダは名前をaws-phpに変更 $ mv aws-php-sample aws-php && cd aws-php

aws-php/ec2_start.php
<?php

// Include the SDK using the Composer autoloader
require 'vendor/autoload.php';

use Aws\Ec2\Ec2Client;

$today = date('Y-m-d H:i:s');
echo "---BEGIN--- Auto ec2 START {$today}\n";

# ap-northeast-1    アジアパシフィック(東京)
# ap-southeast-1    アジアパシフィック (シンガポール)
# ap-southeast-2    アジアパシフィック(シドニー)
# eu-central-1      欧州 (フランクフルト)
# eu-west-1         欧州 (アイルランド)
# sa-east-1         南米(サンパウロ)
# us-east-1         US East (N. Virginia)
# us-west-1         米国西部(北カリフォルニア)
# us-west-2         米国西部(オレゴン)

# 処理実行するリージョン
# eu-central-1      欧州 (フランクフルト) ここは有効領域でないので外すこと
$regions =
    [
        'ap-northeast-1',
        'ap-southeast-1',
        'ap-southeast-2',
        'eu-west-1',
        'sa-east-1',
        'us-east-1',
        'us-west-1',
        'us-west-2',
    ];

# 各リージョン毎に起動処理を実行
$return = array_map('start_instance', $regions);

# インスタンスの起動処理 タグAutoStart:tureの時で,stopped,stoppingのIDを起動
function start_instance($region)
{
    $ec2client = Ec2Client::factory(['region'  => $region]);
    # TagにAutoStart:trueがついてて,stopped,stoppingのinstance_idsを取る
    $start_taged_instances = $ec2client->describeInstances(
        [
            'Filters' => [
                [
                    'Name' => 'tag:AutoStart',
                    'Values' => ['true'],
                ],
                [
                    'Name' => 'instance-state-name',
                    'Values' => ['stopped', 'stopping'],
                ],
            ],
        ]
);

    # 返り値のオブジェクトからInstanceIDを取得
    $target_ids = $start_taged_instances->getPath('Reservations/*/Instances/0/InstanceId');

    # 何も起動するIDが無い時は処理終了
    if (empty($target_ids)) {
        echo "$region Target instances is empty. Nothing to do. \n";

        return;
    }

    # IDがあるときは起動処理を叩く
    # $target_idsが空だとfaitlエラー吐く
    $result = $ec2client->startInstances(
        ['InstanceIds' => $target_ids]
    );

    $started_ids = $result->getPath('StartingInstances/*/InstanceId');
    print "$region START InstanceIds :";
    print_r($started_ids);
}

echo "---END--- Auto ec2 START\n";

実行

  • タグを何もつけないと、何も起こらない
  • タグでAutoCreat:trueを付けるとstop,stopping状態のインスタンスが起動する
$ php ec2_start.php
---BEGIN--- Auto ec2 START 2015-04-28 14:17:39
ap-northeast-1 START InstanceIds :Array
(
    [0] => i-XXXXXXXX
)
ap-southeast-1 Target instances is empty. Nothing to do.
ap-southeast-2 Target instances is empty. Nothing to do.
eu-west-1 Target instances is empty. Nothing to do.
sa-east-1 Target instances is empty. Nothing to do.
us-east-1 Target instances is empty. Nothing to do.
us-west-1 Target instances is empty. Nothing to do.
us-west-2 Target instances is empty. Nothing to do.
---END--- Auto ec2 START

crontabで月~金の始業時間頃に定期実行させる

  • crontabファイルに設定を記述しておく $ vim ~/crontab
~/crontab
SHELL=/bin/bash
# root PATHを設定
PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/bin:/opt/aws/bin
# mailを送信したくない時
MAILTO=""
AWS=/home/ec2-user/aws-php

# 時間はJSTかUSTかシステムに合わせる。今回はJST。 ログはmessageに吐き出す。
27 8 * * 1-5 php $AWS/ec2_start.php  2>&1 | logger -t AWS_SDK_AUTO -p local0.info
  • crontab設定を反映
$ crontab crontab

設定確認

$ crontab -l

自動シャットダウンの処理は??

今回は簡単に各インスタンスにcrontabの設定でシャットダウンします

crontab
SHELL=/bin/bash
# root PATHを設定
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin:/root/bin:/opt/aws/bin
# mailを送信したくない時
MAILTO="" 

# JSTかUSTかシステムに合わせる。これはJST ログはmessageに書く
17 19 * * * shutdown -h now  2>&1 | logger -t shutdown -p local0.info

次にやりたい事

自動起動処理するEC2インスタンス自身をオートスケールで1時間だけ起動する
これができたら、自動起動の処理なんてすぐ終わるから、t2.microの1時間分の料金だけ済むね!

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13