LoginSignup
0
0

More than 5 years have passed since last update.

lambdaで EC2の起動停止をする

Posted at

・INCETANCE_IDは環境変数に追加

StartEC2Instance

const INSTANCE_ID = `${process.env.NODE_ENV}`;

var AWS = require('aws-sdk'); 
AWS.config.region = 'ap-northeast-1';

function ec2Start(cb){
    var ec2 = new AWS.EC2();
    var params = {
        InstanceIds: [
            INSTANCE_ID
        ]
    };

    ec2.startInstances(params, function(err, data) {
        if (!!err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
            cb();
        }
    });
}
exports.handler = function(event, context) {
    console.log('start');
    ec2Start(function() {
        context.done(null, 'Started Instance');
    });
};

StopEC2Instance

const INSTANCE_ID = `${process.env.NODE_ENV}`;

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



AWS.config.region = 'ap-northeast-1';

function ec2Stop(cb){

    var ec2 = new AWS.EC2();
    var params = {
        InstanceIds: [
            INSTANCE_ID
        ]
    };

    ec2.stopInstances(params, function(err, data) {
        if (!!err) {
            console.log(err, err.stack);
        } else {
            console.log(data);
            cb();
        }
    });
}
exports.handler = function(event, context) {
    console.log('start');
    ec2Stop(function() {
        context.done(null, 'Stoped Instance');
    });
};
0
0
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
0
0