0
3

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.

ec2インスタンスの自動起動・停止

Posted at

CloudWatch Eventのcronで朝晩に呼び出す。

勉強のために起動はPythonで、停止はNode.jsで書く。

起動(Python)

startEC2.py
import json
import boto3
import os

instances = [os.environ['INSTANCE_ID']]
region = "ap-northeast-1"

def lambda_handler(event, context):
    ec2 = boto3.client('ec2',region_name=region)
    ec2.start_instances(InstanceIds=instances)
    
    return {
        'statusCode': 200,
        'body': json.dumps('Started Instance')
    }

Pythonでの環境変数の指定方法はos.environ

停止(Node.js)

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

function StopEC2(callback){
  var ec2 = new AWS.EC2();
  var params = {
    InstanceIds: [
      process.env['INSTANCE_ID']
    ]
  };

  ec2.stopInstances(params, function(err, data) {
    if (err) {
      console.log("ERROR", err);
    } else {
      console.log(data);
      callback();
    }
  });
}

exports.handler = function(event, context) {
  console.log('Process Start');
  StopEC2(function() {
    context.done(null, 'Stoped Instance');
  });
};

nodeでの環境変数の指定方法はprocess.env

0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?