Lamda Function Execution Error

0

I created a python program that counts number of RDs instances anad prints it. Program runs fine in standlaone mode in Windows. I want to add this to AWS as Lambda Function.

#!/usr/bin/env python3

from boto3 import client

client = client('rds')

rds_instances = client.describe_db_instances(Filters=[{'Name':'engine', 'Values':['oracle-ee']}])

#print out just the number like your shell script
print(len(rds_instances['DBInstances']))

#Just a little additional code to show you how to access the results from the describe_db_instances call:
if len(rds_instances['DBInstances']) != 0:
    for db_instance in rds_instances['DBInstances']:
        db_engine = db_instance.get('Engine')
        print(db_engine)

I created a new IAM role "Lambda-Role" and gave it "administratorAcceess" policy because the policy "AWSLambda_FullAccess" generated a permission error for script to run a Boto or CLI command. I know this is not secure and I have to change it later.

However, I an getting this error even though the program does print the output. Do you know what is causing this and how to fix it?

Details Execution function: failed

{ "errorMessage": "Handler 'lambda_handler' missing on module 'lambda_function'", "errorType": "Runtime.HandlerNotFound", "requestId": "bfe08f55-5bb3-4d59-8c4d-fb448a4ec15c", "stackTrace": [] }

Log Output

{ 1 oracle-ee START RequestId: bfe08f55-5bb3-4d59-8c4d-fb448a4ec15c Version: $LATEST [ERROR] Runtime.HandlerNotFound: Handler 'lambda_handler' missing on module 'lambda_function' Traceback (most recent call last):END RequestId: bfe08f55-5bb3-4d59-8c4d-fb448a4ec15c REPORT RequestId: bfe08f55-5bb3-4d59-8c4d-fb448a4ec15c Duration: 20.24 ms Billed Duration: 21 ms Memory Size: 128 MB Max Memory Used: 78 MB Init Duration: 761.92 ms

1개 답변
1
수락된 답변

Hello.

Try your Python code as below.
The Lambda function executes the handler method when the function is called, so you need to define the function as follows.
https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html

#!/usr/bin/env python3

from boto3 import client

client = client('rds')

def lambda_handler(event, context):

    rds_instances = client.describe_db_instances(Filters=[{'Name':'engine', 'Values':['oracle-ee']}])

    #print out just the number like your shell script
    print(len(rds_instances['DBInstances']))

    #Just a little additional code to show you how to access the results from the describe_db_instances call:
    if len(rds_instances['DBInstances']) != 0:
        for db_instance in rds_instances['DBInstances']:
            db_engine = db_instance.get('Engine')
            print(db_engine)
profile picture
전문가
답변함 4달 전
profile pictureAWS
전문가
검토됨 4달 전
  • I did add that new line after client variable statement but I get a runtime error now. See below. <<< def lambda_handler(event, context): >>>>

    I also tried addding the "Return" statement at the end but still did not resolve error.

    ====================================== Test Event Name RDS-Event

    Response { "errorMessage": "Syntax error in module 'lambda_function': expected an indented block after function definition on line 7 (lambda_function.py, line 9)", "errorType": "Runtime.UserCodeSyntaxError", "requestId": "32bc3e87-6cd7-4524-9c4e-2f2a45d21dab", "stackTrace": [ " File "/var/task/lambda_function.py" Line 9\n rds_instances = client.describe_db_instances(Filters=[{'Name':'engine', 'Values':['oracle-ee']}])\n" ] }

    Function Logs START RequestId: 32bc3e87-6cd7-4524-9c4e-2f2a45d21dab Version: $LATEST [ERROR] Runtime.UserCodeSyntaxError: Syntax error in module 'lambda_function': expected an indented block after function definition on line 7 (lambda_function.py, line 9) Traceback (most recent call last):   File "/var/task/lambda_function.py" Line 9     rds_instances = client.describe_db_instances(Filters=[{'Name':'engine', 'Values':['oracle-ee']}])END RequestId: 32bc3e87-6cd7-4524-9c4e-2f2a45d21dab REPORT RequestId: 32bc3e87-6cd7-4524-9c4e-2f2a45d21dab Duration: 1.75 ms Billed Duration: 2 ms Memory Size: 128 MB Max Memory Used: 34 MB

    Request ID 32bc3e87-6cd7-4524-9c4e-2f2a45d21dab

  • There seems to be an indentation problem in the error. However, I was unable to reproduce the same error even when running it with my AWS account. So please make sure you have copied and pasted my code correctly.

  • You are correct. It is strange that when I copy/paste your code which is exactly what I had it worked. Can I ask what permission roles did you grant the IAM role attached to Lambda so it can run the function? I used the "AdministratorAccess" but that is not secure. I tried "LambdaFullAccess" role before but it gave me permissions issue.

  • You are correct. It is strange that when I copy/paste your code which is exactly what I had it worked.

    Python is a programming language that divides blocks by indentation, so if the indentation is even slightly off, an error will occur.

    Can I ask what permission roles did you grant the IAM role attached to Lambda so it can run the function?
    I used the "AdministratorAccess" but that is not secure. I tried "LambdaFullAccess" role before but it gave me permissions issue.

    We have set permissions to output logs from Lambda to CloudWatch Logs and permissions to view RDS instances.

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": "logs:CreateLogGroup",
                "Resource": "arn:aws:logs:ap-northeast-1:1111111111111:*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                ],
                "Resource": [
                    "arn:aws:logs:ap-northeast-1:1111111111111:log-group:/aws/lambda/rdstest:*"
                ]
            },
            {
                "Effect": "Allow",
                "Action": [
                    "rds:DescribeDBInstances"
                ],
                "Resource": [
                    "*"
                ]
            }
        ]
    }
    
  • Are you suggesting to create a custom policy you listed and assign it to a new role for lambda access instead of using the ones provided by amazon?

    Does the policy depend on which region the service is running that needs to be updated because i see "ap-northeast"

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

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

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

관련 콘텐츠