lambda-deps-builder 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lambda_deps_builder/__init__.py +4 -0
- lambda_deps_builder/builder_handler/__init__.py +0 -0
- lambda_deps_builder/builder_handler/handler.py +70 -0
- lambda_deps_builder/construct.py +187 -0
- lambda_deps_builder/example/__init__.py +0 -0
- lambda_deps_builder/example/app.py +16 -0
- lambda_deps_builder/example/consumer_handler/handler.py +6 -0
- lambda_deps_builder/example/example_stack.py +58 -0
- lambda_deps_builder/example/requirements_to_build.txt +1 -0
- lambda_deps_builder/py.typed +1 -0
- lambda_deps_builder-0.1.0.dist-info/METADATA +160 -0
- lambda_deps_builder-0.1.0.dist-info/RECORD +13 -0
- lambda_deps_builder-0.1.0.dist-info/WHEEL +4 -0
|
File without changes
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
import subprocess
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import boto3
|
|
8
|
+
|
|
9
|
+
_REQUIREMENTS_FILE = Path("/var/task/requirements.txt")
|
|
10
|
+
_BUILD_ROOT = Path("/tmp/build")
|
|
11
|
+
_ZIP_BASE = Path("/tmp/deps")
|
|
12
|
+
_ZIP_PATH = _ZIP_BASE.with_suffix(".zip")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def handler(event, context):
|
|
16
|
+
"""
|
|
17
|
+
Lambda entry point. Installs the bundled requirements.txt into a layer-shaped
|
|
18
|
+
directory, zips it, and uploads to S3 at the bucket/key supplied via environment.
|
|
19
|
+
|
|
20
|
+
:param event: Lambda invocation event (unused).
|
|
21
|
+
:param context: Lambda context (unused).
|
|
22
|
+
:return: `{"bucket": ..., "key": ..., "size": <bytes>}`.
|
|
23
|
+
"""
|
|
24
|
+
bucket_name = os.environ["BUCKET_NAME"]
|
|
25
|
+
object_key = os.environ["OBJECT_KEY"]
|
|
26
|
+
|
|
27
|
+
# Warm-container reuse can leave previous installs on /tmp; start clean so the
|
|
28
|
+
# produced zip reflects only the current requirements.txt.
|
|
29
|
+
if _BUILD_ROOT.exists():
|
|
30
|
+
shutil.rmtree(_BUILD_ROOT)
|
|
31
|
+
target = _BUILD_ROOT / "python"
|
|
32
|
+
target.mkdir(parents=True)
|
|
33
|
+
|
|
34
|
+
pip_env = {
|
|
35
|
+
**os.environ,
|
|
36
|
+
"PIP_DISABLE_PIP_VERSION_CHECK": "1",
|
|
37
|
+
"HOME": "/tmp",
|
|
38
|
+
}
|
|
39
|
+
subprocess.run(
|
|
40
|
+
[
|
|
41
|
+
sys.executable,
|
|
42
|
+
"-m",
|
|
43
|
+
"pip",
|
|
44
|
+
"install",
|
|
45
|
+
"-r",
|
|
46
|
+
str(_REQUIREMENTS_FILE),
|
|
47
|
+
"-t",
|
|
48
|
+
str(target),
|
|
49
|
+
"--no-cache-dir",
|
|
50
|
+
"--only-binary",
|
|
51
|
+
":all:",
|
|
52
|
+
],
|
|
53
|
+
check=True,
|
|
54
|
+
env=pip_env,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
if not any(target.iterdir()):
|
|
58
|
+
raise RuntimeError(
|
|
59
|
+
"pip install produced no files; requirements.txt is empty or matched no packages"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
shutil.make_archive(str(_ZIP_BASE), "zip", root_dir=str(_BUILD_ROOT), base_dir="python")
|
|
63
|
+
|
|
64
|
+
boto3.client("s3").upload_file(str(_ZIP_PATH), bucket_name, object_key)
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
"bucket": bucket_name,
|
|
68
|
+
"key": object_key,
|
|
69
|
+
"size": _ZIP_PATH.stat().st_size,
|
|
70
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import atexit
|
|
2
|
+
import shutil
|
|
3
|
+
import tempfile
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional, List
|
|
6
|
+
|
|
7
|
+
from aws_cdk import Duration, RemovalPolicy, Size
|
|
8
|
+
from aws_cdk import aws_lambda as lambda_
|
|
9
|
+
from aws_cdk import aws_s3 as s3
|
|
10
|
+
from aws_cdk import triggers
|
|
11
|
+
from constructs import Construct
|
|
12
|
+
|
|
13
|
+
_HANDLER_SOURCE_DIR = Path(__file__).parent / "builder_handler"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LambdaDepsBuilder(Construct):
|
|
17
|
+
"""
|
|
18
|
+
Builds Python Lambda dependencies inside an AWS Lambda matching the target runtime
|
|
19
|
+
and architecture, uploads the resulting layer-shaped zip to S3, and exposes it as
|
|
20
|
+
`aws_lambda.Code` / `aws_lambda.LayerVersion` for use in the same stack — no local
|
|
21
|
+
Docker required.
|
|
22
|
+
|
|
23
|
+
:param scope: parent construct.
|
|
24
|
+
:param construct_id: construct id.
|
|
25
|
+
:param requirements_txt_file: path on the developer machine to a requirements.txt
|
|
26
|
+
whose dependencies should be installed inside Lambda.
|
|
27
|
+
:param target_runtime: the Lambda runtime to build for. Pip resolves wheels matching
|
|
28
|
+
this runtime's Python version.
|
|
29
|
+
:param target_architecture: the Lambda architecture to build for. The build runs on
|
|
30
|
+
a Lambda of this architecture so pip selects matching wheels (x86_64 vs arm64).
|
|
31
|
+
:param deps_bucket: optional pre-existing bucket to upload into. A bucket is
|
|
32
|
+
auto-created when omitted. NOTE: a caller-supplied bucket without
|
|
33
|
+
``auto_delete_objects=True`` will fail to destroy because the trigger leaves
|
|
34
|
+
the zip behind; ensure the bucket can be emptied.
|
|
35
|
+
:param output_key: S3 key for the produced zip. Defaults to
|
|
36
|
+
``deps-{ARCH}-{construct_id}.zip`` so sibling builders sharing a bucket never
|
|
37
|
+
collide regardless of architecture or requirements.
|
|
38
|
+
:param build_timeout: timeout for the build Lambda. Increase for large requirement
|
|
39
|
+
sets that take long to install.
|
|
40
|
+
:param build_memory_mb: memory for the build Lambda.
|
|
41
|
+
:param ephemeral_storage_gib: size of `/tmp` inside the build Lambda. Lambda's
|
|
42
|
+
default is 0.5 GiB; raise for large dep trees.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
scope: Construct,
|
|
48
|
+
construct_id: str,
|
|
49
|
+
*,
|
|
50
|
+
requirements_txt_file: Path,
|
|
51
|
+
target_runtime: lambda_.Runtime = lambda_.Runtime.PYTHON_3_12,
|
|
52
|
+
target_architecture: lambda_.Architecture = lambda_.Architecture.X86_64,
|
|
53
|
+
deps_bucket: Optional[s3.IBucket] = None,
|
|
54
|
+
output_key: Optional[str] = None,
|
|
55
|
+
build_timeout: Duration = Duration.minutes(5),
|
|
56
|
+
build_memory_mb: int = 1024,
|
|
57
|
+
ephemeral_storage_gib: int = 4,
|
|
58
|
+
) -> None:
|
|
59
|
+
super().__init__(scope, construct_id)
|
|
60
|
+
|
|
61
|
+
if not requirements_txt_file.is_file():
|
|
62
|
+
raise FileNotFoundError(
|
|
63
|
+
f"requirements_txt_file does not exist: {requirements_txt_file}"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
self._target_architecture = target_architecture
|
|
67
|
+
self._deps_key = (
|
|
68
|
+
output_key
|
|
69
|
+
if output_key is not None
|
|
70
|
+
else f"deps-{target_architecture.name}-{construct_id}.zip"
|
|
71
|
+
)
|
|
72
|
+
self._target_runtime = target_runtime
|
|
73
|
+
|
|
74
|
+
if deps_bucket is None:
|
|
75
|
+
deps_bucket = s3.Bucket(
|
|
76
|
+
self,
|
|
77
|
+
"DepsBucket",
|
|
78
|
+
auto_delete_objects=True,
|
|
79
|
+
removal_policy=RemovalPolicy.DESTROY,
|
|
80
|
+
block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
|
|
81
|
+
enforce_ssl=True,
|
|
82
|
+
)
|
|
83
|
+
self._deps_bucket = deps_bucket
|
|
84
|
+
|
|
85
|
+
staged_asset_dir = _stage_handler_asset(requirements_txt_file)
|
|
86
|
+
|
|
87
|
+
self._trigger = triggers.TriggerFunction(
|
|
88
|
+
self,
|
|
89
|
+
"Builder",
|
|
90
|
+
runtime=target_runtime,
|
|
91
|
+
architecture=target_architecture,
|
|
92
|
+
handler="handler.handler",
|
|
93
|
+
code=lambda_.Code.from_asset(staged_asset_dir),
|
|
94
|
+
timeout=build_timeout,
|
|
95
|
+
memory_size=build_memory_mb,
|
|
96
|
+
ephemeral_storage_size=Size.gibibytes(ephemeral_storage_gib),
|
|
97
|
+
environment={
|
|
98
|
+
"BUCKET_NAME": deps_bucket.bucket_name,
|
|
99
|
+
"OBJECT_KEY": self._deps_key,
|
|
100
|
+
},
|
|
101
|
+
)
|
|
102
|
+
deps_bucket.grant_put(self._trigger, objects_key_pattern=self._deps_key)
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def target_architecture(self) -> lambda_.Architecture:
|
|
106
|
+
return self._target_architecture
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def deps_bucket(self) -> s3.IBucket:
|
|
110
|
+
return self._deps_bucket
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def deps_key(self) -> str:
|
|
114
|
+
return self._deps_key
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def trigger(self) -> triggers.TriggerFunction:
|
|
118
|
+
return self._trigger
|
|
119
|
+
|
|
120
|
+
def as_layer_version(
|
|
121
|
+
self,
|
|
122
|
+
scope: Construct,
|
|
123
|
+
construct_id: str,
|
|
124
|
+
*,
|
|
125
|
+
compatible_runtimes: Optional[List[lambda_.Runtime]] = None,
|
|
126
|
+
) -> lambda_.LayerVersion:
|
|
127
|
+
"""
|
|
128
|
+
Build a `LayerVersion` whose code is the S3 zip produced by the trigger.
|
|
129
|
+
|
|
130
|
+
:param scope: parent construct for the LayerVersion.
|
|
131
|
+
:param construct_id: construct id for the LayerVersion.
|
|
132
|
+
:param compatible_runtimes: optional override; defaults to `[target_runtime]`.
|
|
133
|
+
Pass an empty list to publish a layer with no runtime restriction.
|
|
134
|
+
:return: a LayerVersion that depends on the trigger so CFN waits for the build.
|
|
135
|
+
"""
|
|
136
|
+
runtimes = (
|
|
137
|
+
compatible_runtimes
|
|
138
|
+
if compatible_runtimes is not None
|
|
139
|
+
else [self._target_runtime]
|
|
140
|
+
)
|
|
141
|
+
layer = lambda_.LayerVersion(
|
|
142
|
+
scope,
|
|
143
|
+
construct_id,
|
|
144
|
+
code=lambda_.Code.from_bucket(self._deps_bucket, self._deps_key),
|
|
145
|
+
compatible_runtimes=runtimes,
|
|
146
|
+
compatible_architectures=[self._target_architecture],
|
|
147
|
+
)
|
|
148
|
+
layer.node.add_dependency(self._trigger)
|
|
149
|
+
return layer
|
|
150
|
+
|
|
151
|
+
def as_function_code(self) -> lambda_.Code:
|
|
152
|
+
"""
|
|
153
|
+
Return a `lambda_.Code` referencing the built S3 zip. Prefer
|
|
154
|
+
:meth:`attach_to_function`, which also wires the CDK dependency on the trigger.
|
|
155
|
+
Use this lower-level helper only when you can't access the consuming Function
|
|
156
|
+
at the call site, and remember to call ``fn.node.add_dependency(self.trigger)``
|
|
157
|
+
yourself or CFN may try to create the Function before the upload exists.
|
|
158
|
+
"""
|
|
159
|
+
return lambda_.Code.from_bucket(self._deps_bucket, self._deps_key)
|
|
160
|
+
|
|
161
|
+
def attach_to_function(self, function: lambda_.Function) -> None:
|
|
162
|
+
"""
|
|
163
|
+
Wire an existing Function's code to the built deps zip and add the CDK
|
|
164
|
+
dependency on the trigger so CFN creates the Function only after the upload.
|
|
165
|
+
|
|
166
|
+
:param function: the Function whose code should be the built deps zip.
|
|
167
|
+
"""
|
|
168
|
+
function.node.add_dependency(self._trigger)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _stage_handler_asset(requirements_txt_file: Path) -> str:
|
|
172
|
+
"""
|
|
173
|
+
Copy the in-Lambda handler module and the user's requirements file into a fresh
|
|
174
|
+
directory so they can be packaged as a single asset. The directory contents
|
|
175
|
+
determine the asset hash, so changes to requirements.txt re-fire the trigger.
|
|
176
|
+
|
|
177
|
+
The temp directory is registered for cleanup at process exit, since CDK only
|
|
178
|
+
needs to read it during synth.
|
|
179
|
+
|
|
180
|
+
:param requirements_txt_file: user-supplied requirements file.
|
|
181
|
+
:return: path to the staged directory as a string for `Code.from_asset`.
|
|
182
|
+
"""
|
|
183
|
+
staged_dir = Path(tempfile.mkdtemp(prefix="lambda-deps-builder-"))
|
|
184
|
+
atexit.register(shutil.rmtree, staged_dir, ignore_errors=True)
|
|
185
|
+
shutil.copy(_HANDLER_SOURCE_DIR / "handler.py", staged_dir / "handler.py")
|
|
186
|
+
shutil.copy(requirements_txt_file, staged_dir / "requirements.txt")
|
|
187
|
+
return str(staged_dir)
|
|
File without changes
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import aws_cdk as cdk
|
|
4
|
+
|
|
5
|
+
from lambda_deps_builder.example.example_stack import ExampleStack
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main() -> None:
|
|
9
|
+
app = cdk.App()
|
|
10
|
+
stack_name = os.environ.get("STACK_NAME", "LambdaDepsBuilderExample")
|
|
11
|
+
ExampleStack(app, stack_name)
|
|
12
|
+
app.synth()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
if __name__ == "__main__":
|
|
16
|
+
main()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from aws_cdk import CfnOutput, Duration, RemovalPolicy, Stack
|
|
4
|
+
from aws_cdk import aws_lambda as lambda_
|
|
5
|
+
from aws_cdk import aws_s3 as s3
|
|
6
|
+
from constructs import Construct
|
|
7
|
+
|
|
8
|
+
from lambda_deps_builder import LambdaDepsBuilder
|
|
9
|
+
|
|
10
|
+
_HERE = Path(__file__).parent
|
|
11
|
+
_REQUIREMENTS = _HERE / "requirements_to_build.txt"
|
|
12
|
+
_CONSUMER_DIR = _HERE / "consumer_handler"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ExampleStack(Stack):
|
|
16
|
+
"""Builds `requests` for both x86_64 and arm64 and wires a consumer Lambda per arch."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
|
|
19
|
+
super().__init__(scope, construct_id, **kwargs)
|
|
20
|
+
|
|
21
|
+
shared_bucket = s3.Bucket(
|
|
22
|
+
self,
|
|
23
|
+
"DepsBucket",
|
|
24
|
+
auto_delete_objects=True,
|
|
25
|
+
removal_policy=RemovalPolicy.DESTROY,
|
|
26
|
+
block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
|
|
27
|
+
enforce_ssl=True,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
for arch_name, arch in [
|
|
31
|
+
("X86", lambda_.Architecture.X86_64),
|
|
32
|
+
("Arm", lambda_.Architecture.ARM_64),
|
|
33
|
+
]:
|
|
34
|
+
builder = LambdaDepsBuilder(
|
|
35
|
+
self,
|
|
36
|
+
f"RequestsDeps{arch_name}",
|
|
37
|
+
requirements_txt_file=_REQUIREMENTS,
|
|
38
|
+
target_runtime=lambda_.Runtime.PYTHON_3_12,
|
|
39
|
+
target_architecture=arch,
|
|
40
|
+
deps_bucket=shared_bucket,
|
|
41
|
+
)
|
|
42
|
+
layer = builder.as_layer_version(self, f"RequestsLayer{arch_name}")
|
|
43
|
+
|
|
44
|
+
consumer = lambda_.Function(
|
|
45
|
+
self,
|
|
46
|
+
f"Consumer{arch_name}",
|
|
47
|
+
runtime=lambda_.Runtime.PYTHON_3_12,
|
|
48
|
+
architecture=arch,
|
|
49
|
+
handler="handler.handler",
|
|
50
|
+
code=lambda_.Code.from_asset(str(_CONSUMER_DIR)),
|
|
51
|
+
layers=[layer],
|
|
52
|
+
timeout=Duration.seconds(15),
|
|
53
|
+
)
|
|
54
|
+
CfnOutput(
|
|
55
|
+
self,
|
|
56
|
+
f"Consumer{arch_name}FunctionName",
|
|
57
|
+
value=consumer.function_name,
|
|
58
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
requests==2.32.3
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Marker file for PEP 561.
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: lambda-deps-builder
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CDK construct that builds Python Lambda dependencies inside Lambda — no local Docker.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Keywords: aws,cdk,lambda,dependencies,dockerless,layer
|
|
7
|
+
Author: Alexy Grabov
|
|
8
|
+
Author-email: alexy.grabov@gmail.com
|
|
9
|
+
Requires-Python: >=3.11,<4.0
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Dist: aws-cdk-lib (>=2.150.0)
|
|
21
|
+
Requires-Dist: constructs (>=10.0.0)
|
|
22
|
+
Project-URL: Homepage, https://github.com/CoreOxide/poc/tree/main/lambda_deps_builder
|
|
23
|
+
Project-URL: Repository, https://github.com/CoreOxide/poc
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# lambda_deps_builder
|
|
27
|
+
|
|
28
|
+
A CDK construct that builds Python Lambda dependencies **inside an actual AWS Lambda** during `cdk deploy` — no local Docker, no platform mismatch, no cross-compile gymnastics.
|
|
29
|
+
|
|
30
|
+
## What it solves
|
|
31
|
+
|
|
32
|
+
Building Python Lambda packages on Windows or on a developer machine without Docker produces wheels that fail on Lambda's Linux runtime. The standard CDK answers all have caveats:
|
|
33
|
+
|
|
34
|
+
| Approach | Where deps are resolved | Local prerequisites | Cross-platform safe? |
|
|
35
|
+
|---|---|---|---|
|
|
36
|
+
| `lambda.Code.from_asset(local_pip_install_dir)` | Dev machine | Python + pip | **No** — native wheels often wrong |
|
|
37
|
+
| `aws_lambda_python_alpha.PythonFunction` | Local Docker container | **Docker daemon** | Yes (Docker does the cross-build) |
|
|
38
|
+
| `aws_lambda_nodejs.NodejsFunction` | Local esbuild (or Docker fallback) | Node.js + esbuild (or Docker) | Yes (JS is mostly platform-agnostic) |
|
|
39
|
+
| **`LambdaDepsBuilder` (this POC)** | **Inside AWS Lambda, during `cdk deploy`** | **None beyond CDK** | Yes — by definition |
|
|
40
|
+
|
|
41
|
+
The build runs on the same Lambda runtime + architecture that will execute the deps, so `pip` selects matching wheels automatically.
|
|
42
|
+
|
|
43
|
+
## Architecture
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
synth ──> CDK creates: S3 bucket
|
|
47
|
+
+ TriggerFunction(runtime=python3.12, architecture=X)
|
|
48
|
+
+ LayerVersion(code=fromBucket, compatible_architectures=[X])
|
|
49
|
+
deploy ──> 1. CFN creates bucket
|
|
50
|
+
2. CFN creates the TriggerFunction (handler asset bundles requirements.txt)
|
|
51
|
+
3. Triggers framework invokes the function ONCE, synchronously, on AWS Lambda
|
|
52
|
+
└─ handler runs ON ARCHITECTURE X:
|
|
53
|
+
pip install -r requirements.txt -t /tmp/build/python
|
|
54
|
+
zip /tmp/build → /tmp/deps.zip
|
|
55
|
+
s3.put_object(Bucket=..., Key=deps-X.zip)
|
|
56
|
+
4. CFN creates LayerVersion (depends_on the trigger) → reads zip from S3
|
|
57
|
+
5. Consumer Function(architecture=X, layers=[layer]) runs with matching deps
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The trigger re-fires whenever `requirements.txt` changes (its content is part of the staged asset hash) or whenever the architecture changes.
|
|
61
|
+
|
|
62
|
+
## Usage
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from pathlib import Path
|
|
66
|
+
from aws_cdk import Stack, Duration
|
|
67
|
+
from aws_cdk import aws_lambda as lambda_
|
|
68
|
+
from lambda_deps_builder import LambdaDepsBuilder
|
|
69
|
+
|
|
70
|
+
class MyStack(Stack):
|
|
71
|
+
def __init__(self, scope, id, **kwargs):
|
|
72
|
+
super().__init__(scope, id, **kwargs)
|
|
73
|
+
|
|
74
|
+
builder = LambdaDepsBuilder(
|
|
75
|
+
self, "Deps",
|
|
76
|
+
requirements_txt_file=Path(__file__).parent / "requirements.txt",
|
|
77
|
+
target_runtime=lambda_.Runtime.PYTHON_3_12,
|
|
78
|
+
target_architecture=lambda_.Architecture.ARM_64, # or X86_64
|
|
79
|
+
)
|
|
80
|
+
layer = builder.as_layer_version(self, "DepsLayer")
|
|
81
|
+
|
|
82
|
+
lambda_.Function(
|
|
83
|
+
self, "Fn",
|
|
84
|
+
runtime=lambda_.Runtime.PYTHON_3_12,
|
|
85
|
+
architecture=lambda_.Architecture.ARM_64,
|
|
86
|
+
handler="handler.handler",
|
|
87
|
+
code=lambda_.Code.from_asset("./my_handler"),
|
|
88
|
+
layers=[layer],
|
|
89
|
+
timeout=Duration.seconds(15),
|
|
90
|
+
)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
That's it — `cdk deploy`, and the consumer Function imports its dependencies on the next invocation.
|
|
94
|
+
|
|
95
|
+
## Architecture support
|
|
96
|
+
|
|
97
|
+
Pass `target_architecture=lambda_.Architecture.ARM_64` for Graviton consumers. The construct:
|
|
98
|
+
|
|
99
|
+
- runs the build Lambda on the chosen architecture, so `pip` picks `aarch64` wheels for compiled extensions like `pydantic-core`, `cryptography`, `numpy`;
|
|
100
|
+
- sets `compatible_architectures=[chosen]` on the LayerVersion so Lambda rejects mismatched consumers at attach time (instead of a confusing runtime `ImportError`);
|
|
101
|
+
- defaults `output_key` to `deps-{ARCH}.zip` so two builders sharing one bucket don't overwrite each other.
|
|
102
|
+
|
|
103
|
+
The example stack builds for both x86_64 and arm64 off a shared bucket — see `lambda_deps_builder/example/example_stack.py`.
|
|
104
|
+
|
|
105
|
+
## Why no Node.js variant?
|
|
106
|
+
|
|
107
|
+
`aws_cdk.aws_lambda_nodejs.NodejsFunction` already handles the JS case adequately:
|
|
108
|
+
|
|
109
|
+
- it uses **esbuild** to bundle handler code + tree-shaken deps into a single asset;
|
|
110
|
+
- if esbuild is on the dev machine, the entire bundle (including `npm install` of `bundling.nodeModules`) runs **locally** with no Docker;
|
|
111
|
+
- if esbuild is missing, it transparently falls back to bundling **inside a local Docker container** based on the Node.js Lambda image;
|
|
112
|
+
- JS deps are overwhelmingly pure JS, so platform mismatch is rarely an issue. For the rare native module (`sharp`), the Docker fallback handles it.
|
|
113
|
+
|
|
114
|
+
So the JS pain point this POC would address (Linux-native compiled deps) is largely absent in Node.js and well-handled by `NodejsFunction` for the few cases where it matters. **Use `NodejsFunction` for JS Lambdas.**
|
|
115
|
+
|
|
116
|
+
## Running the example
|
|
117
|
+
|
|
118
|
+
```shell
|
|
119
|
+
cd lambda_deps_builder
|
|
120
|
+
poetry install
|
|
121
|
+
poetry run cdk deploy
|
|
122
|
+
# invoke either consumer to confirm `requests` is importable on Lambda:
|
|
123
|
+
aws lambda invoke \
|
|
124
|
+
--function-name "$(aws cloudformation describe-stacks \
|
|
125
|
+
--stack-name LambdaDepsBuilderExample \
|
|
126
|
+
--query "Stacks[0].Outputs[?OutputKey=='ConsumerX86FunctionName'].OutputValue" \
|
|
127
|
+
--output text)" \
|
|
128
|
+
/tmp/out.json && cat /tmp/out.json
|
|
129
|
+
poetry run cdk destroy
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## Running tests
|
|
133
|
+
|
|
134
|
+
```shell
|
|
135
|
+
poetry install
|
|
136
|
+
poetry run pytest -v # fast tests: synth + handler unit tests, no AWS
|
|
137
|
+
poetry run pytest -v -m e2e # the real-AWS E2E test (deploys, invokes, destroys)
|
|
138
|
+
poetry run pytest -v -m '' # everything (default suite + e2e)
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
`pyproject.toml` sets `addopts = -m 'not e2e'` so a plain `pytest` skips the E2E test by default.
|
|
142
|
+
|
|
143
|
+
The default suite is pure-Python (CDK assertion templates + mocked handler) — no AWS, no Docker.
|
|
144
|
+
|
|
145
|
+
The E2E test (`tests/test_e2e_deploy.py`):
|
|
146
|
+
|
|
147
|
+
- requires the `cdk` CLI on `PATH`, AWS credentials, and the target account/region bootstrapped (`cdk bootstrap` once);
|
|
148
|
+
- deploys a uniquely-named stack via `cdk deploy --require-approval never`;
|
|
149
|
+
- invokes both consumer Lambdas (x86_64 and arm64) and asserts each returns `{"status": 200, ...}` — proving `requests` was built on Linux Lambda and is importable from a separate consumer Lambda;
|
|
150
|
+
- destroys the stack in a `finally` block so a failed deploy or assertion still cleans up;
|
|
151
|
+
- takes ~2–3 minutes per run.
|
|
152
|
+
|
|
153
|
+
## Caveats
|
|
154
|
+
|
|
155
|
+
- **Lambda layer size limit (250 MB unzipped)** — `pandas` + `numpy` together exceed this. For large dep sets, use a container image Lambda instead.
|
|
156
|
+
- **`/tmp` size** — defaults to 0.5 GiB on Lambda; raise `ephemeral_storage_gib` for big trees.
|
|
157
|
+
- **First-deploy latency** — the trigger invocation adds ~30–60 s to the first deploy (and to any deploy where requirements changed).
|
|
158
|
+
- **Cost is negligible** — a one-shot Lambda invocation per deploy and a tiny S3 object.
|
|
159
|
+
- **Two architectures = two builders** — cheap, but the example shows the pattern explicitly.
|
|
160
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
lambda_deps_builder/__init__.py,sha256=hQZAYuKqOOhDzktmfKXP98vv6T04SvBAbcAtU1VUf8o,130
|
|
2
|
+
lambda_deps_builder/builder_handler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
lambda_deps_builder/builder_handler/handler.py,sha256=tRbgugxI8ZFOn6Z4aMVpassWNUkRXmsSo3CNKe5RIQY,1919
|
|
4
|
+
lambda_deps_builder/construct.py,sha256=vz8igvsidhzO-_CaqcCfaEsZ1na5vpA61AglyhAD1iY,7597
|
|
5
|
+
lambda_deps_builder/example/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
lambda_deps_builder/example/app.py,sha256=ICCd-OOsNvxCrGiubjNR3OnNCan9x2XYV4Vbf2ddvaw,307
|
|
7
|
+
lambda_deps_builder/example/consumer_handler/handler.py,sha256=D6FXzYU1VsUqEOBCzFuYB8HYXdiS6EQMNvnWnmrwzmc,180
|
|
8
|
+
lambda_deps_builder/example/example_stack.py,sha256=fEqfdLe2Sa_yhsPWvNMcL5dWKJoZ3Sb_zcIdjo7yW-M,1996
|
|
9
|
+
lambda_deps_builder/example/requirements_to_build.txt,sha256=S4GDEB_RnwcXcYBaQqMfuyNKeWGSH9uLeDonl1WhtdU,17
|
|
10
|
+
lambda_deps_builder/py.typed,sha256=bWew9mHgMy8LqMu7RuqQXFXLBxh2CRx0dUbSx-3wE48,27
|
|
11
|
+
lambda_deps_builder-0.1.0.dist-info/METADATA,sha256=S-eejPv8cqQCo3Xfm4miqWWkYCsPmCN0JD2BgfHCHIM,7956
|
|
12
|
+
lambda_deps_builder-0.1.0.dist-info/WHEEL,sha256=eY7nduwzv-ldUxpzbRlxwvC693Hg6PX8bWDjEHjZ_dk,88
|
|
13
|
+
lambda_deps_builder-0.1.0.dist-info/RECORD,,
|