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))

asked 2 years ago432 views
2 Answers
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
EXPERT
Uri
answered 2 years ago
profile pictureAWS
EXPERT
reviewed 2 years ago
1
Accepted Answer

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
EXPERT
kentrad
answered 2 years ago
profile pictureAWS
EXPERT
reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions