Lambda shutdown script is not working

1

I had set up a lambda script years ago using Python 2.7 and it worked fine and as EC.2 instances were decommissioned or added I was able to remove or add instance id as needed. AWS has stopped being able to edit the script if created using Python 2.7. I am trying to create a script for Python 3.8. When testing the script I get a very generic error of "There is an error in your JSON event. Correct it before saving."

The script created using Python 2.7 looks like this:

import boto3
region = 'us-east-1'

instances = [listing of ID’s]

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

The script using Python 3.8 looks like this:

import boto3
region = 'us-east-1'
instances = [listing of ID’s]
ec2 = boto3.client('ec2', region_name=region)

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

It feels like there is something simple missing in my syntax but for the life of my I cannot fix out what it might be.

demandé il y a un an498 vues
4 réponses
2
Réponse acceptée

Hello, your script looks correct.

I just tested your script myself and it works.

It seems something else is wrong, maybe your testevent itself?

I used the default testevent:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

See also: https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-eventbridge/

profile picture
HeikoMR
répondu il y a un an
profile pictureAWS
EXPERT
vérifié il y a un an
0

Yes, code for Python 3.8 looks fine.

profile picture
répondu il y a un an
0

HeikoMR, thanks for the link. It helped to remind me about the roles and how I forgot to apply the correct one to the Lambda function.

répondu il y a un an
0

Hello,

You are just missing a double quote. The code should look as below. I tested this in my environment and it works fine.


import boto3
region = 'us-east-1'
instances = ["i-xxxxxxxxxxx"]
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))
profile pictureAWS
répondu il y a un an

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