Home > Blockchain >  Lambda function for creating an EC2 instance
Lambda function for creating an EC2 instance

Time:08-19

I ran my code to create an EC2 instance but I keep getting this error.

  "errorMessage": "'message'",
  "errorType": "KeyError",

The full code

import boto3
import os

AMI = os.environ['AMI']
INSTANCE_TYPE = os.environ['INSTANCE_TYPE']
KEY_NAME = os.environ['KEY_NAME']
SUBNET_ID = os.environ['SUBNET_ID']
REGION = os.environ['AWS_REGION']

ec2 = boto3.client('ec2', region_name=REGION)

def lambda_handler(event, context):
    message = event['message']


    instance = ec2.run_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        SubnetId=SUBNET_ID,
        MaxCount=1,
        MinCount=1,
        InstanceInitiatedShutdownBehavior='terminate', 
        UserData=init_script
    )

    instance_id = instance['Instances'][0]['InstanceId']
    print instance_id

    return instance_id

What could be triggering this key error?

As an environmental variable, am I supposed to use the full key name including its file type. Ex: "key.pem" instead of "key"

CodePudding user response:

The error indicates that you have an error on this line:

message = event['message']

Most likely the lambda event does not have the 'message' key you are expecting. You should print out the event to CloudWatch Logs and take a look.

I ran the rest of your code and it created an EC2 instance successfully.

  • Related