Skip to content
v2.273.0

Amazon Lambda Python Library ​

Version 2.273.0-alpha.0

Separate package

@aws-cdk/aws-lambda-python-alpha is not part of aws-cdk-lib — install it separately:

sh
npm install @aws-cdk/aws-lambda-python-alpha
pip install aws-cdk.aws-lambda-python-alpha

This module is experimental (alpha): its API may change in any release, without a major version bump.


cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


This library provides constructs for Python Lambda functions.

To use this module, you will need to have Docker installed.

Python Function ​

Define a PythonFunction:

ts
new python.PythonFunction(this, 'MyFunction', {
  entry: '/path/to/my/function', // required
  runtime: Runtime.PYTHON_3_8, // required
  index: 'my_index.py', // optional, defaults to 'index.py'
  handler: 'my_exported_func', // optional, defaults to 'handler'
});
python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",  # required
    runtime=Runtime.PYTHON_3_8,  # required
    index="my_index.py",  # optional, defaults to 'index.py'
    handler="my_exported_func"
)
java
PythonFunction.Builder.create(this, "MyFunction")
        .entry("/path/to/my/function") // required
        .runtime(Runtime.PYTHON_3_8) // required
        .index("my_index.py") // optional, defaults to 'index.py'
        .handler("my_exported_func")
        .build();
csharp
new PythonFunction(this, "MyFunction", new PythonFunctionProps {
    Entry = "/path/to/my/function",  // required
    Runtime = Runtime.PYTHON_3_8,  // required
    Index = "my_index.py",  // optional, defaults to 'index.py'
    Handler = "my_exported_func"
});
go
python.NewPythonFunction(this, jsii.String("MyFunction"), &PythonFunctionProps{
	Entry: jsii.String("/path/to/my/function"),
	 // required
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	 // required
	Index: jsii.String("my_index.py"),
	 // optional, defaults to 'index.py'
	Handler: jsii.String("my_exported_func"),
})

All other properties of lambda.Function are supported, see also the AWS Lambda construct library.

Python Layer ​

You may create a python-based lambda layer with PythonLayerVersion. If PythonLayerVersion detects a requirements.txt or Pipfile or poetry.lock with the associated pyproject.toml at the entry path, then PythonLayerVersion will include the dependencies inline with your code in the layer.

Define a PythonLayerVersion:

ts
new python.PythonLayerVersion(this, 'MyLayer', {
  entry: '/path/to/my/layer', // point this to your library's directory
})
python
python.PythonLayerVersion(self, "MyLayer",
    entry="/path/to/my/layer"
)
java
PythonLayerVersion.Builder.create(this, "MyLayer")
        .entry("/path/to/my/layer")
        .build();
csharp
new PythonLayerVersion(this, "MyLayer", new PythonLayerVersionProps {
    Entry = "/path/to/my/layer"
});
go
python.NewPythonLayerVersion(this, jsii.String("MyLayer"), &PythonLayerVersionProps{
	Entry: jsii.String("/path/to/my/layer"),
})

A layer can also be used as a part of a PythonFunction:

ts
new python.PythonFunction(this, 'MyFunction', {
  entry: '/path/to/my/function',
  runtime: Runtime.PYTHON_3_8,
  layers: [
    new python.PythonLayerVersion(this, 'MyLayer', {
      entry: '/path/to/my/layer', // point this to your library's directory
    }),
  ],
});
python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",
    runtime=Runtime.PYTHON_3_8,
    layers=[
        python.PythonLayerVersion(self, "MyLayer",
            entry="/path/to/my/layer"
        )
    ]
)
java
PythonFunction.Builder.create(this, "MyFunction")
        .entry("/path/to/my/function")
        .runtime(Runtime.PYTHON_3_8)
        .layers(List.of(
            PythonLayerVersion.Builder.create(this, "MyLayer")
                    .entry("/path/to/my/layer")
                    .build()))
        .build();
csharp
new PythonFunction(this, "MyFunction", new PythonFunctionProps {
    Entry = "/path/to/my/function",
    Runtime = Runtime.PYTHON_3_8,
    Layers = new [] {
        new PythonLayerVersion(this, "MyLayer", new PythonLayerVersionProps {
            Entry = "/path/to/my/layer"
        }) }
});
go
python.NewPythonFunction(this, jsii.String("MyFunction"), &PythonFunctionProps{
	Entry: jsii.String("/path/to/my/function"),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Layers: []ILayerVersion{
		python.NewPythonLayerVersion(this, jsii.String("MyLayer"), &PythonLayerVersionProps{
			Entry: jsii.String("/path/to/my/layer"),
		}),
	},
})

