Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(lambda-python): bundle dependencies in a lambda layer #9582

Merged
merged 68 commits into from
Oct 12, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
68 commits
Select commit Hold shift + click to select a range
b724a26
feat(aws-lambda-python): add support for placing python dependencies …
misterjoshua Aug 11, 2020
4b96baa
Add compatibleRuntimes to the lambda layer
misterjoshua Aug 11, 2020
fd3025d
Review changes and add pipenv support
misterjoshua Aug 11, 2020
f2f6fa3
Insert the pipenvHome directory into the bundling output directory an…
misterjoshua Aug 11, 2020
61a03b8
Try invoking pipenv via python -m pipenv
misterjoshua Aug 11, 2020
fdf70c4
README.md and a spelling fix
misterjoshua Aug 11, 2020
faa3db9
Integ tests for pipenv layers on each runtime and fix asset hash issues
misterjoshua Aug 11, 2020
a31d44c
Move pipenv install to an image that extends from the runtime bundlin…
misterjoshua Aug 14, 2020
2edf744
Trial installing dependencies in a docker build
misterjoshua Aug 16, 2020
a3b8fc5
Fix some comments and un-expose some functions we don't need to expose.
misterjoshua Aug 16, 2020
f52c25b
Add back my layer bundling test
misterjoshua Aug 16, 2020
f3a6e39
Merge branch 'master' into lambda-python-layers
misterjoshua Aug 17, 2020
236186b
Fix accidental disable of import order linting rule
misterjoshua Aug 17, 2020
ff8594f
Add #9763's convenient FROM build arg defaults
misterjoshua Aug 17, 2020
ec8f9cc
Apply suggestions from code review
misterjoshua Aug 19, 2020
d47cb34
Merge branch 'master' into lambda-python-layers
misterjoshua Aug 19, 2020
c742923
Install rsync if necessary
misterjoshua Aug 19, 2020
a7a1e4f
Change the default dependenciesLocation to LAYER
misterjoshua Aug 19, 2020
3a1ffe7
Merge branch 'master' into lambda-python-layers
misterjoshua Aug 21, 2020
628c38a
Merge branch 'master' into lambda-python-layers
misterjoshua Aug 24, 2020
5ff6199
Add an integ test that checks dependency removal
misterjoshua Aug 26, 2020
02208e2
Change the integ test to check a layer instead
misterjoshua Aug 26, 2020
12a367f
Merge branch 'master' into lambda-python-layers
misterjoshua Aug 26, 2020
53ca44e
Merge branch 'master' into lambda-python-layers
misterjoshua Aug 26, 2020
ba98c9c
Merge branch 'master' of github.com:aws/aws-cdk into lambda-python-la…
misterjoshua Aug 27, 2020
92f3658
Change the dependency removal integ to synth twice
misterjoshua Aug 27, 2020
5b95db6
Point the custom dockerfile name test to a real directory
misterjoshua Aug 27, 2020
0a9facf
Simplify the bundling code
misterjoshua Aug 27, 2020
3f9b271
Add PythonDependencyLayer and PythonSharedCodeLayer
misterjoshua Aug 27, 2020
b0b8f72
Fix compatibleRuntimes in PythonDependenciesLayer
misterjoshua Aug 27, 2020
dd9a3c3
Merge branch 'master' of github.com:aws/aws-cdk into lambda-python-la…
misterjoshua Aug 27, 2020
1fb4a5c
Merge layer constructs into PythonLayerVersion
misterjoshua Aug 27, 2020
c69216a
Inline docs and cleanup
misterjoshua Aug 27, 2020
bac8dee
Add readonly to bundling functions options
misterjoshua Aug 27, 2020
0aba325
Match up a code style
misterjoshua Aug 27, 2020
830ce8a
Merge branch 'master' of github.com:aws/aws-cdk into lambda-python-la…
misterjoshua Aug 27, 2020
257b657
Convert function to use the python layer for bundling dependencies
misterjoshua Aug 27, 2020
217be2a
Change layer test to compare readDirSync outputs to enhance error vis…
misterjoshua Aug 27, 2020
3be7e09
Add more tests
misterjoshua Aug 27, 2020
d0a9e40
Fix the PythonCodeLocalBundler rename I forgot to include. whoops.
misterjoshua Aug 27, 2020
b020cd7
Remove the dependency on @aws-cdk/assets
misterjoshua Aug 27, 2020
988b5ea
Decrease assetHash thrashing based on cwd
misterjoshua Aug 27, 2020
281d365
Remove DependenciesLocation, consolidate bundling
misterjoshua Aug 28, 2020
dbfc2af
Merge branch 'master' of github.com:aws/aws-cdk into lambda-python-la…
misterjoshua Aug 28, 2020
a940c85
Add more explanation for the two Dockerfiles
misterjoshua Aug 28, 2020
e7cce93
Restore more of the original code
misterjoshua Aug 28, 2020
f793c90
Update the readme
misterjoshua Aug 28, 2020
90290b9
Consolidate bundle*Layer fns into bundleLayer
misterjoshua Aug 28, 2020
942c615
Remove extraneous text fixtures
misterjoshua Aug 28, 2020
f0ac60f
Remove extraneous cdk.CopyOptions from PythonLayerVersionProps
misterjoshua Aug 28, 2020
acee7f9
Reword some of the readme, add missing semicolon.
misterjoshua Aug 28, 2020
3ecdaab
Consolidate bundle{Function,Layer} into bundle
misterjoshua Aug 29, 2020
faa0771
Fix typo in PythonLayerVersionProps docblock
misterjoshua Aug 29, 2020
d55cb8c
Add lambda.LayerVersionOptions and extend from it
misterjoshua Aug 29, 2020
9669e32
Add a test to cover layer runtime checking exceptions
misterjoshua Aug 29, 2020
dd2e1c5
Merge branch 'master' into lambda-python-layers
misterjoshua Sep 1, 2020
e04b07a
Update vpc test expected json
misterjoshua Sep 1, 2020
045556c
Merge branch 'master' into lambda-python-layers
misterjoshua Sep 1, 2020
191a013
Merge branch 'master' into lambda-python-layers
misterjoshua Sep 6, 2020
af8a79a
Merge branch 'master' into lambda-python-layers
misterjoshua Sep 18, 2020
d9e0f68
Fix variable destructuring oversight
misterjoshua Sep 18, 2020
8747b6b
Merge branch 'master' into lambda-python-layers
misterjoshua Sep 27, 2020
466cae6
Update integ expectations
misterjoshua Sep 27, 2020
f2c74d4
Merge branch 'master' of github.com:aws/aws-cdk into lambda-python-la…
misterjoshua Oct 6, 2020
1eca86b
fix: stacks have changed
misterjoshua Oct 6, 2020
9c2d272
Merge branch 'master' into lambda-python-layers
misterjoshua Oct 11, 2020
d4da14c
fix: duplicate identifier path
misterjoshua Oct 11, 2020
a82411d
Merge branch 'master' into lambda-python-layers
mergify[bot] Oct 12, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 33 additions & 1 deletion packages/@aws-cdk/aws-lambda-python/lib/bundling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ export interface BundlingOptions {
* The runtime of the lambda function
*/
readonly runtime: lambda.Runtime;

/**
* Install dependencies while bundling
*/
readonly installDependencies: boolean;
}

