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.

질문됨 일 년 전492회 조회
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
답변함 일 년 전
profile pictureAWS
전문가
검토됨 일 년 전
0

Yes, code for Python 3.8 looks fine.

profile picture
답변함 일 년 전
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.

답변함 일 년 전
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
답변함 일 년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