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 年前498 查看次数
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 年前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则