/**
Expand All @@ -25,9 +30,10 @@ export function bundle(options: BundlingOptions): lambda.AssetCode {
let installer = options.runtime === lambda.Runtime.PYTHON_2_7 ? Installer.PIP : Installer.PIP3;

let hasRequirements = fs.existsSync(path.join(options.entry, 'requirements.txt'));
let installDependencies = options.installDependencies;

let depsCommand = chain([
hasRequirements ? `${installer} install -r requirements.txt -t ${cdk.AssetStaging.BUNDLING_OUTPUT_DIR}` : '',
hasRequirements && installDependencies ? `${installer} install -r requirements.txt -t ${cdk.AssetStaging.BUNDLING_OUTPUT_DIR}` : '',
`cp -au . ${cdk.AssetStaging.BUNDLING_OUTPUT_DIR}`,
]);

Expand All @@ -47,3 +53,29 @@ enum Installer {
function chain(commands: string[]): string {
return commands.filter(c => !!c).join(' && ');
}

export interface DependencyBundlingOptions {
/**
* Entry path
*/
readonly entry: string;

/**
* The runtime of the lambda function
*/
readonly runtime: lambda.Runtime;
}
export function bundleDependencies(options: DependencyBundlingOptions): lambda.AssetCode {
let installer = options.runtime === lambda.Runtime.PYTHON_2_7 ? Installer.PIP : Installer.PIP3;
let depsCommand = chain([
`${installer} install -r requirements.txt -t ${cdk.AssetStaging.BUNDLING_OUTPUT_DIR}/python`,
]);

return lambda.Code.fromAsset(options.entry, {
bundling: {
image: options.runtime.bundlingDockerImage,
command: ['bash', '-c', depsCommand],
},
exclude: ['*', '!requirements.txt'],
});
}
27 changes: 26 additions & 1 deletion packages/@aws-cdk/aws-lambda-python/lib/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as fs from 'fs';
import * as path from 'path';
import * as lambda from '@aws-cdk/aws-lambda';
import * as cdk from '@aws-cdk/core';
import { bundle } from './bundling';
import { bundle, bundleDependencies } from './bundling';

