13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS Lambda でEC2の起動・停止を行う

Posted at

目的

AWSのEC2の起動・停止をLambdaを使用して決まった時間に行う

コード

まずは、起動させる方

var AWS = require('aws-sdk');

// EC2のアクセス権限を持っているユーザ
var accessKey = 'XXX';
var secretAccessKey = 'XXX';

exports.handler = function(event, context) {
    
    var ec2 = new AWS.EC2({
        accessKeyId: accessKey,
        secretAccessKey: secretAccessKey
    });
    var params = {
        // 起動対象のEC2のインスタンスID
        InstanceIds: ['i-00640ca5']
    };
    
    ec2.startInstances(params, function(err, data){
        if (err) {
            context.done('error', err);
        } else {
            context.succeed('handler complete');
        }
    });
};

次に停止させる方ですが、上記ソースに以下の変更を入れたものでOK

ec2.startInstances → ec2.stopInstances

イベントソース

イベントソースには、以下のように起動or停止させたい時間を設定すればOK

  • Event source type : CloudWatch Events - Schedule
  • Rule name : 適当なもの
  • Rule description : 適当なもの
  • Schedule expression : cron(0 0 * * ? *) // UTC なので注意(この場合は毎日9:00)

「Schedule expression」の詳しい書き方は以下を参照
スケジュールされたイベントでの AWS Lambda の使用

13
14
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
13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?