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

demandé il y a 2 ans454 vues
2 réponses
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
répondu il y a 2 ans
profile picture
EXPERT
vérifié il y a un mois
profile pictureAWS
EXPERT
vérifié il y a 2 ans
1
Réponse acceptée

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
répondu il y a 2 ans
profile picture
EXPERT
vérifié il y a un mois
profile pictureAWS
EXPERT
vérifié il y a 2 ans

Vous n'êtes pas connecté. Se connecter pour publier une réponse.

Une bonne réponse répond clairement à la question, contient des commentaires constructifs et encourage le développement professionnel de la personne qui pose la question.

Instructions pour répondre aux questions