Packaging ​

If requirements.txt, Pipfile, uv.lock or poetry.lock exists at the entry path, the construct will handle installing all required modules in a Lambda compatible Docker container according to the runtime and with the Docker platform based on the target architecture of the Lambda function.

Python bundles are only recreated and published when a file in a source directory has changed. Therefore (and as a general best-practice), it is highly recommended to commit a lockfile with a list of all transitive dependencies and their exact versions. This will ensure that when any dependency version is updated, the bundle asset is recreated and uploaded.

To that end, we recommend using [pipenv], [uv] or [poetry] which have lockfile support.

Packaging is executed using the Packaging class, which:

  1. Infers the packaging type based on the files present.
  2. If it sees a Pipfile, uv.lock or a poetry.lock file, it exports it to a compatible requirements.txt file with credentials (if they're available in the source files or in the bundling container).
  3. Installs dependencies using pip or uv.
  4. Copies the dependencies into an asset that is bundled for the Lambda package.

Lambda with a requirements.txt

plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── requirements.txt # has to be present at the entry path

Lambda with a Pipfile

plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── Pipfile # has to be present at the entry path
├── Pipfile.lock # your lock file

Lambda with a poetry.lock

plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── poetry.lock # your poetry lock file has to be present at the entry path

Lambda with a uv.lock

Reference: https://docs.astral.sh/uv/concepts/projects/layout/

plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── uv.lock # your uv lock file has to be present at the entry path
├── .python-version # this file is ignored, python version is configured via Runtime

Excluding source files

You can exclude files from being copied using the optional bundling string array parameter assetExcludes:

ts
new python.PythonFunction(this, 'function', {
  entry: '/path/to/poetry-function',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    // translates to `rsync --exclude='.venv'`
    assetExcludes: ['.venv'],
  },
});
python
python.PythonFunction(self, "function",
    entry="/path/to/poetry-function",
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        # translates to `rsync --exclude='.venv'`
        asset_excludes=[".venv"]
    )
)
java
PythonFunction.Builder.create(this, "function")
        .entry("/path/to/poetry-function")
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                // translates to `rsync --exclude='.venv'`
                .assetExcludes(List.of(".venv"))
                .build())
        .build();
csharp
new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = "/path/to/poetry-function",
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        // translates to `rsync --exclude='.venv'`
        AssetExcludes = new [] { ".venv" }
    }
});
go
python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String("/path/to/poetry-function"),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		// translates to `rsync --exclude='.venv'`
		AssetExcludes: []*string{
			jsii.String(".venv"),
		},
	},
})

Including hashes

You can include hashes in poetry using the optional boolean parameter poetryIncludeHashes:

ts
new python.PythonFunction(this, 'function', {
  entry: '/path/to/poetry-function',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    poetryIncludeHashes: true,
  },
});
python
python.PythonFunction(self, "function",
    entry="/path/to/poetry-function",
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        poetry_include_hashes=True
    )
)
java
PythonFunction.Builder.create(this, "function")
        .entry("/path/to/poetry-function")
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                .poetryIncludeHashes(true)
                .build())
        .build();
csharp
new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = "/path/to/poetry-function",
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        PoetryIncludeHashes = true
    }
});
go
python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String("/path/to/poetry-function"),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		PoetryIncludeHashes: jsii.Boolean(true),
	},
})

Excluding URLs

You can exclude URLs in poetry using the optional boolean parameter poetryWithoutUrls:

ts
new python.PythonFunction(this, 'function', {
  entry: '/path/to/poetry-function',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    poetryWithoutUrls: true,
  },
});
python
python.PythonFunction(self, "function",
    entry="/path/to/poetry-function",
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        poetry_without_urls=True
    )
)
java
PythonFunction.Builder.create(this, "function")
        .entry("/path/to/poetry-function")
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                .poetryWithoutUrls(true)
                .build())
        .build();
csharp
new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = "/path/to/poetry-function",
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        PoetryWithoutUrls = true
    }
});
go
python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String("/path/to/poetry-function"),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		PoetryWithoutUrls: jsii.Boolean(true),
	},
})

Custom Bundling ​

Custom bundling can be performed by passing in additional build arguments that point to index URLs to private repos, or by using an entirely custom Docker images for bundling dependencies. The build args currently supported are:

  • PIP_INDEX_URL
  • PIP_EXTRA_INDEX_URL
  • HTTPS_PROXY