/**
* Properties for a PythonFunction
Expand Down Expand Up @@ -34,6 +34,18 @@ export interface PythonFunctionProps extends lambda.FunctionOptions {
* @default lambda.Runtime.PYTHON_3_7
*/
readonly runtime?: lambda.Runtime;

/**
* Install dependencies
* @default true
*/
readonly installDependencies?: boolean;

/**
* Use a dependency lambda layer for packages.
* @default false
*/
readonly useDependencyLayer?: boolean;
misterjoshua marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand All @@ -59,6 +71,8 @@ export class PythonFunction extends lambda.Function {

const handler = props.handler ?? 'handler';
const runtime = props.runtime ?? lambda.Runtime.PYTHON_3_7;
const useDependencyLayer = props.useDependencyLayer ?? false;
const installDependencies = props.installDependencies ?? true;

super(scope, id, {
...props,
Expand All @@ -67,8 +81,19 @@ export class PythonFunction extends lambda.Function {
...props,
entry,
runtime,
installDependencies: !useDependencyLayer && installDependencies,
}),
handler: `${index.slice(0, -3)}.${handler}`,
});

if (installDependencies && useDependencyLayer && fs.existsSync(path.join(entry, 'requirements.txt'))) {
misterjoshua marked this conversation as resolved.
Show resolved Hide resolved
this.addLayers(new lambda.LayerVersion(this, 'Dependencies', {
compatibleRuntimes: [runtime],
code: bundleDependencies({
entry,
runtime,
}),
}));
}
}
}
48 changes: 47 additions & 1 deletion packages/@aws-cdk/aws-lambda-python/test/bundling.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as fs from 'fs';
import { Code, Runtime } from '@aws-cdk/aws-lambda';
import { bundle } from '../lib/bundling';
import { bundle, bundleDependencies } from '../lib/bundling';

