Package: aws-cdk.aws-lambda-python-alpha
Amazon Lambda Python Library---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 theSemantic Versioningmodel 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 FunctionDefine aPythonFunction:python.PythonFunction(self,"MyFunction",entry="/path/to/my/function",# requiredruntime=Runtime.PYTHON_3_8,# requiredindex="my_index.py",# optional, defaults to 'index.py'handler="my_exported_func")All other properties oflambda.Functionare supported, see also theAWS Lambda construct library.Python LayerYou may create a python-based lambda layer withPythonLayerVersion. IfPythonLayerVersiondetects arequirements.txtorPipfileorpoetry.lockwith the associatedpyproject.tomlat the entry path, thenPythonLayerVersionwill include the dependencies inline with your code in the
layer.Define aPythonLayerVersion:python.PythonLayerVersion(self,"MyLayer",entry="/path/to/my/layer")A layer can also be used as a part of aPythonFunction:python.PythonFunction(self,"MyFunction",entry="/path/to/my/function",runtime=Runtime.PYTHON_3_8,layers=[python.PythonLayerVersion(self,"MyLayer",entry="/path/to/my/layer")])PackagingIfrequirements.txt,Pipfileorpoetry.lockexists at the entry path, the construct will handle installing all required modules in aLambda compatible Docker containeraccording to theruntimeand 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] or [poetry] which have lockfile support.pipenvpoetryPackaging is executed using thePackagingclass, which:Infers the packaging type based on the files present.If it sees aPipfileor apoetry.lockfile, it exports it to a compatiblerequirements.txtfile with credentials (if they're available in the source files or in the bundling container).Installs dependencies usingpip.Copies the dependencies into an asset that is bundled for the Lambda package.Lambda with a requirements.txt.
├── lambda_function.py # exports a function named 'handler'
├── requirements.txt # has to be present at the entry pathLambda with a Pipfile.
├── lambda_function.py # exports a function named 'handler'
├── Pipfile # has to be present at the entry path
├── Pipfile.lock # your lock fileLambda with a poetry.lock.
├── 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 pathExcluding source filesYou can exclude files from being copied using the optional bundling string array parameterassetExcludes: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"]))Including hashesYou can include hashes inpoetryusing the optional boolean parameterpoetryIncludeHashes:python.PythonFunction(self,"function",entry="/path/to/poetry-function",runtime=Runtime.PYTHON_3_8,bundling=python.BundlingOptions(poetry_include_hashes=True))Excluding URLsYou can exclude URLs inpoetryusing the optional boolean parameterpoetryWithoutUrls:python.PythonFunction(self,"function",entry="/path/to/poetry-function",runtime=Runtime.PYTHON_3_8,bundling=python.BundlingOptions(poetry_without_urls=True))Custom BundlingCustom 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_URLPIP_EXTRA_INDEX_URLHTTPS_PROXYAdditional build args for bundling that refer to PyPI indexes can be specified as: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/"}))If using a custom Docker image for bundling, the dependencies are installed withpip,pipenvorpoetryby using thePackagingclass. A different bundling Docker image that is in the same directory as the function can be specified as:entry="/path/to/function"image=DockerImage.from_build(entry)python.PythonFunction(self,"function",entry=entry,runtime=Runtime.PYTHON_3_8,bundling=python.BundlingOptions(image=image))You can set additional Docker options to configure the build environment:entry="/path/to/function"python.PythonFunction(self,"function",entry=entry,runtime=Runtime.PYTHON_3_8,bundling=python.BundlingOptions(network="host",security_opt="no-new-privileges",user="user:group",volumes_from=["777f7dc92da7"],volumes=[DockerVolume(host_path="/host-path",container_path="/container-path")]))Custom Bundling with Code ArtifactTo use a Code Artifact PyPI repo, thePIP_INDEX_URLfor bundling the function can be customized (requires AWS CLI in the build environment):fromchild_processimportexec_syncentry="/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}))The index URL or the token are only used during bundling and thus not included in the final asset. Setting only environment variable forPIP_INDEX_URLorPIP_EXTRA_INDEX_URLshould work for accesing private Python repositories withpip,pipenvandpoetrybased dependencies.If you also want to use the Code Artifact repo for building the base Docker image for bundling, usebuildArgs. 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:fromchild_processimportexec_syncentry="/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}))Command hooksIt is  possible to run additional commands by specifying thecommandHooksprop:entry="/path/to/function"python.PythonFunction(self,"function",entry=entry,runtime=Runtime.PYTHON_3_8,bundling=python.BundlingOptions(command_hooks={# run testsdefbefore_bundling(self,input_dir):return["pytest"],defafter_bundling(self,input_dir):return["pylint"]}))The following hooks are available:beforeBundling: runs before all bundling commandsafterBundling: runs after all bundling commandsThey 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 configurationsBy default the input and output of Docker based bundling is handled via bind mounts.
In situtations 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.entry="/path/to/function"python.PythonFunction(self,"function",entry=entry,runtime=Runtime.PYTHON_3_8,bundling=python.BundlingOptions(bundling_file_access=BundlingFileAccess.VOLUME_COPY))TroubleshootingContainerfile: no such file or directoryIf you are on a Mac, usingFinchinstead of Docker, and see an error
like this:lstat /private/var/folders/zx/d5wln9n10sn0tcj1v9798f1c0000gr/T/jsii-kernel-9VYgrO/node_modules/@aws-cdk/aws-lambda-python-alpha/lib/Containerfile: no such file or directoryThat is a sign that your temporary directory has not been mapped into the Finch VM. Add the following to~/.finch/finch.yaml:additional_directories:-path:/private/var/folders/-path:/var/folders/Then restart the Finch VM by runningfinch vm stop && finch vm start.