SAM Lambda:[错误] Runtime.ImportModuleError:无法导入模块“index”:没有名为“pg8000”的模块

Den*_*boy 4 sam amazon-web-services python-3.x aws-lambda aws-sam-cli

我已经部署了一个使用 pg8000 的 lambda (python3.7)

import pg8000
..
def get_connection():
    """
        Method to establish the connection.
    """
    try:
        print ("Connecting to database")
        # Create a low-level client with the service name for rds
        client = boto3.client("rds")
        # Read the environment variables to get DB EndPoint
        DBEndPoint = os.environ.get("DBEndPoint")
        # Read the environment variables to get the Database name
        DatabaseName = os.environ.get("DatabaseName")
        # Read the environment variables to get the Database username which has access to database.
        DBUserName = os.environ.get("DBUserName")
        # Generates an auth token used to connect to a db with IAM credentials.
        password = client.generate_db_auth_token(
            DBHostname=DBEndPoint, Port=5432, DBUsername=DBUserName
        )
        # Establishes the connection with the server using the token generated as password
        conn = pg8000.connect(
            host=DBEndPoint,
            user=DBUserName,
            database=DatabaseName,
            password=password,
            ssl={"sslmode": "verify-full", "sslrootcert": "rds-ca-2015-root.pem"},
        )
        print("Succesful connection!")
        return conn
    except Exception as e:
        print ("While connecting failed due to :{0}".format(str(e)))
        return None
...
Run Code Online (Sandbox Code Playgroud)

我有一个requirements.txt,其中包含:

pg8000==1.13.2
boto3==1.9.67
Run Code Online (Sandbox Code Playgroud)

我正在执行 sam 构建、sam 包和 sam 部署。sam build 不处理像 pg8000 这样的依赖项的下载吗?

确切的命令:

sam build
sam package --template-file ./template.yml --output-template-file output.yml --s3-bucket xxx-bucket
sam deploy --template-file ./output.yml --stack-name demo --capabilities CAPABILITY_IAM
Run Code Online (Sandbox Code Playgroud)

触发 lambda 后出错:

[ERROR] Runtime.ImportModuleError: Unable to import module 'index': No module named 'pg8000'
Run Code Online (Sandbox Code Playgroud)

Ass*_*ran 5

根据文档

sam build 查找包含依赖项的清单文件(例如 requirements.txt),并自动创建部署工件。

您的模块似乎根本没有部署。

我将解释如何逐步修复它:

  • sam build创建了一个.aws-sam/build包含 lambda 函数的文件夹,其中包括依赖项和另一个非常重要的文件:您将它 template.ymlCodeUri相对于.aws-sam/build文件夹的(lambdas src 代码的路径)一起使用。

  • sam package命令应该将您的位置template.yml作为参数传递,这意味着sam build目标文件夹 url 。跑sam package --template-file .\.aws-sam\build\template.yml --output-template-file .\.aws-sam\build\output.yml --s3-bucket your_bucket

  • 最后运行 sam deploy --template-file .\.aws-sam\build\output.yml --stack-name demo --capabilities CAPABILITY_IAM

当您执行此命令时:sam package --template-file ./template.yml --output-template-file output.yml --s3-bucket xxx-bucket , 模板文件./template.yml指向您的 lambda 函数,而没有位于 .\.aws-sam\build\your_lambda.

还有一件事:

如果您使用多个模块,您应该考虑使用图层

希望这可以帮助