0
0

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を全部問答無用で停止するLambda

Last updated at Posted at 2023-10-04

さくっとコピペでどうぞ

python
import json
import boto3

client = boto3.client('ec2')

def lambda_handler(event, context):
    response = client.describe_instances(
        Filters=[
            {
                'Name': 'instance-state-code',
                'Values': [
                    '16',
                ]
            },
        ]
    )
    targetInstances = []
    for i in response['Reservations']:
        targetInstances.append(i['Instances'][0]['InstanceId'])
    
    if not targetInstances:
        return "nothing target instances"
    else:
        response = client.stop_instances(
            InstanceIds=targetInstances,
            Force=True
        )
        return response

解説

desclibe_instancesで動作状態(Statuscode:16)のEC2インスタンスを全部取得して、そこからinstanceIDのみを配列にして、stop_instancesに渡して終わり。

環境に左右されない作りだと思うのでどこでも使えると思います。
強いて言うならEC2の台数が多くなると正常に動かないかも。(X>50?わかんない)
その場合はpagenatorとかで取得動作自体がループするAPIに差し替えれば行けるはず。

あと、LambdaからEC2のAPIを叩けるようなIAMの権限設定だけはお忘れなく。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?