Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
14
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@y-sugasawa

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

目的

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 の使用

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
14
Help us understand the problem. What are the problem?