jest.mock('@aws-cdk/aws-lambda');
const existsSyncOriginal = fs.existsSync;
Expand All @@ -14,6 +14,7 @@ test('Bundling', () => {
bundle({
entry: '/project/folder',
runtime: Runtime.PYTHON_3_7,
installDependencies: true,
});

// Correctly bundles
Expand Down Expand Up @@ -41,6 +42,7 @@ test('Bundling with requirements.txt installed', () => {
bundle({
entry: '/project/folder',
runtime: Runtime.PYTHON_3_7,
installDependencies: true,
});

// Correctly bundles with requirements.txt pip installed
Expand All @@ -65,6 +67,7 @@ test('Bundling Python 2.7 with requirements.txt installed', () => {
bundle({
entry: '/project/folder',
runtime: Runtime.PYTHON_2_7,
installDependencies: true,
});

// Correctly bundles with requirements.txt pip installed
Expand All @@ -77,3 +80,46 @@ test('Bundling Python 2.7 with requirements.txt installed', () => {
}),
});
});

test('Bundling can dependencies can be switched off', () => {
existsSyncMock.mockImplementation((p: fs.PathLike) => {
if (/requirements.txt/.test(p.toString())) {
return true;
}
return existsSyncOriginal(p);
});

bundle({
entry: '/project/folder',
runtime: Runtime.PYTHON_3_7,
installDependencies: false,
});

// Does not install dependencies when instructed not to.
expect(Code.fromAsset).toHaveBeenCalledWith('/project/folder', {
bundling: expect.objectContaining({
command: [
'bash', '-c',
'cp -au . /asset-output',
],
}),
});
});

test('Bundling dependencies for a lambda layer', () => {

bundleDependencies({
entry: '/project/folder',
runtime: Runtime.PYTHON_3_7,
});

expect(Code.fromAsset).toHaveBeenCalledWith('/project/folder', {
bundling: expect.objectContaining({
command: [
'bash', '-c',
'pip3 install -r requirements.txt -t /asset-output/python',
],
}),
exclude: ['*', '!requirements.txt'],
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
{
"Resources": {
"myhandlerServiceRole77891068": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
}
}
],
"Version": "2012-10-17"
},
"ManagedPolicyArns": [
{
"Fn::Join": [
"",
[
"arn:",
{
"Ref": "AWS::Partition"
},
":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
]
]
}
]
}
},
"myhandlerD202FA8E": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"S3Bucket": {
"Ref": "AssetParameters4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5fS3Bucket2F5C84CD"
},
"S3Key": {
"Fn::Join": [
"",
[
{
"Fn::Select": [
0,
{
"Fn::Split": [
"||",
{
"Ref": "AssetParameters4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5fS3VersionKey83071E5E"
}
]
}
]
},
{
"Fn::Select": [
1,
{
"Fn::Split": [
"||",
{
"Ref": "AssetParameters4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5fS3VersionKey83071E5E"
}
]
}
]
}
]
]
}
},
"Handler": "index.handler",
"Role": {
"Fn::GetAtt": [
"myhandlerServiceRole77891068",
"Arn"
]
},
"Runtime": "python3.8",
"Layers": [
{
"Ref": "myhandlerDependencies20391420"
}
]
},
"DependsOn": [
"myhandlerServiceRole77891068"
]
},
"myhandlerDependencies20391420": {
"Type": "AWS::Lambda::LayerVersion",
"Properties": {
"Content": {
"S3Bucket": {
"Ref": "AssetParameters252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29S3Bucket642CA4C7"
},
"S3Key": {
"Fn::Join": [
"",
[
{
"Fn::Select": [
0,
{
"Fn::Split": [
"||",
{
"Ref": "AssetParameters252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29S3VersionKey64C9926E"
}
]
}
]
},
{
"Fn::Select": [
1,
{
"Fn::Split": [
"||",
{
"Ref": "AssetParameters252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29S3VersionKey64C9926E"
}
]
}
]
}
]
]
}
},
"CompatibleRuntimes": [
"python3.8"
]
}
}
},
"Parameters": {
"AssetParameters4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5fS3Bucket2F5C84CD": {
"Type": "String",
"Description": "S3 bucket for asset \"4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5f\""
},
"AssetParameters4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5fS3VersionKey83071E5E": {
"Type": "String",
"Description": "S3 key for asset version \"4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5f\""
},
"AssetParameters4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5fArtifactHashA46D9597": {
"Type": "String",
"Description": "Artifact hash for asset \"4eea0d640af1864916a242dbdb7f389832098cafcef9a336426f3e722767cd5f\""
},
"AssetParameters252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29S3Bucket642CA4C7": {
"Type": "String",
"Description": "S3 bucket for asset \"252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29\""
},
"AssetParameters252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29S3VersionKey64C9926E": {
"Type": "String",
"Description": "S3 key for asset version \"252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29\""
},
"AssetParameters252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29ArtifactHash8A3CA2CC": {
"Type": "String",
"Description": "Artifact hash for asset \"252e7578113dbc054fc4bc9801f3a9da383755d081008bd4d023b030d198cd29\""
}
},
"Outputs": {
"FunctionName": {
"Value": {
"Ref": "myhandlerD202FA8E"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as path from 'path';
import { Runtime } from '@aws-cdk/aws-lambda';
import { App, CfnOutput, Construct, Stack, StackProps } from '@aws-cdk/core';
import * as lambda from '../lib';

/*
* Stack verification steps:
* cdk deploy --app "node integ.function.dependencies-layer.js"
* aws lambda invoke --function-name <function name> --invocation-type Event --payload $(base64 <<<'"OK"') response.json
*/

class TestStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);

const fn = new lambda.PythonFunction(this, 'my_handler', {
entry: path.join(__dirname, 'lambda-handler2'),
runtime: Runtime.PYTHON_3_8,
useDependencyLayer: true,
});

new CfnOutput(this, 'FunctionName', {
value: fn.functionName,
});
}
}

const app = new App();
new TestStack(app, 'cdk-integ-lambda-dependencies-layer');
app.synth();