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

gefragt vor 2 Jahren454 Aufrufe
2 Antworten
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
EXPERTE
Uri
beantwortet vor 2 Jahren
profile picture
EXPERTE
überprüft vor einem Monat
profile pictureAWS
EXPERTE
überprüft vor 2 Jahren
1
Akzeptierte Antwort

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
EXPERTE
kentrad
beantwortet vor 2 Jahren
profile picture
EXPERTE
überprüft vor einem Monat
profile pictureAWS
EXPERTE
überprüft vor 2 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen