4
5

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 1 year has passed since last update.

定期的に全EC2サーバを停止する設定

Posted at

内容

AWS検証環境でEC2の停止を忘れてしまうことがあるので、全EC2サーバを1日1回停止する運用をいれます。
EventBridgeの「EC2 StopInstances API呼び出し」を使用しようと思いましたが、全てのインスタンスIDを指定する方法が分からなくlambda関数を作成しました。

コード

同一AWSアカウント内で起動中の全EC2サーバを停止します。

import boto3

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

def lambda_handler(event, context):
    ec2_list = client.describe_instances()
    for ec2_reservation in ec2_list['Reservations']:
        for ec2_instance in ec2_reservation['Instances']:
            ec2_instance_id = ec2_instance['InstanceId']
            ec2_instance_state = ec2_instance['State']['Name']

            if ec2_instance_state == 'running':
                response = client.stop_instances(InstanceIds = [ec2_instance_id])

設定方法

  • Lambda用のIAMロールを作成します。(EC2アクセス用)

  • Lambda関数を作成します。
    lambda1.png

  • EventBridgeで定期実行の設定をします。
    lambda2.png

4
5
1

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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?