Additional build args for bundling that refer to PyPI indexes can be specified as:

ts
const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    buildArgs: { PIP_INDEX_URL: "https://your.index.url/simple/", PIP_EXTRA_INDEX_URL: "https://your.extra-index.url/simple/" },
  },
});
python
entry = "/path/to/function"
image = DockerImage.from_build(entry)

python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": "https://your.index.url/simple/", "PIP_EXTRA_INDEX_URL": "https://your.extra-index.url/simple/"}
    )
)
java
String entry = "/path/to/function";
DockerImage image = DockerImage.fromBuild(entry);

PythonFunction.Builder.create(this, "function")
        .entry(entry)
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                .buildArgs(Map.of("PIP_INDEX_URL", "https://your.index.url/simple/", "PIP_EXTRA_INDEX_URL", "https://your.extra-index.url/simple/"))
                .build())
        .build();
csharp
var entry = "/path/to/function";
var image = DockerImage.FromBuild(entry);

new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = entry,
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        BuildArgs = new Dictionary<string, string> { { "PIP_INDEX_URL", "https://your.index.url/simple/" }, { "PIP_EXTRA_INDEX_URL", "https://your.extra-index.url/simple/" } }
    }
});
go
entry := "/path/to/function"
image := awscdk.DockerImage_FromBuild(entry)

python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String(Entry),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		BuildArgs: map[string]*string{
			"PIP_INDEX_URL": jsii.String("https://your.index.url/simple/"),
			"PIP_EXTRA_INDEX_URL": jsii.String("https://your.extra-index.url/simple/"),
		},
	},
})

If using a custom Docker image for bundling, the dependencies are installed with pip, pipenv or poetry by using the Packaging class. A different bundling Docker image that is in the same directory as the function can be specified as:

ts
const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

new python.PythonFunction(this, 'function', {
 entry,
 runtime: Runtime.PYTHON_3_8,
 bundling: { image },
});

You can set additional Docker options to configure the build environment:

ts
const entry = '/path/to/function';

new python.PythonFunction(this, 'function', {
 entry,
 runtime: Runtime.PYTHON_3_8,
 bundling: {
   network: 'host',
   securityOpt: 'no-new-privileges',
   user: 'user:group',
   volumesFrom: ['777f7dc92da7'],
   volumes: [{ hostPath: '/host-path', containerPath: '/container-path' }],
 },
});

Custom Bundling with Code Artifact ​

To use a Code Artifact PyPI repo, the PIP_INDEX_URL for bundling the function can be customized (requires AWS CLI in the build environment):

ts
import { execSync } from 'child_process';

const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

const domain = 'my-domain';
const domainOwner = '111122223333';
const repoName = 'my_repo';
const region = 'us-east-1';
const codeArtifactAuthToken = execSync(`aws codeartifact get-authorization-token --domain ${domain} --domain-owner ${domainOwner} --query authorizationToken --output text`).toString().trim();

const indexUrl = `https://aws:${codeArtifactAuthToken}@${domain}-${domainOwner}.d.codeartifact.${region}.amazonaws.com/pypi/${repoName}/simple/`;

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    environment: { PIP_INDEX_URL: indexUrl },
  },
});
python
from child_process import exec_sync


entry = "/path/to/function"
image = DockerImage.from_build(entry)

domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()

index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"

python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        environment={"PIP_INDEX_URL": index_url}
    )
)
java
import child.process.execSync.*;


String entry = "/path/to/function";
DockerImage image = DockerImage.fromBuild(entry);

String domain = "my-domain";
String domainOwner = "111122223333";
String repoName = "my_repo";
String region = "us-east-1";
String codeArtifactAuthToken = execSync(String.format("aws codeartifact get-authorization-token --domain %s --domain-owner %s --query authorizationToken --output text", domain, domainOwner)).toString().trim();

String indexUrl = String.format("https://aws:%s@%s-%s.d.codeartifact.%s.amazonaws.com/pypi/%s/simple/", codeArtifactAuthToken, domain, domainOwner, region, repoName);

PythonFunction.Builder.create(this, "function")
        .entry(entry)
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                .environment(Map.of("PIP_INDEX_URL", indexUrl))
                .build())
        .build();
csharp
using Child.Process;


var entry = "/path/to/function";
var image = DockerImage.FromBuild(entry);

var domain = "my-domain";
var domainOwner = "111122223333";
var repoName = "my_repo";
var region = "us-east-1";
var codeArtifactAuthToken = ExecSync($"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").ToString().Trim();

