I've a monorepo that contains a set of Python AWS lambdas and I'm using Bazel for building and packaging the lambdas. I'm now trying to use Bazel to create a zip file that follows the expected AWS Lambdas packaging and that I can upload to Lambda. Wondering what's the best way to do this with Bazel?
Below are a few different things I've tried thus far:
Attempt 1: py_binary
BUILD.bazel
py_binary(
name = "main_binary",
srcs = glob(["*.py"]),
main = "main.py",
visibility = ["//appcode/api/transaction_details:__subpackages__"],
deps = [
requirement("Faker"),
],
)
Problem:
This generates the following:
- main_binary (python executable)
- main_binary.runfiles
- main_binary.runfiles_manifest
Lambda expects the handler to be in the format of lambda_function.lambda_handler
. Since main_binary
is an executable vs. a python file, it doesn't expose the actual handler method and the lambda blows up because it can't find it. I tried updating the handler configuration to simply point to the main_binary
but it blows up because it expects two arguments(i.e. lambda_function.lambda_handler
).
Attempt 2: py_library + pkg_zip
BUILD.bazel
py_library(
name = "main",
srcs = glob(["*.py"]),
visibility = ["//appcode/api/transaction_details:__subpackages__"],
deps = [
requirement("Faker"),
],
)
pkg_zip(
name = "main_zip",
srcs =["//appcode/api/transaction_details/src:main" ],
)
Problem:
This generates a zip file with:
- main.py
__init__.py
The zip file now includes the main.py
but none of its runtime dependencies. Thus the lambda blows up because it can't find Faker
.
Other Attempts:
I've also tried using the --build_python_zip
flag as well as the @bazel_tools//tools/zip:zipper
with a generic rule but they both lead to similar outcomes as the two previous attempts.
Below are the changes I made to the previous answer to generate the lambda zip. Thanks @jvolkman for the original suggestion.
project/BUILD.bazel: Added rule to generate
requirements_lock.txt
fromproject/requirements.txt
project/WORKSPACE.bazel: swap pip_install with pip_parse
project/build_rules/lambda_packaging/lambda.bzl: Modified custom rule provided by @jvolkman to include source code in the resulting zip code.
project/appcode/api/transaction_details/src/BUILD.bazel: Used custom
py_lambda_zip
rule to zip uppy_library