Search code examples
pythonamazon-web-servicesaws-lambdaaws-samaws-sam-cli

Issue with AWS Sam invoking local lambda


I have a python lambda which is just the sample hello_world which you can create using sam init.

I have modified it slightly by adding sub-folder in the lambda folder.

So inside the hello_world lambda folder I have:

app.py # this is the lambda handler
requirements.txt
my_code_folder # I added this and I want to be able to import it and use it in the lambda. It contains a tonne of custom modules.

However when I run sam local invoke I get:

[ERROR] Runtime.ImportModuleError: Unable to import module 'app': No module named 'hello_world'

If I take out the import it works fine.

Perhaps I have imported incorrectly in my lambda?

import hello_world.my_code_folder.MyModule as my_module

My SAM template has this:

Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.8
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Solution

  • Sample app created using sam init command and added a custom module named hello

    āÆāÆ cat hello_world/hello/hello_world.py
    # custom module
    def hello():
        print("hello")
    
    āÆāÆ cat hello_world/app.py
    import json
    import hello.hello_world as h
    
    
    def lambda_handler(event, context):
    ...
        h.hello()
    
        return {
            "statusCode": 200,
            "body": json.dumps({
                "message": "hello world",
                # "location": ip.text.replace("\n", "")
    
    

    directory structure

    /tmp/foo/samapp via šŸ v3.8.2 ((samapp))
    āÆāÆ tree
    .
    ..
    ā”œā”€ā”€ __init__.py
    ā”œā”€ā”€ events
    ā”‚Ā Ā  ā””ā”€ā”€ event.json
    ā”œā”€ā”€ hello_world
    ā”‚Ā Ā  ā”œā”€ā”€ __init__.py
    ā”‚Ā Ā  ā”œā”€ā”€ app.py
    ā”‚Ā Ā  ā”œā”€ā”€ hello. <--- my custom module
    ā”‚Ā Ā  ā”‚Ā Ā  ā””ā”€ā”€ hello_world.py
    ā”‚Ā Ā  ā””ā”€ā”€ requirements.txt
    ā”œā”€ā”€ samconfig.toml
    ā”œā”€ā”€ template.yaml
    

    Uploaded code

    enter image description here

    Logs

    enter image description here