LoginSignup
0
0

More than 1 year has passed since last update.

lambdaでEC2の停止起動をしてみる

Posted at

内部で作ったサーバ群があるためlambdaを使って停止起動をするプログラムを書いてみることにする。
lambdaを使ったこともないため、lambdaの触りを試しながら実施。

試してみる

AWS公式ドキュメントに以下の記事を見つけた。
Lambda を使用して、Amazon EC2 インスタンスを一定の間隔で停止および起動するにはどうすればよいですか?

この記事を元にlambdaを作っていくことにする。

起動用lambdaの作成

実行ロールの作成

ロール用にポリシー(lambda_ec2_start-stop_policy)をまず作成。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:Start*",
        "ec2:Stop*"
      ],
      "Resource": "*"
    }
  ]
}

作成したポリシーをlambda用ロール(lambda_ec2_start-stop_role)へ許可する。
2_role.png

これでテスト用のロールが完成。

lambdaの作成

EC2開始用lambdaを作成する。

項目 設定値
関数名 start_ec2_instance
ランタイム Python 3.9
アーキテクチャ x86_64
既存のロール lambda_ec2_start-stop_role

3_start_lambda.png

AWSドキュメントをコピーしてregionと対象インスタンスIDを変更して作成。

import boto3
region = 'ap-northeast-1'
instances = ['i-xxxxxxxxxxx', 'i-xxxxxxxxxxx']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=instances)
    print('started your instances: ' + str(instances))

lambdaの実行

lambdaのテストイベントを作成。

項目 設定値
イベントアクションをテスト 新しいイベントを作成
イベント名 test_start_instance
イベント共有の設定 プライベート

作成したテストイベントを使って作成したlambdaを動かしてみると以下の通り。
指定したインスタンスの起動ができた。
6_test_evnet_start_ec2.png

停止用lambdaの作成

lambdaの作成

ロールは先ほど作ったものを使いまわせるため、手順を飛ばしEC2停止用lambdaを作成する。

項目 設定値
関数名 stop_ec2_instance
ランタイム Python 3.9
アーキテクチャ x86_64
既存のロール lambda_ec2_start-stop_role

7_stop_lambda.png

AWSドキュメントをコピーしてregionと対象インスタンスIDを変更して作成。

import boto3
region = 'ap-northeast-1'
instances = ['i-xxxxxxxxxxx', 'i-xxxxxxxxxxx']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('started your instances: ' + str(instances))

lambdaの実行

lambdaのテストイベントを作成。

項目 設定値
イベントアクションをテスト 新しいイベントを作成
イベント名 test_stop_instance
イベント共有の設定 プライベート

作成したテストイベントを使って作成したlambdaを動かしてみると以下の通り。
先ほど起動していた指定したインスタンスの停止ができた。
10_test_evnet_stop_ec2.png

まとめ

今回はlambdaを使って指定したインスタンスのみを停止起動することをやったが、
これだけを使うことは少ないだろうと思ったため、
次はEC2インスタンスすべてを起動停止できるようなlambdaを作成してみることにする。

実用的なところまで行くにはタグをつけ、指定したタグをつけているインスタンスのみ、
EventBridgeで指定した時間に停止するなどそのぐらいまで作れるようにしておきたい。

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