2

I am new to python and AWS lambda. I am trying to run this script from the lambda function but I am getting error:

Runtime.HandlerNotFound

This script is working fine if I run it from the ec2 instance, but when I run the same script from AWS lambda it throws an error.

I would be really thankful if someone guides me on what I did wrong.

Thank you


    import boto3
    import requests
    import time
    
    AWS_Access_Key_ID = 
    AWS_Secret_Access_Key = 
    
    DELAY_TIME=10 # 10 Seconds
    
    region = 'us-east-2'
    # instances = ['']
    
    instances = {
      'instance id': 'http://link',
      'instance id': 'http://link'
      
    }
    
    ec2 = None
    
    try:
      ec2 = boto3.client('ec2', aws_access_key_id=AWS_Access_Key_ID, aws_secret_access_key=AWS_Secret_Access_Key, region_name=region)
      # ec2 = boto3.resource('ec2',aws_access_key_id=AWS_Access_Key_ID, aws_secret_access_key=AWS_Secret_Access_Key, region_name=region)
    except Exception as e:
      print(e)
      print("AWS CREDS ERROR, Exiting...")
      exit()
    
    def startInstances(instancesIds):
      if(type(instancesIds) != list):  
        instancesIds = [instancesIds]
    
      try:
        response = ec2.start_instances(InstanceIds=instancesIds, DryRun=False)
        print(response)
        print("Instances Started")
      except ClientError as e:
        print(e)
        print("Instances Failed to Start")
    
    def stopInstances(instancesIds):
      if(type(instancesIds) != list):  
        instancesIds = [instancesIds
        ]
      try:
        response = ec2.stop_instances(InstanceIds=instancesIds, DryRun=False)
        print(response)
        print("Instances Stopped")
      except ClientError as e:
        print(e)
        print("Instances Failed to Stop")
    
    def check():
      for x in instances:
        retry = 0
        live = False
    
        print("Checking Webiste " + instances[x])
    
        while(retry < 5):
          try:
            r = requests.get(instances[x] ,verify=True)
            if(r.status_code == 200):
              live = True
            break
          except: 
            print("Not Live, retry time " + str(retry + 1))
            print("Delaying request for " + str(DELAY_TIME) + " seconds...")
            retry += 1
            time.sleep(DELAY_TIME)
    
        if(live):
          print("Website is live")
          # call function  to start the ec2 instance
          startInstances(x)
        else:
          # call function to stop the ec2 instance
          print('Website is dead') 
          stopInstances(x)   
        print("")
    
    def main():
      check()
    
    if __name__ == '__main__':
      main()
7
  • Can you share the configuration of your lambda? Without it, it is not possible to know why you're getting this error. Commented Aug 6, 2021 at 9:27
  • 2
    Your function does not have any handler. Did you check aws docs on how to make a lambda function in python? btw, hardcoding credentails like that is a very bad idea. Commented Aug 6, 2021 at 9:39
  • try to set the handler in the console with the next pattern file_name.function_name in your case could be file_name.main Commented Aug 6, 2021 at 13:04
  • It's a bad idea to introduce sleep into a lambda function. It's better to just run the function every second than to have the function sleep one second. Commented Aug 6, 2021 at 14:53
  • @ChristianDanielAvilaSanchez thank you for the reply , now i am getting this error, { "errorMessage": "main() takes 0 positional arguments but 2 were given", "errorType": "TypeError", "stackTrace": [ " File \"/var/runtime/bootstrap.py\", line 127, in handle_event_request\n response = request_handler(event, lambda_context)\n" ] } Commented Aug 7, 2021 at 10:53

2 Answers 2

1

https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html You need to specify what is the name of the handler function, which is the function that AWS lambda will call. Then you need to implement that function in your Python script.

Sign up to request clarification or add additional context in comments.

Comments

0

I had a similar problem recently. I was able to define a lambda handler function in my python code that solved the problem. Got the guidance from this post

in short, add this code (adjust naming conventions accordingly):

import botocore
import boto3

def lambda_handler(event, context):
    s3 = boto3.resource('s3')
    bucket = s3.Bucket('bucketname')
    exists = True

    try:
        s3.meta.client.head_bucket(Bucket='bucketname')
    except botocore.exceptions.ClientError as e:
        # If a client error is thrown, then check that it was a 404 error.
        # If it was a 404 error, then the bucket does not exist.
        error_code = int(e.response['Error']['Code'])
        if error_code == 404:
            exists = False

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.