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年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