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.

已提問 1 年前檢視次數 496 次
4 個答案
2
已接受的答案

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
已回答 1 年前
profile pictureAWS
專家
已審閱 1 年前
0

Yes, code for Python 3.8 looks fine.

profile picture
已回答 1 年前
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.

已回答 1 年前
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
已回答 1 年前

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

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

回答問題指南