Christopher Moura
Christopher Moura

Reputation: 1

AWS Lambda unable to import module No module named 'psycopg2'

I'm trying to import psycopg2 in my lambda but I'm getting this error:

[ERROR] Runtime.ImportModuleError: Unable to import module 'expire_invites': No module named 'psycopg2'

I already downloaded the bundle for python3.6 from [jkehler/awslambda-psycopg2] (https://github.com/jkehler/awslambda-psycopg2) and copied to my lambda directory.

Lambda directory screenshot

I'm creating the lambda and his layer for psycopg2 using terraform:

data.tf

data "archive_file" "psycopg2_layer" {
  type        = "zip"
  source_dir  = "${path.module}/../../scripts/python/expire_invites/psycopg2"
  output_path = "${path.module}/../../scripts/python/expire_invites/psycopg2_layer.zip"
}

main.tf

resource "aws_lambda_layer_version" "pg_dependencies_layer" {
  layer_name          = "pg-dependencies-layer"
  filename            = data.archive_file.psycopg2_layer.output_path
  source_code_hash    = data.archive_file.psycopg2_layer.output_base64sha256
  compatible_runtimes = ["python3.6"]
}

resource "aws_lambda_function" "expire_invites" {
  filename      = "${path.module}/../../scripts/python/expire-invites.zip"
  function_name = "expire_invites-${terraform.workspace}"
  role          = aws_iam_role.lambda.arn
  layers        = [aws_lambda_layer_version.pg_dependencies_layer.arn]
  handler       = "expire_invites.lambda_handler"
  runtime       = "python3.6"

  environment {
    variables = {
      ...database variables
    }
  }

  vpc_config {
    ...vpc config
  }
}

The lambda is created and works fine, except for the psycopg2 import...

I've tried several different things but no success, I don't know if it's something I'm doing wrong.

Upvotes: 0

Views: 310

Answers (1)

Christopher Moura
Christopher Moura

Reputation: 1

Solved by adding the following key to my lambda definition:

source_code_hash  = data.archive_file.expire_invites.output_base64sha256

My code was not being updated and the package was not uploaded to AWS.

Upvotes: 0

Related Questions