var indexUrl = $"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/";

new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = entry,
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        Environment = new Dictionary<string, string> { { "PIP_INDEX_URL", indexUrl } }
    }
});
go
import "github.com/aws-samples/dummy/child_process"


entry := "/path/to/function"
image := awscdk.DockerImage_FromBuild(entry)

domain := "my-domain"
domainOwner := "111122223333"
repoName := "my_repo"
region := "us-east-1"
codeArtifactAuthToken := child_process.ExecSync(fmt.Sprintf("aws codeartifact get-authorization-token --domain %v --domain-owner %v --query authorizationToken --output text", domain, domainOwner)).toString().trim()

indexUrl := fmt.Sprintf("https://aws:%v@%v-%v.d.codeartifact.%v.amazonaws.com/pypi/%v/simple/", codeArtifactAuthToken, domain, domainOwner, region, repoName)

python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String(Entry),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		Environment: map[string]*string{
			"PIP_INDEX_URL": indexUrl,
		},
	},
})

The index URL or the token are only used during bundling and thus not included in the final asset. Setting only environment variable for PIP_INDEX_URL or PIP_EXTRA_INDEX_URL should work for accessing private Python repositories with pip, pipenv and poetry based dependencies.

If you also want to use the Code Artifact repo for building the base Docker image for bundling, use buildArgs. However, note that setting custom build args for bundling will force the base bundling image to be rebuilt every time (i.e. skip the Docker cache). Build args can be customized as:

ts
import { execSync } from 'child_process';

const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

const domain = 'my-domain';
const domainOwner = '111122223333';
const repoName = 'my_repo';
const region = 'us-east-1';
const codeArtifactAuthToken = execSync(`aws codeartifact get-authorization-token --domain ${domain} --domain-owner ${domainOwner} --query authorizationToken --output text`).toString().trim();

const indexUrl = `https://aws:${codeArtifactAuthToken}@${domain}-${domainOwner}.d.codeartifact.${region}.amazonaws.com/pypi/${repoName}/simple/`;

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    buildArgs: { PIP_INDEX_URL: indexUrl },
  },
});
python
from child_process import exec_sync


entry = "/path/to/function"
image = DockerImage.from_build(entry)

domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()

index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"

python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": index_url}
    )
)
java
import child.process.execSync.*;


String entry = "/path/to/function";
DockerImage image = DockerImage.fromBuild(entry);

String domain = "my-domain";
String domainOwner = "111122223333";
String repoName = "my_repo";
String region = "us-east-1";
String codeArtifactAuthToken = execSync(String.format("aws codeartifact get-authorization-token --domain %s --domain-owner %s --query authorizationToken --output text", domain, domainOwner)).toString().trim();

String indexUrl = String.format("https://aws:%s@%s-%s.d.codeartifact.%s.amazonaws.com/pypi/%s/simple/", codeArtifactAuthToken, domain, domainOwner, region, repoName);

PythonFunction.Builder.create(this, "function")
        .entry(entry)
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                .buildArgs(Map.of("PIP_INDEX_URL", indexUrl))
                .build())
        .build();
csharp
using Child.Process;


var entry = "/path/to/function";
var image = DockerImage.FromBuild(entry);

var domain = "my-domain";
var domainOwner = "111122223333";
var repoName = "my_repo";
var region = "us-east-1";
var codeArtifactAuthToken = ExecSync($"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").ToString().Trim();

var indexUrl = $"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/";

new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = entry,
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        BuildArgs = new Dictionary<string, string> { { "PIP_INDEX_URL", indexUrl } }
    }
});
go
import "github.com/aws-samples/dummy/child_process"


entry := "/path/to/function"
image := awscdk.DockerImage_FromBuild(entry)

domain := "my-domain"
domainOwner := "111122223333"
repoName := "my_repo"
region := "us-east-1"
codeArtifactAuthToken := child_process.ExecSync(fmt.Sprintf("aws codeartifact get-authorization-token --domain %v --domain-owner %v --query authorizationToken --output text", domain, domainOwner)).toString().trim()

indexUrl := fmt.Sprintf("https://aws:%v@%v-%v.d.codeartifact.%v.amazonaws.com/pypi/%v/simple/", codeArtifactAuthToken, domain, domainOwner, region, repoName)

python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String(Entry),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		BuildArgs: map[string]*string{
			"PIP_INDEX_URL": indexUrl,
		},
	},
})

Command hooks ​

It is possible to run additional commands by specifying the commandHooks prop:

