Lambda function to automatically stop an instance

0

I have used the below Lambda code to auto stop instances, with Instance IDs specified. I would like to target all the running instances instead of specific ones, hence please advise how can I achieve this. Please note this works successfully for the Instance IDs specified. The code is below:

import boto3 region = 'eu-west-2'

ec2 = boto3.client('ec2', region_name=region) instances = ['i-02639vfrge55c5ad2','i-03tyho9cffe4aee0']

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

2回答
2

There is no single API to stop all the running instances. You need to get the list of running instance using the describe_instances API. You can use the instance-state-name filter to get only the running instances. Once you have the result, you can extract the instance IDs, place them in an array and call the stop_instances API as you did before.

profile pictureAWS
エキスパート
Uri
回答済み 2年前
profile picture
エキスパート
レビュー済み 25日前
profile pictureAWS
エキスパート
レビュー済み 2年前
1
承認された回答

There is also a Solution for stopping instances on a schedule if that is what you are working on. Instance Scheduler on AWS

profile pictureAWS
エキスパート
kentrad
回答済み 2年前
profile picture
エキスパート
レビュー済み 25日前
profile pictureAWS
エキスパート
レビュー済み 2年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