LoginSignup
2
0

More than 1 year has passed since last update.

【EC2】LambdaでEC2インスタンスを自動起動・停止

Posted at

EC2インスタンスを自動停止させたい

社内利用用のEC2インスタンスなど夜間や日中だけは停止させておきたいEC2インスタンスがあり、Lambdaスクリプトで実現させました

EC2インスタンのタグ付け

EC2インスタンスにタグを付けて、そのタグを付けたインスタンスを自動で停止させるようにします。
タグはなんでもいいのですが
keyにAutoStop
valueにtrue
といれておきます

Lambdaスクリプト

前提としてLambda関数にはEC2のstart・stopとdescribeの権限をIAMロールに付与する必要があります。

import boto3
region = 'ap-northeast-1'
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    
    custom_filter = [{
        'Name':'AutoStop', 
        'Values': ['true']}]
        
    response = ec2.describe_instances(Filters=custom_filter)
    instance_ids = []
    for instance_dic in response['Reservations']:
        instance_ids.append(instance_dic['Instances'][0]['InstanceId'])
    
    ec2.stop_instances(InstanceIds=instance_ids)
    # ec2.start_instances(InstanceIds=instance_ids) #開始するとき

コードは解説する程ではないのですが、describe_instancesにfilterで設定したタグのインスタンス一覧を取ってきて、instance_idの一覧を作ります。
あとはそれをstop(またはstart)させているだけです。

自動停止

最後にこのLambdaをAmazon EventBridgeで呼び出してあげるだけです。
タグ付けで対象インスタンスを設定すると、ON・OFFや設定の確認がかなり楽になります。

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