LoginSignup
0
0

More than 1 year has passed since last update.

Lambdaでec2自動起動停止

Posted at

自動起動

iam role作成

AWSコンソールへログイン
https://console.aws.amazon.com/iamv2
左ペインロール押下
ロールを作成押下
一般的なユースケース:lambda
ポリシー:AmazonEC2FullAccess
ロール名:control-ec2
作成

lambda関数作成

https://console.aws.amazon.com/lambda
関数の作成押下
関数名:start-ec2
ランタイム:python3.9
デフォルトの実行ロールの変更
既存のロールを使用する:control-ec2
関数の作成
以下コード入れる

import boto3
region = 'ap-northeast-1'
instances = []
instances.append('対象インスタンスID1')
instances.append('対象インスタンスID2')

ec2 = boto3.client('ec2', region_name=region)

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

test押下
新しいテストイベントの作成
イベントテンプレート:そのまま
イベント名:適当に
作成
test押下
ちゃんと動くか確認

EventBridge

+トリガーの追加
トリガーの選択
EventBridge
新規ルールの作成
ルール名:auto-start-ec2

ルールタイプ
スケジュール式
cron(0 23 ? * SUN-THU *) #平日の朝8時起動

自動停止

lambda関数作成

https://console.aws.amazon.com/lambda
関数の作成押下
関数名:stop-ec2
ランタイム:python3.9
デフォルトの実行ロールの変更
既存のロールを使用する:control-ec2
関数の作成
以下コード入れる

import boto3
region = 'ap-northeast-1'
instances = []
instances.append('対象インスタンスID1')
instances.append('対象インスタンスID2')

ec2 = boto3.client('ec2', region_name=region)

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

test押下
新しいテストイベントの作成
イベントテンプレート:そのまま
イベント名:適当に
作成
test押下
ちゃんと動くか確認

EventBridge

+トリガーの追加
トリガーの選択
EventBridge
新規ルールの作成
ルール名:auto-stop-ec2

ルールタイプ
スケジュール式
cron(0 13 ? * MON-FRI *) #平日の22時停止

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