Home > front end >  AWS "Hello World" Python Lambda results in Runtime.ImportModuleError: "Unable to impo
AWS "Hello World" Python Lambda results in Runtime.ImportModuleError: "Unable to impo

Time:01-12

I've read dozens of articles, blog posts, docs, and Q&A posts on this site on this issue, and I haven't found a solution.

My Python code in index.py is simple:

def handler(event, context):
    print("hello world. this is hello handler")


if __name__ == "__main__":
    print("hello world. this is the main section in hello index.py")

Notice that I'm using the default filename index.py and the default entry point handler.

I have a simple pyproject.toml:

[tool.poetry]
name = "hello"
version = "0.1.0"
description = ""
authors = []

[tool.poetry.dependencies]
python = "~3.9"

[tool.poetry.dev-dependencies]

[build-system]
requires = ["poetry-core>=1.1.0"]
build-backend = "poetry.core.masonry.api"

As a basic sanity check, I can run the main section locally via:

poetry run python index.py

I deploy via typescript CDK:

    const stack = new Stack(app, "PythonHelloStack", {env})
    new PythonFunction(stack, `HelloFunction`, {
        runtime: Runtime.PYTHON_3_9,
        entry: path.join(__dirname, `../../../lambdas/hello`),
    })

This successfully creates the Lambda. When I run a test event against this, I get the error:

  "errorMessage": "Unable to import module 'index': No module named 'index'",
  "errorType": "Runtime.ImportModuleError",

To show a screenshot of the console, which shows the code:

screenshot of Lambda console

The code shows up fine if I click on index.py. Why can't the AWS Lambda import index.py? I'm stuck on how to proceed in troubleshooting this.

CodePudding user response:

This is a bug in CDK that's still to be patched in the next release. Downgrade to 1.136 if using CDK v1, or the 2.3.0-alpha.0 version of @aws-cdk/aws-lambda-python-alpha if using CDK v2.

  •  Tags:  
  • Related