0
votes

I am using the below Lambda function but keep getting errors. I was able to use the function at the bottom of this page via Pycharm conducting some tests so was expecting this to work in Lambda. Any help would be greatly appreciated.

import boto3

def handler(event, context):
    client = boto3.client('rds')

response = client.stop_db_instance(
    DBInstanceIdentifier='dev-mysql-rds'
)

Response: { "errorMessage": "name 'client' is not defined",
"errorType": "NameError", "stackTrace": [ " File "/var/lang/lib/python3.8/imp.py", line 234, in load_module\n return load_source(name, filename, file)\n", " File "/var/lang/lib/python3.8/imp.py", line 171, in load_source\n module = _load(spec)\n", " File "", line 702, in _load\n", " File "", line 671, in _load_unlocked\n", " File "", line 783, in exec_module\n", " File "", line 219, in _call_with_frames_removed\n", " File "/var/task/lambda_function.py", line 6, in \n response = client.stop_db_instance(\n" ] }

Request ID: "7fd994c0-799f-44a2-b93f-a437fee740af"

Function logs: START RequestId: 7fd994c0-799f-44a2-b93f-a437fee740af Version: $LATEST [ERROR] NameError: name 'client' is not defined Traceback (most recent call last):   File "/var/lang/lib/python3.8/imp.py", line 234, in load_module     return load_source(name, filename, file)   File "/var/lang/lib/python3.8/imp.py", line 171, in load_source     module = _load(spec)   File "", line 702, in _load   File "", line 671, in _load_unlocked   File "", line 783, in exec_module   File "", line 219, in _call_with_frames_removed   File "/var/task/lambda_function.py", line 6, in     response = client.stop_db_instance(END RequestId: 7fd994c0-799f-44a2-b93f-a437fee740af REPORT RequestId: 7fd994c0-799f-44a2-b93f-a437fee740af Duration: 352.02 ms Billed Duration: 353 ms Memory Size: 1024 MB Max Memory Used: 22 MB Unknown application error occurred

The below function works via Pycharm.

import boto3
rds = boto3.setup_default_session(profile_name='dev')
client = boto3.client('rds')

response = client.stop_db_instance(
    DBInstanceIdentifier='dev-mysql-rds'
)
2

2 Answers

2
votes

@Magitrek and @John Rotenstein
Thank you for your help. I managed to get it working with the below script in Lambda.
I had to use the lambda_handler because the originally posted handler did not work.

import boto3

client = boto3.client('rds')

def lambda_handler(event, context):
    
    response = client.stop_db_instance(
        DBInstanceIdentifier='dev-mysql-rds'
    )
0
votes

Since the code is imported before handler() is executed, client.stop_db_instance() is executed before AWS lambda executes handler(), and outside of the scope of the handler function, so client is undefined. If you move that function call inside of the handler it should work.