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 年前檢視次數 454 次
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 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南