ts
const entry = '/path/to/function';
new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    commandHooks: {
      // run tests
      beforeBundling(inputDir: string): string[] {
        return ['pytest'];
      },
      afterBundling(inputDir: string): string[] {
        return ['pylint'];
      },
      // ...
    },
  },
});
python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        command_hooks={
            # run tests
            def before_bundling(self, input_dir):
                return ["pytest"],
            def after_bundling(self, input_dir):
                return ["pylint"]
        }
    )
)
java
String entry = "/path/to/function";
PythonFunction.Builder.create(this, "function")
        .entry(entry)
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                .commandHooks(Map.of(
                        // run tests
                        public String[] beforeBundling(String inputDir) {
                            return List.of("pytest");
                        },
                        public String[] afterBundling(String inputDir) {
                            return List.of("pylint");
                        }))
                .build())
        .build();
csharp
var entry = "/path/to/function";
new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = entry,
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        CommandHooks = new Dictionary<string, object> {
            // run tests
            public string[] BeforeBundling(string inputDir)
            {
                return new [] { "pytest" };
            },
            public string[] AfterBundling(string inputDir)
            {
                return new [] { "pylint" };
            }
        }
    }
});
go
entry := "/path/to/function"
python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String(Entry),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		CommandHooks: map[string]interface{}{
			// run tests
			(MethodDeclaration beforeBundling(inputDir: string): string[] {
			        return ['pytest'];
			      }
					beforeBundling
					inputDir *string
					string[]
					{
						return []*string{
							jsii.String("pytest"),
						}
					}),
			(MethodDeclaration afterBundling(inputDir: string): string[] {
			        return ['pylint'];
			      }
					afterBundling
					inputDir *string
					string[]
					{
						return []*string{
							jsii.String("pylint"),
						}
					}),
		},
	},
})

The following hooks are available:

  • beforeBundling: runs before all bundling commands
  • afterBundling: runs after all bundling commands

They all receive the directory containing the dependencies file (inputDir) and the directory where the bundled asset will be output (outputDir). They must return an array of commands to run. Commands are chained with &&.

The commands will run in the environment in which bundling occurs: inside the container for Docker bundling or on the host OS for local bundling.

Docker based bundling in complex Docker configurations ​

By default the input and output of Docker based bundling is handled via bind mounts. In situations where this does not work, like Docker-in-Docker setups or when using a remote Docker socket, you can configure an alternative, but slower, variant that also works in these situations.

ts
const entry = '/path/to/function';

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    bundlingFileAccess: BundlingFileAccess.VOLUME_COPY,
  },
});
python
entry = "/path/to/function"

python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        bundling_file_access=BundlingFileAccess.VOLUME_COPY
    )
)
java
String entry = "/path/to/function";

PythonFunction.Builder.create(this, "function")
        .entry(entry)
        .runtime(Runtime.PYTHON_3_8)
        .bundling(BundlingOptions.builder()
                .bundlingFileAccess(BundlingFileAccess.VOLUME_COPY)
                .build())
        .build();
csharp
var entry = "/path/to/function";

new PythonFunction(this, "function", new PythonFunctionProps {
    Entry = entry,
    Runtime = Runtime.PYTHON_3_8,
    Bundling = new BundlingOptions {
        BundlingFileAccess = BundlingFileAccess.VOLUME_COPY
    }
});
go
entry := "/path/to/function"

python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String(Entry),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		BundlingFileAccess: awscdk.BundlingFileAccess_VOLUME_COPY,
	},
})

Troubleshooting ​

Containerfile: no such file or directory ​

If you are on a Mac, using Finch instead of Docker, and see an error like this:

txt
lstat /private/var/folders/zx/d5wln9n10sn0tcj1v9798f1c0000gr/T/jsii-kernel-9VYgrO/node_modules/@aws-cdk/aws-lambda-python-alpha/lib/Containerfile: no such file or directory

That is a sign that your temporary directory has not been mapped into the Finch VM. Add the following to ~/.finch/finch.yaml:

yaml
additional_directories:
  - path: /private/var/folders/
  - path: /var/folders/

Then restart the Finch VM by running finch vm stop && finch vm start.

Types ​

NameKindSummary
PythonFunctionConstruct (L2)A Python Lambda function.
PythonLayerVersionConstruct (L2)A lambda layer version.
BundlingOptionsStructOptions for bundling.
ICommandHooksInterfaceCommand hooks.
PythonFunctionPropsStructProperties for a PythonFunction.
PythonLayerVersionPropsStructProperties for PythonLayerVersion.