awscdklambdapythonalpha

package module
v2.160.0-alpha.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2024 License: Apache-2.0 Imports: 16 Imported by: 0

README

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 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:

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:

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:

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 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] 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 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.
  4. 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 path

Lambda with a Pipfile

.
├── 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

.
├── 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

Excluding source files

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

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:

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:

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:

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:

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{
		Image: *Image,
	},
})

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

entry := "/path/to/function"

python.NewPythonFunction(this, jsii.String("function"), &PythonFunctionProps{
	Entry: jsii.String(Entry),
	Runtime: awscdk.Runtime_PYTHON_3_8(),
	Bundling: &BundlingOptions{
		Network: jsii.String("host"),
		SecurityOpt: jsii.String("no-new-privileges"),
		User: jsii.String("user:group"),
		VolumesFrom: []*string{
			jsii.String("777f7dc92da7"),
		},
		Volumes: []dockerVolume{
			&dockerVolume{
				HostPath: jsii.String("/host-path"),
				ContainerPath: jsii.String("/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):

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 accesing 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:

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:

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 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.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:

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:

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

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

Documentation

Overview

The CDK Construct Library for AWS Lambda in Python

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewPythonFunction_Override

func NewPythonFunction_Override(p PythonFunction, scope constructs.Construct, id *string, props *PythonFunctionProps)

Experimental.

func NewPythonLayerVersion_Override

func NewPythonLayerVersion_Override(p PythonLayerVersion, scope constructs.Construct, id *string, props *PythonLayerVersionProps)

Experimental.

func PythonFunction_ClassifyVersionProperty

func PythonFunction_ClassifyVersionProperty(propertyName *string, locked *bool)

Record whether specific properties in the `AWS::Lambda::Function` resource should also be associated to the Version resource.

See 'currentVersion' section in the module README for more details. Experimental.

func PythonFunction_FromFunctionArn

func PythonFunction_FromFunctionArn(scope constructs.Construct, id *string, functionArn *string) awslambda.IFunction

Import a lambda function into the CDK using its ARN.

For `Function.addPermissions()` to work on this imported lambda, make sure that is in the same account and region as the stack you are importing it into. Experimental.

func PythonFunction_FromFunctionAttributes

func PythonFunction_FromFunctionAttributes(scope constructs.Construct, id *string, attrs *awslambda.FunctionAttributes) awslambda.IFunction

Creates a Lambda function object which represents a function not defined within this stack.

For `Function.addPermissions()` to work on this imported lambda, set the sameEnvironment property to true if this imported lambda is in the same account and region as the stack you are importing it into. Experimental.

func PythonFunction_FromFunctionName

func PythonFunction_FromFunctionName(scope constructs.Construct, id *string, functionName *string) awslambda.IFunction

Import a lambda function into the CDK using its name. Experimental.

func PythonFunction_IsConstruct

func PythonFunction_IsConstruct(x interface{}) *bool

Checks if `x` is a construct.

Use this method instead of `instanceof` to properly detect `Construct` instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the `constructs` library on disk are seen as independent, completely different libraries. As a consequence, the class `Construct` in each copy of the `constructs` library is seen as a different class, and an instance of one class will not test as `instanceof` the other class. `npm install` will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the `constructs` library can be accidentally installed, and `instanceof` will behave unpredictably. It is safest to avoid using `instanceof`, and using this type-testing method instead.

Returns: true if `x` is an object created from a class which extends `Construct`. Experimental.

func PythonFunction_IsOwnedResource

func PythonFunction_IsOwnedResource(construct constructs.IConstruct) *bool

Returns true if the construct was created by CDK, and false otherwise. Experimental.

func PythonFunction_IsResource

func PythonFunction_IsResource(construct constructs.IConstruct) *bool

Check whether the given construct is a Resource. Experimental.

func PythonFunction_MetricAll

func PythonFunction_MetricAll(metricName *string, props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Return the given named metric for this Lambda. Experimental.

func PythonFunction_MetricAllConcurrentExecutions

func PythonFunction_MetricAllConcurrentExecutions(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of concurrent executions across all Lambdas. Default: max over 5 minutes.

Experimental.

func PythonFunction_MetricAllDuration

func PythonFunction_MetricAllDuration(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the Duration executing all Lambdas. Default: average over 5 minutes.

Experimental.

func PythonFunction_MetricAllErrors

func PythonFunction_MetricAllErrors(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of Errors executing all Lambdas. Default: sum over 5 minutes.

Experimental.

func PythonFunction_MetricAllInvocations

func PythonFunction_MetricAllInvocations(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of invocations of all Lambdas. Default: sum over 5 minutes.

Experimental.

func PythonFunction_MetricAllThrottles

func PythonFunction_MetricAllThrottles(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of throttled invocations of all Lambdas. Default: sum over 5 minutes.

Experimental.

func PythonFunction_MetricAllUnreservedConcurrentExecutions

func PythonFunction_MetricAllUnreservedConcurrentExecutions(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of unreserved concurrent executions across all Lambdas. Default: max over 5 minutes.

Experimental.

func PythonLayerVersion_FromLayerVersionArn

func PythonLayerVersion_FromLayerVersionArn(scope constructs.Construct, id *string, layerVersionArn *string) awslambda.ILayerVersion

Imports a layer version by ARN.

Assumes it is compatible with all Lambda runtimes. Experimental.

func PythonLayerVersion_FromLayerVersionAttributes

func PythonLayerVersion_FromLayerVersionAttributes(scope constructs.Construct, id *string, attrs *awslambda.LayerVersionAttributes) awslambda.ILayerVersion

Imports a Layer that has been defined externally. Experimental.

func PythonLayerVersion_IsConstruct

func PythonLayerVersion_IsConstruct(x interface{}) *bool

Checks if `x` is a construct.

Use this method instead of `instanceof` to properly detect `Construct` instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the `constructs` library on disk are seen as independent, completely different libraries. As a consequence, the class `Construct` in each copy of the `constructs` library is seen as a different class, and an instance of one class will not test as `instanceof` the other class. `npm install` will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the `constructs` library can be accidentally installed, and `instanceof` will behave unpredictably. It is safest to avoid using `instanceof`, and using this type-testing method instead.

Returns: true if `x` is an object created from a class which extends `Construct`. Experimental.

func PythonLayerVersion_IsOwnedResource

func PythonLayerVersion_IsOwnedResource(construct constructs.IConstruct) *bool

Returns true if the construct was created by CDK, and false otherwise. Experimental.

func PythonLayerVersion_IsResource

func PythonLayerVersion_IsResource(construct constructs.IConstruct) *bool

Check whether the given construct is a Resource. Experimental.

Types

type BundlingOptions

type BundlingOptions struct {
	// The command to run in the container.
	// Default: - run the command defined in the image.
	//
	// Experimental.
	Command *[]*string `field:"optional" json:"command" yaml:"command"`
	// The entrypoint to run in the container.
	// Default: - run the entrypoint defined in the image.
	//
	// Experimental.
	Entrypoint *[]*string `field:"optional" json:"entrypoint" yaml:"entrypoint"`
	// The environment variables to pass to the container.
	// Default: - no environment variables.
	//
	// Experimental.
	Environment *map[string]*string `field:"optional" json:"environment" yaml:"environment"`
	// Docker [Networking options](https://docs.docker.com/engine/reference/commandline/run/#connect-a-container-to-a-network---network).
	// Default: - no networking options.
	//
	// Experimental.
	Network *string `field:"optional" json:"network" yaml:"network"`
	// Set platform if server is multi-platform capable. _Requires Docker Engine API v1.38+_.
	//
	// Example value: `linux/amd64`.
	// Default: - no platform specified.
	//
	// Experimental.
	Platform *string `field:"optional" json:"platform" yaml:"platform"`
	// [Security configuration](https://docs.docker.com/engine/reference/run/#security-configuration) when running the docker container.
	// Default: - no security options.
	//
	// Experimental.
	SecurityOpt *string `field:"optional" json:"securityOpt" yaml:"securityOpt"`
	// The user to use when running the container.
	// Default: - root or image default.
	//
	// Experimental.
	User *string `field:"optional" json:"user" yaml:"user"`
	// Docker volumes to mount.
	// Default: - no volumes are mounted.
	//
	// Experimental.
	Volumes *[]*awscdk.DockerVolume `field:"optional" json:"volumes" yaml:"volumes"`
	// Where to mount the specified volumes from.
	// See: https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container---volumes-from
	//
	// Default: - no containers are specified to mount volumes from.
	//
	// Experimental.
	VolumesFrom *[]*string `field:"optional" json:"volumesFrom" yaml:"volumesFrom"`
	// Working directory inside the container.
	// Default: - image default.
	//
	// Experimental.
	WorkingDirectory *string `field:"optional" json:"workingDirectory" yaml:"workingDirectory"`
	// List of file patterns to exclude when copying assets from source for bundling.
	// Default: - Empty list.
	//
	// Experimental.
	AssetExcludes *[]*string `field:"optional" json:"assetExcludes" yaml:"assetExcludes"`
	// Specify a custom hash for this asset.
	//
	// If `assetHashType` is set it must
	// be set to `AssetHashType.CUSTOM`. For consistency, this custom hash will
	// be SHA256 hashed and encoded as hex. The resulting hash will be the asset
	// hash.
	//
	// NOTE: the hash is used in order to identify a specific revision of the asset, and
	// used for optimizing and caching deployment activities related to this asset such as
	// packaging, uploading to Amazon S3, etc. If you chose to customize the hash, you will
	// need to make sure it is updated every time the asset changes, or otherwise it is
	// possible that some deployments will not be invalidated.
	// Default: - Based on `assetHashType`.
	//
	// Experimental.
	AssetHash *string `field:"optional" json:"assetHash" yaml:"assetHash"`
	// Determines how asset hash is calculated. Assets will get rebuild and uploaded only if their hash has changed.
	//
	// If asset hash is set to `SOURCE` (default), then only changes to the source
	// directory will cause the asset to rebuild. This means, for example, that in
	// order to pick up a new dependency version, a change must be made to the
	// source tree. Ideally, this can be implemented by including a dependency
	// lockfile in your source tree or using fixed dependencies.
	//
	// If the asset hash is set to `OUTPUT`, the hash is calculated after
	// bundling. This means that any change in the output will cause the asset to
	// be invalidated and uploaded. Bear in mind that `pip` adds timestamps to
	// dependencies it installs, which implies that in this mode Python bundles
	// will _always_ get rebuild and uploaded. Normally this is an anti-pattern
	// since build.
	// Default: AssetHashType.SOURCE By default, hash is calculated based on the
	// contents of the source directory. This means that only updates to the
	// source will cause the asset to rebuild.
	//
	// Experimental.
	AssetHashType awscdk.AssetHashType `field:"optional" json:"assetHashType" yaml:"assetHashType"`
	// Optional build arguments to pass to the default container.
	//
	// This can be used to customize
	// the index URLs used for installing dependencies.
	// This is not used if a custom image is provided.
	// Default: - No build arguments.
	//
	// Experimental.
	BuildArgs *map[string]*string `field:"optional" json:"buildArgs" yaml:"buildArgs"`
	// Which option to use to copy the source files to the docker container and output files back.
	// Default: - BundlingFileAccess.BIND_MOUNT
	//
	// Experimental.
	BundlingFileAccess awscdk.BundlingFileAccess `field:"optional" json:"bundlingFileAccess" yaml:"bundlingFileAccess"`
	// Command hooks.
	// Default: - do not run additional commands.
	//
	// Experimental.
	CommandHooks ICommandHooks `field:"optional" json:"commandHooks" yaml:"commandHooks"`
	// Docker image to use for bundling.
	//
	// If no options are provided, the default bundling image
	// will be used. Dependencies will be installed using the default packaging commands
	// and copied over from into the Lambda asset.
	// Default: - Default bundling image.
	//
	// Experimental.
	Image awscdk.DockerImage `field:"optional" json:"image" yaml:"image"`
	// Output path suffix: the suffix for the directory into which the bundled output is written.
	// Default: - 'python' for a layer, empty string otherwise.
	//
	// Experimental.
	OutputPathSuffix *string `field:"optional" json:"outputPathSuffix" yaml:"outputPathSuffix"`
	// Whether to export Poetry dependencies with hashes.
	//
	// Note that this can cause builds to fail if not all dependencies
	// export with a hash.
	// See: https://github.com/aws/aws-cdk/issues/19232
	//
	// Default: Hashes are NOT included in the exported `requirements.txt` file
	//
	// Experimental.
	PoetryIncludeHashes *bool `field:"optional" json:"poetryIncludeHashes" yaml:"poetryIncludeHashes"`
	// Whether to export Poetry dependencies with source repository urls.
	// Default: URLs are included in the exported `requirements.txt` file.
	//
	// Experimental.
	PoetryWithoutUrls *bool `field:"optional" json:"poetryWithoutUrls" yaml:"poetryWithoutUrls"`
}

Options for bundling.

Example:

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/"),
		},
	},
})

Experimental.

type ICommandHooks

type ICommandHooks interface {
	// Returns commands to run after bundling.
	//
	// Commands are chained with `&&`.
	// Experimental.
	AfterBundling(inputDir *string, outputDir *string) *[]*string
	// Returns commands to run before bundling.
	//
	// Commands are chained with `&&`.
	// Experimental.
	BeforeBundling(inputDir *string, outputDir *string) *[]*string
}

Command hooks.

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

Commands are chained with `&&`.

```text

{
  // Run tests prior to bundling
  beforeBundling(inputDir: string, outputDir: string): string[] {
    return [`pytest`];
  }
  // ...
}

```. Experimental.

type PythonFunction

type PythonFunction interface {
	awslambda.Function
	// The architecture of this Lambda Function (this is an optional attribute and defaults to X86_64).
	// Experimental.
	Architecture() awslambda.Architecture
	// Whether the addPermission() call adds any permissions.
	//
	// True for new Lambdas, false for version $LATEST and imported Lambdas
	// from different accounts.
	// Experimental.
	CanCreatePermissions() *bool
	// Access the Connections object.
	//
	// Will fail if not a VPC-enabled Lambda Function.
	// Experimental.
	Connections() awsec2.Connections
	// Returns a `lambda.Version` which represents the current version of this Lambda function. A new version will be created every time the function's configuration changes.
	//
	// You can specify options for this version using the `currentVersionOptions`
	// prop when initializing the `lambda.Function`.
	// Experimental.
	CurrentVersion() awslambda.Version
	// The DLQ (as queue) associated with this Lambda Function (this is an optional attribute).
	// Experimental.
	DeadLetterQueue() awssqs.IQueue
	// The DLQ (as topic) associated with this Lambda Function (this is an optional attribute).
	// Experimental.
	DeadLetterTopic() awssns.ITopic
	// The environment this resource belongs to.
	//
	// For resources that are created and managed by the CDK
	// (generally, those created by creating new class instances like Role, Bucket, etc.),
	// this is always the same as the environment of the stack they belong to;
	// however, for imported resources
	// (those obtained from static methods like fromRoleArn, fromBucketName, etc.),
	// that might be different than the stack they were imported into.
	// Experimental.
	Env() *awscdk.ResourceEnvironment
	// ARN of this function.
	// Experimental.
	FunctionArn() *string
	// Name of this function.
	// Experimental.
	FunctionName() *string
	// The principal this Lambda Function is running as.
	// Experimental.
	GrantPrincipal() awsiam.IPrincipal
	// Whether or not this Lambda function was bound to a VPC.
	//
	// If this is is `false`, trying to access the `connections` object will fail.
	// Experimental.
	IsBoundToVpc() *bool
	// The `$LATEST` version of this function.
	//
	// Note that this is reference to a non-specific AWS Lambda version, which
	// means the function this version refers to can return different results in
	// different invocations.
	//
	// To obtain a reference to an explicit version which references the current
	// function configuration, use `lambdaFunction.currentVersion` instead.
	// Experimental.
	LatestVersion() awslambda.IVersion
	// The LogGroup where the Lambda function's logs are made available.
	//
	// If either `logRetention` is set or this property is called, a CloudFormation custom resource is added to the stack that
	// pre-creates the log group as part of the stack deployment, if it already doesn't exist, and sets the correct log retention
	// period (never expire, by default).
	//
	// Further, if the log group already exists and the `logRetention` is not set, the custom resource will reset the log retention
	// to never expire even if it was configured with a different value.
	// Experimental.
	LogGroup() awslogs.ILogGroup
	// The tree node.
	// Experimental.
	Node() constructs.Node
	// The construct node where permissions are attached.
	// Experimental.
	PermissionsNode() constructs.Node
	// Returns a string-encoded token that resolves to the physical name that should be passed to the CloudFormation resource.
	//
	// This value will resolve to one of the following:
	// - a concrete value (e.g. `"my-awesome-bucket"`)
	// - `undefined`, when a name should be generated by CloudFormation
	// - a concrete name generated automatically during synthesis, in
	//   cross-environment scenarios.
	// Experimental.
	PhysicalName() *string
	// The ARN(s) to put into the resource field of the generated IAM policy for grantInvoke().
	// Experimental.
	ResourceArnsForGrantInvoke() *[]*string
	// Execution role associated with this function.
	// Experimental.
	Role() awsiam.IRole
	// The runtime configured for this lambda.
	// Experimental.
	Runtime() awslambda.Runtime
	// The stack in which this resource is defined.
	// Experimental.
	Stack() awscdk.Stack
	// The timeout configured for this lambda.
	// Experimental.
	Timeout() awscdk.Duration
	// Defines an alias for this function.
	//
	// The alias will automatically be updated to point to the latest version of
	// the function as it is being updated during a deployment.
	//
	// “`ts
	// declare const fn: lambda.Function;
	//
	// fn.addAlias('Live');
	//
	// // Is equivalent to
	//
	// new lambda.Alias(this, 'AliasLive', {
	//   aliasName: 'Live',
	//   version: fn.currentVersion,
	// });
	// “`.
	// Experimental.
	AddAlias(aliasName *string, options *awslambda.AliasOptions) awslambda.Alias
	// Adds an environment variable to this Lambda function.
	//
	// If this is a ref to a Lambda function, this operation results in a no-op.
	// Experimental.
	AddEnvironment(key *string, value *string, options *awslambda.EnvironmentOptions) awslambda.Function
	// Adds an event source to this function.
	//
	// Event sources are implemented in the aws-cdk-lib/aws-lambda-event-sources module.
	//
	// The following example adds an SQS Queue as an event source:
	// “`
	// import { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
	// myFunction.addEventSource(new SqsEventSource(myQueue));
	// “`.
	// Experimental.
	AddEventSource(source awslambda.IEventSource)
	// Adds an event source that maps to this AWS Lambda function.
	// Experimental.
	AddEventSourceMapping(id *string, options *awslambda.EventSourceMappingOptions) awslambda.EventSourceMapping
	// Adds a url to this lambda function.
	// Experimental.
	AddFunctionUrl(options *awslambda.FunctionUrlOptions) awslambda.FunctionUrl
	// Adds one or more Lambda Layers to this Lambda function.
	// Experimental.
	AddLayers(layers ...awslambda.ILayerVersion)
	// Adds a permission to the Lambda resource policy.
	// See: Permission for details.
	//
	// Experimental.
	AddPermission(id *string, permission *awslambda.Permission)
	// Adds a statement to the IAM role assumed by the instance.
	// Experimental.
	AddToRolePolicy(statement awsiam.PolicyStatement)
	// Apply the given removal policy to this resource.
	//
	// The Removal Policy controls what happens to this resource when it stops
	// being managed by CloudFormation, either because you've removed it from the
	// CDK application or because you've made a change that requires the resource
	// to be replaced.
	//
	// The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
	// account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).
	// Experimental.
	ApplyRemovalPolicy(policy awscdk.RemovalPolicy)
	// Configures options for asynchronous invocation.
	// Experimental.
	ConfigureAsyncInvoke(options *awslambda.EventInvokeConfigOptions)
	// A warning will be added to functions under the following conditions: - permissions that include `lambda:InvokeFunction` are added to the unqualified function.
	//
	// - function.currentVersion is invoked before or after the permission is created.
	//
	// This applies only to permissions on Lambda functions, not versions or aliases.
	// This function is overridden as a noOp for QualifiedFunctionBase.
	// Experimental.
	ConsiderWarningOnInvokeFunctionPermissions(scope constructs.Construct, action *string)
	// Experimental.
	GeneratePhysicalName() *string
	// Returns an environment-sensitive token that should be used for the resource's "ARN" attribute (e.g. `bucket.bucketArn`).
	//
	// Normally, this token will resolve to `arnAttr`, but if the resource is
	// referenced across environments, `arnComponents` will be used to synthesize
	// a concrete ARN with the resource's physical name. Make sure to reference
	// `this.physicalName` in `arnComponents`.
	// Experimental.
	GetResourceArnAttribute(arnAttr *string, arnComponents *awscdk.ArnComponents) *string
	// Returns an environment-sensitive token that should be used for the resource's "name" attribute (e.g. `bucket.bucketName`).
	//
	// Normally, this token will resolve to `nameAttr`, but if the resource is
	// referenced across environments, it will be resolved to `this.physicalName`,
	// which will be a concrete name.
	// Experimental.
	GetResourceNameAttribute(nameAttr *string) *string
	// Grant the given identity permissions to invoke this Lambda.
	// Experimental.
	GrantInvoke(grantee awsiam.IGrantable) awsiam.Grant
	// Grant multiple principals the ability to invoke this Lambda via CompositePrincipal.
	// Experimental.
	GrantInvokeCompositePrincipal(compositePrincipal awsiam.CompositePrincipal) *[]awsiam.Grant
	// Grant the given identity permissions to invoke the $LATEST version or unqualified version of this Lambda.
	// Experimental.
	GrantInvokeLatestVersion(grantee awsiam.IGrantable) awsiam.Grant
	// Grant the given identity permissions to invoke this Lambda Function URL.
	// Experimental.
	GrantInvokeUrl(grantee awsiam.IGrantable) awsiam.Grant
	// Grant the given identity permissions to invoke the given version of this Lambda.
	// Experimental.
	GrantInvokeVersion(grantee awsiam.IGrantable, version awslambda.IVersion) awsiam.Grant
	// Mix additional information into the hash of the Version object.
	//
	// The Lambda Function construct does its best to automatically create a new
	// Version when anything about the Function changes (its code, its layers,
	// any of the other properties).
	//
	// However, you can sometimes source information from places that the CDK cannot
	// look into, like the deploy-time values of SSM parameters. In those cases,
	// the CDK would not force the creation of a new Version object when it actually
	// should.
	//
	// This method can be used to invalidate the current Version object. Pass in
	// any string into this method, and make sure the string changes when you know
	// a new Version needs to be created.
	//
	// This method may be called more than once.
	// Experimental.
	InvalidateVersionBasedOn(x *string)
	// Return the given named metric for this Function.
	// Experimental.
	Metric(metricName *string, props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How long execution of this Lambda takes.
	//
	// Average over 5 minutes.
	// Experimental.
	MetricDuration(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How many invocations of this Lambda fail.
	//
	// Sum over 5 minutes.
	// Experimental.
	MetricErrors(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How often this Lambda is invoked.
	//
	// Sum over 5 minutes.
	// Experimental.
	MetricInvocations(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How often this Lambda is throttled.
	//
	// Sum over 5 minutes.
	// Experimental.
	MetricThrottles(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// Returns a string representation of this construct.
	// Experimental.
	ToString() *string
	// Experimental.
	WarnInvokeFunctionPermissions(scope constructs.Construct)
}

A Python Lambda function.

Example:

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/"),
		},
	},
})

Experimental.

func NewPythonFunction

func NewPythonFunction(scope constructs.Construct, id *string, props *PythonFunctionProps) PythonFunction

Experimental.

type PythonFunctionProps

type PythonFunctionProps struct {
	// The maximum age of a request that Lambda sends to a function for processing.
	//
	// Minimum: 60 seconds
	// Maximum: 6 hours.
	// Default: Duration.hours(6)
	//
	// Experimental.
	MaxEventAge awscdk.Duration `field:"optional" json:"maxEventAge" yaml:"maxEventAge"`
	// The destination for failed invocations.
	// Default: - no destination.
	//
	// Experimental.
	OnFailure awslambda.IDestination `field:"optional" json:"onFailure" yaml:"onFailure"`
	// The destination for successful invocations.
	// Default: - no destination.
	//
	// Experimental.
	OnSuccess awslambda.IDestination `field:"optional" json:"onSuccess" yaml:"onSuccess"`
	// The maximum number of times to retry when the function returns an error.
	//
	// Minimum: 0
	// Maximum: 2.
	// Default: 2.
	//
	// Experimental.
	RetryAttempts *float64 `field:"optional" json:"retryAttempts" yaml:"retryAttempts"`
	// Specify the configuration of AWS Distro for OpenTelemetry (ADOT) instrumentation.
	// See: https://aws-otel.github.io/docs/getting-started/lambda
	//
	// Default: - No ADOT instrumentation.
	//
	// Experimental.
	AdotInstrumentation *awslambda.AdotInstrumentationConfig `field:"optional" json:"adotInstrumentation" yaml:"adotInstrumentation"`
	// Whether to allow the Lambda to send all ipv6 network traffic.
	//
	// If set to true, there will only be a single egress rule which allows all
	// outbound ipv6 traffic. If set to false, you must individually add traffic rules to allow the
	// Lambda to connect to network targets using ipv6.
	//
	// Do not specify this property if the `securityGroups` or `securityGroup` property is set.
	// Instead, configure `allowAllIpv6Outbound` directly on the security group.
	// Default: false.
	//
	// Experimental.
	AllowAllIpv6Outbound *bool `field:"optional" json:"allowAllIpv6Outbound" yaml:"allowAllIpv6Outbound"`
	// Whether to allow the Lambda to send all network traffic (except ipv6).
	//
	// If set to false, you must individually add traffic rules to allow the
	// Lambda to connect to network targets.
	//
	// Do not specify this property if the `securityGroups` or `securityGroup` property is set.
	// Instead, configure `allowAllOutbound` directly on the security group.
	// Default: true.
	//
	// Experimental.
	AllowAllOutbound *bool `field:"optional" json:"allowAllOutbound" yaml:"allowAllOutbound"`
	// Lambda Functions in a public subnet can NOT access the internet.
	//
	// Use this property to acknowledge this limitation and still place the function in a public subnet.
	// See: https://stackoverflow.com/questions/52992085/why-cant-an-aws-lambda-function-inside-a-public-subnet-in-a-vpc-connect-to-the/52994841#52994841
	//
	// Default: false.
	//
	// Experimental.
	AllowPublicSubnet *bool `field:"optional" json:"allowPublicSubnet" yaml:"allowPublicSubnet"`
	// Sets the application log level for the function.
	// Default: "INFO".
	//
	// Deprecated: Use `applicationLogLevelV2` as a property instead.
	ApplicationLogLevel *string `field:"optional" json:"applicationLogLevel" yaml:"applicationLogLevel"`
	// Sets the application log level for the function.
	// Default: ApplicationLogLevel.INFO
	//
	// Experimental.
	ApplicationLogLevelV2 awslambda.ApplicationLogLevel `field:"optional" json:"applicationLogLevelV2" yaml:"applicationLogLevelV2"`
	// The system architectures compatible with this lambda function.
	// Default: Architecture.X86_64
	//
	// Experimental.
	Architecture awslambda.Architecture `field:"optional" json:"architecture" yaml:"architecture"`
	// Code signing config associated with this function.
	// Default: - Not Sign the Code.
	//
	// Experimental.
	CodeSigningConfig awslambda.ICodeSigningConfig `field:"optional" json:"codeSigningConfig" yaml:"codeSigningConfig"`
	// Options for the `lambda.Version` resource automatically created by the `fn.currentVersion` method.
	// Default: - default options as described in `VersionOptions`.
	//
	// Experimental.
	CurrentVersionOptions *awslambda.VersionOptions `field:"optional" json:"currentVersionOptions" yaml:"currentVersionOptions"`
	// The SQS queue to use if DLQ is enabled.
	//
	// If SNS topic is desired, specify `deadLetterTopic` property instead.
	// Default: - SQS queue with 14 day retention period if `deadLetterQueueEnabled` is `true`.
	//
	// Experimental.
	DeadLetterQueue awssqs.IQueue `field:"optional" json:"deadLetterQueue" yaml:"deadLetterQueue"`
	// Enabled DLQ.
	//
	// If `deadLetterQueue` is undefined,
	// an SQS queue with default options will be defined for your Function.
	// Default: - false unless `deadLetterQueue` is set, which implies DLQ is enabled.
	//
	// Experimental.
	DeadLetterQueueEnabled *bool `field:"optional" json:"deadLetterQueueEnabled" yaml:"deadLetterQueueEnabled"`
	// The SNS topic to use as a DLQ.
	//
	// Note that if `deadLetterQueueEnabled` is set to `true`, an SQS queue will be created
	// rather than an SNS topic. Using an SNS topic as a DLQ requires this property to be set explicitly.
	// Default: - no SNS topic.
	//
	// Experimental.
	DeadLetterTopic awssns.ITopic `field:"optional" json:"deadLetterTopic" yaml:"deadLetterTopic"`
	// A description of the function.
	// Default: - No description.
	//
	// Experimental.
	Description *string `field:"optional" json:"description" yaml:"description"`
	// Key-value pairs that Lambda caches and makes available for your Lambda functions.
	//
	// Use environment variables to apply configuration changes, such
	// as test and production environment configurations, without changing your
	// Lambda function source code.
	// Default: - No environment variables.
	//
	// Experimental.
	Environment *map[string]*string `field:"optional" json:"environment" yaml:"environment"`
	// The AWS KMS key that's used to encrypt your function's environment variables.
	// Default: - AWS Lambda creates and uses an AWS managed customer master key (CMK).
	//
	// Experimental.
	EnvironmentEncryption awskms.IKey `field:"optional" json:"environmentEncryption" yaml:"environmentEncryption"`
	// The size of the function’s /tmp directory in MiB.
	// Default: 512 MiB.
	//
	// Experimental.
	EphemeralStorageSize awscdk.Size `field:"optional" json:"ephemeralStorageSize" yaml:"ephemeralStorageSize"`
	// Event sources for this function.
	//
	// You can also add event sources using `addEventSource`.
	// Default: - No event sources.
	//
	// Experimental.
	Events *[]awslambda.IEventSource `field:"optional" json:"events" yaml:"events"`
	// The filesystem configuration for the lambda function.
	// Default: - will not mount any filesystem.
	//
	// Experimental.
	Filesystem awslambda.FileSystem `field:"optional" json:"filesystem" yaml:"filesystem"`
	// A name for the function.
	// Default: - AWS CloudFormation generates a unique physical ID and uses that
	// ID for the function's name. For more information, see Name Type.
	//
	// Experimental.
	FunctionName *string `field:"optional" json:"functionName" yaml:"functionName"`
	// Initial policy statements to add to the created Lambda Role.
	//
	// You can call `addToRolePolicy` to the created lambda to add statements post creation.
	// Default: - No policy statements are added to the created Lambda role.
	//
	// Experimental.
	InitialPolicy *[]awsiam.PolicyStatement `field:"optional" json:"initialPolicy" yaml:"initialPolicy"`
	// Specify the version of CloudWatch Lambda insights to use for monitoring.
	// See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights-Getting-Started-docker.html
	//
	// Default: - No Lambda Insights.
	//
	// Experimental.
	InsightsVersion awslambda.LambdaInsightsVersion `field:"optional" json:"insightsVersion" yaml:"insightsVersion"`
	// Allows outbound IPv6 traffic on VPC functions that are connected to dual-stack subnets.
	//
	// Only used if 'vpc' is supplied.
	// Default: false.
	//
	// Experimental.
	Ipv6AllowedForDualStack *bool `field:"optional" json:"ipv6AllowedForDualStack" yaml:"ipv6AllowedForDualStack"`
	// A list of layers to add to the function's execution environment.
	//
	// You can configure your Lambda function to pull in
	// additional code during initialization in the form of layers. Layers are packages of libraries or other dependencies
	// that can be used by multiple functions.
	// Default: - No layers.
	//
	// Experimental.
	Layers *[]awslambda.ILayerVersion `field:"optional" json:"layers" yaml:"layers"`
	// Sets the logFormat for the function.
	// Default: "Text".
	//
	// Deprecated: Use `loggingFormat` as a property instead.
	LogFormat *string `field:"optional" json:"logFormat" yaml:"logFormat"`
	// Sets the loggingFormat for the function.
	// Default: LoggingFormat.TEXT
	//
	// Experimental.
	LoggingFormat awslambda.LoggingFormat `field:"optional" json:"loggingFormat" yaml:"loggingFormat"`
	// The log group the function sends logs to.
	//
	// By default, Lambda functions send logs to an automatically created default log group named /aws/lambda/\<function name\>.
	// However you cannot change the properties of this auto-created log group using the AWS CDK, e.g. you cannot set a different log retention.
	//
	// Use the `logGroup` property to create a fully customizable LogGroup ahead of time, and instruct the Lambda function to send logs to it.
	//
	// Providing a user-controlled log group was rolled out to commercial regions on 2023-11-16.
	// If you are deploying to another type of region, please check regional availability first.
	// Default: `/aws/lambda/${this.functionName}` - default log group created by Lambda
	//
	// Experimental.
	LogGroup awslogs.ILogGroup `field:"optional" json:"logGroup" yaml:"logGroup"`
	// The number of days log events are kept in CloudWatch Logs.
	//
	// When updating
	// this property, unsetting it doesn't remove the log retention policy. To
	// remove the retention policy, set the value to `INFINITE`.
	//
	// This is a legacy API and we strongly recommend you move away from it if you can.
	// Instead create a fully customizable log group with `logs.LogGroup` and use the `logGroup` property
	// to instruct the Lambda function to send logs to it.
	// Migrating from `logRetention` to `logGroup` will cause the name of the log group to change.
	// Users and code and referencing the name verbatim will have to adjust.
	//
	// In AWS CDK code, you can access the log group name directly from the LogGroup construct:
	// “`ts
	// import * as logs from 'aws-cdk-lib/aws-logs';
	//
	// declare const myLogGroup: logs.LogGroup;
	// myLogGroup.logGroupName;
	// “`.
	// Default: logs.RetentionDays.INFINITE
	//
	// Experimental.
	LogRetention awslogs.RetentionDays `field:"optional" json:"logRetention" yaml:"logRetention"`
	// When log retention is specified, a custom resource attempts to create the CloudWatch log group.
	//
	// These options control the retry policy when interacting with CloudWatch APIs.
	//
	// This is a legacy API and we strongly recommend you migrate to `logGroup` if you can.
	// `logGroup` allows you to create a fully customizable log group and instruct the Lambda function to send logs to it.
	// Default: - Default AWS SDK retry options.
	//
	// Experimental.
	LogRetentionRetryOptions *awslambda.LogRetentionRetryOptions `field:"optional" json:"logRetentionRetryOptions" yaml:"logRetentionRetryOptions"`
	// The IAM role for the Lambda function associated with the custom resource that sets the retention policy.
	//
	// This is a legacy API and we strongly recommend you migrate to `logGroup` if you can.
	// `logGroup` allows you to create a fully customizable log group and instruct the Lambda function to send logs to it.
	// Default: - A new role is created.
	//
	// Experimental.
	LogRetentionRole awsiam.IRole `field:"optional" json:"logRetentionRole" yaml:"logRetentionRole"`
	// The amount of memory, in MB, that is allocated to your Lambda function.
	//
	// Lambda uses this value to proportionally allocate the amount of CPU
	// power. For more information, see Resource Model in the AWS Lambda
	// Developer Guide.
	// Default: 128.
	//
	// Experimental.
	MemorySize *float64 `field:"optional" json:"memorySize" yaml:"memorySize"`
	// Specify the configuration of Parameters and Secrets Extension.
	// See: https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-integration-lambda-extensions.html
	//
	// Default: - No Parameters and Secrets Extension.
	//
	// Experimental.
	ParamsAndSecrets awslambda.ParamsAndSecretsLayerVersion `field:"optional" json:"paramsAndSecrets" yaml:"paramsAndSecrets"`
	// Enable profiling.
	// See: https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
	//
	// Default: - No profiling.
	//
	// Experimental.
	Profiling *bool `field:"optional" json:"profiling" yaml:"profiling"`
	// Profiling Group.
	// See: https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
	//
	// Default: - A new profiling group will be created if `profiling` is set.
	//
	// Experimental.
	ProfilingGroup awscodeguruprofiler.IProfilingGroup `field:"optional" json:"profilingGroup" yaml:"profilingGroup"`
	// Sets the Recursive Loop Protection for Lambda Function.
	//
	// It lets Lambda detect and terminate unintended recusrive loops.
	// Default: RecursiveLoop.Terminate
	//
	// Experimental.
	RecursiveLoop awslambda.RecursiveLoop `field:"optional" json:"recursiveLoop" yaml:"recursiveLoop"`
	// The maximum of concurrent executions you want to reserve for the function.
	// See: https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html
	//
	// Default: - No specific limit - account limit.
	//
	// Experimental.
	ReservedConcurrentExecutions *float64 `field:"optional" json:"reservedConcurrentExecutions" yaml:"reservedConcurrentExecutions"`
	// Lambda execution role.
	//
	// This is the role that will be assumed by the function upon execution.
	// It controls the permissions that the function will have. The Role must
	// be assumable by the 'lambda.amazonaws.com' service principal.
	//
	// The default Role automatically has permissions granted for Lambda execution. If you
	// provide a Role, you must add the relevant AWS managed policies yourself.
	//
	// The relevant managed policies are "service-role/AWSLambdaBasicExecutionRole" and
	// "service-role/AWSLambdaVPCAccessExecutionRole".
	// Default: - A unique role will be generated for this lambda function.
	// Both supplied and generated roles can always be changed by calling `addToRolePolicy`.
	//
	// Experimental.
	Role awsiam.IRole `field:"optional" json:"role" yaml:"role"`
	// Sets the runtime management configuration for a function's version.
	// Default: Auto.
	//
	// Experimental.
	RuntimeManagementMode awslambda.RuntimeManagementMode `field:"optional" json:"runtimeManagementMode" yaml:"runtimeManagementMode"`
	// The list of security groups to associate with the Lambda's network interfaces.
	//
	// Only used if 'vpc' is supplied.
	// Default: - If the function is placed within a VPC and a security group is
	// not specified, either by this or securityGroup prop, a dedicated security
	// group will be created for this function.
	//
	// Experimental.
	SecurityGroups *[]awsec2.ISecurityGroup `field:"optional" json:"securityGroups" yaml:"securityGroups"`
	// Enable SnapStart for Lambda Function.
	//
	// SnapStart is currently supported only for Java 11, 17 runtime.
	// Default: - No snapstart.
	//
	// Experimental.
	SnapStart awslambda.SnapStartConf `field:"optional" json:"snapStart" yaml:"snapStart"`
	// Sets the system log level for the function.
	// Default: "INFO".
	//
	// Deprecated: Use `systemLogLevelV2` as a property instead.
	SystemLogLevel *string `field:"optional" json:"systemLogLevel" yaml:"systemLogLevel"`
	// Sets the system log level for the function.
	// Default: SystemLogLevel.INFO
	//
	// Experimental.
	SystemLogLevelV2 awslambda.SystemLogLevel `field:"optional" json:"systemLogLevelV2" yaml:"systemLogLevelV2"`
	// The function execution time (in seconds) after which Lambda terminates the function.
	//
	// Because the execution time affects cost, set this value
	// based on the function's expected execution time.
	// Default: Duration.seconds(3)
	//
	// Experimental.
	Timeout awscdk.Duration `field:"optional" json:"timeout" yaml:"timeout"`
	// Enable AWS X-Ray Tracing for Lambda Function.
	// Default: Tracing.Disabled
	//
	// Experimental.
	Tracing awslambda.Tracing `field:"optional" json:"tracing" yaml:"tracing"`
	// VPC network to place Lambda network interfaces.
	//
	// Specify this if the Lambda function needs to access resources in a VPC.
	// This is required when `vpcSubnets` is specified.
	// Default: - Function is not placed within a VPC.
	//
	// Experimental.
	Vpc awsec2.IVpc `field:"optional" json:"vpc" yaml:"vpc"`
	// Where to place the network interfaces within the VPC.
	//
	// This requires `vpc` to be specified in order for interfaces to actually be
	// placed in the subnets. If `vpc` is not specify, this will raise an error.
	//
	// Note: Internet access for Lambda Functions requires a NAT Gateway, so picking
	// public subnets is not allowed (unless `allowPublicSubnet` is set to `true`).
	// Default: - the Vpc default strategy if not specified.
	//
	// Experimental.
	VpcSubnets *awsec2.SubnetSelection `field:"optional" json:"vpcSubnets" yaml:"vpcSubnets"`
	// Path to the source of the function or the location for dependencies.
	// Experimental.
	Entry *string `field:"required" json:"entry" yaml:"entry"`
	// The runtime environment.
	//
	// Only runtimes of the Python family are
	// supported.
	// Experimental.
	Runtime awslambda.Runtime `field:"required" json:"runtime" yaml:"runtime"`
	// Bundling options to use for this function.
	//
	// Use this to specify custom bundling options like
	// the bundling Docker image, asset hash type, custom hash, architecture, etc.
	// Default: - Use the default bundling Docker image, with x86_64 architecture.
	//
	// Experimental.
	Bundling *BundlingOptions `field:"optional" json:"bundling" yaml:"bundling"`
	// The name of the exported handler in the index file.
	// Default: handler.
	//
	// Experimental.
	Handler *string `field:"optional" json:"handler" yaml:"handler"`
	// The path (relative to entry) to the index file containing the exported handler.
	// Default: index.py
	//
	// Experimental.
	Index *string `field:"optional" json:"index" yaml:"index"`
}

Properties for a PythonFunction.

Example:

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/"),
		},
	},
})

Experimental.

type PythonLayerVersion

type PythonLayerVersion interface {
	awslambda.LayerVersion
	// The runtimes compatible with this Layer.
	// Experimental.
	CompatibleRuntimes() *[]awslambda.Runtime
	// The environment this resource belongs to.
	//
	// For resources that are created and managed by the CDK
	// (generally, those created by creating new class instances like Role, Bucket, etc.),
	// this is always the same as the environment of the stack they belong to;
	// however, for imported resources
	// (those obtained from static methods like fromRoleArn, fromBucketName, etc.),
	// that might be different than the stack they were imported into.
	// Experimental.
	Env() *awscdk.ResourceEnvironment
	// The ARN of the Lambda Layer version that this Layer defines.
	// Experimental.
	LayerVersionArn() *string
	// The tree node.
	// Experimental.
	Node() constructs.Node
	// Returns a string-encoded token that resolves to the physical name that should be passed to the CloudFormation resource.
	//
	// This value will resolve to one of the following:
	// - a concrete value (e.g. `"my-awesome-bucket"`)
	// - `undefined`, when a name should be generated by CloudFormation
	// - a concrete name generated automatically during synthesis, in
	//   cross-environment scenarios.
	// Experimental.
	PhysicalName() *string
	// The stack in which this resource is defined.
	// Experimental.
	Stack() awscdk.Stack
	// Add permission for this layer version to specific entities.
	//
	// Usage within
	// the same account where the layer is defined is always allowed and does not
	// require calling this method. Note that the principal that creates the
	// Lambda function using the layer (for example, a CloudFormation changeset
	// execution role) also needs to have the “lambda:GetLayerVersion“
	// permission on the layer version.
	// Experimental.
	AddPermission(id *string, permission *awslambda.LayerVersionPermission)
	// Apply the given removal policy to this resource.
	//
	// The Removal Policy controls what happens to this resource when it stops
	// being managed by CloudFormation, either because you've removed it from the
	// CDK application or because you've made a change that requires the resource
	// to be replaced.
	//
	// The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
	// account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).
	// Experimental.
	ApplyRemovalPolicy(policy awscdk.RemovalPolicy)
	// Experimental.
	GeneratePhysicalName() *string
	// Returns an environment-sensitive token that should be used for the resource's "ARN" attribute (e.g. `bucket.bucketArn`).
	//
	// Normally, this token will resolve to `arnAttr`, but if the resource is
	// referenced across environments, `arnComponents` will be used to synthesize
	// a concrete ARN with the resource's physical name. Make sure to reference
	// `this.physicalName` in `arnComponents`.
	// Experimental.
	GetResourceArnAttribute(arnAttr *string, arnComponents *awscdk.ArnComponents) *string
	// Returns an environment-sensitive token that should be used for the resource's "name" attribute (e.g. `bucket.bucketName`).
	//
	// Normally, this token will resolve to `nameAttr`, but if the resource is
	// referenced across environments, it will be resolved to `this.physicalName`,
	// which will be a concrete name.
	// Experimental.
	GetResourceNameAttribute(nameAttr *string) *string
	// Returns a string representation of this construct.
	// Experimental.
	ToString() *string
}

A lambda layer version.

Example:

python.NewPythonLayerVersion(this, jsii.String("MyLayer"), &PythonLayerVersionProps{
	Entry: jsii.String("/path/to/my/layer"),
})

Experimental.

func NewPythonLayerVersion

func NewPythonLayerVersion(scope constructs.Construct, id *string, props *PythonLayerVersionProps) PythonLayerVersion

Experimental.

type PythonLayerVersionProps

type PythonLayerVersionProps struct {
	// The description the this Lambda Layer.
	// Default: - No description.
	//
	// Experimental.
	Description *string `field:"optional" json:"description" yaml:"description"`
	// The name of the layer.
	// Default: - A name will be generated.
	//
	// Experimental.
	LayerVersionName *string `field:"optional" json:"layerVersionName" yaml:"layerVersionName"`
	// The SPDX licence identifier or URL to the license file for this layer.
	// Default: - No license information will be recorded.
	//
	// Experimental.
	License *string `field:"optional" json:"license" yaml:"license"`
	// Whether to retain this version of the layer when a new version is added or when the stack is deleted.
	// Default: RemovalPolicy.DESTROY
	//
	// Experimental.
	RemovalPolicy awscdk.RemovalPolicy `field:"optional" json:"removalPolicy" yaml:"removalPolicy"`
	// The path to the root directory of the lambda layer.
	// Experimental.
	Entry *string `field:"required" json:"entry" yaml:"entry"`
	// Bundling options to use for this function.
	//
	// Use this to specify custom bundling options like
	// the bundling Docker image, asset hash type, custom hash, architecture, etc.
	// Default: - Use the default bundling Docker image, with x86_64 architecture.
	//
	// Experimental.
	Bundling *BundlingOptions `field:"optional" json:"bundling" yaml:"bundling"`
	// The system architectures compatible with this layer.
	// Default: [Architecture.X86_64]
	//
	// Experimental.
	CompatibleArchitectures *[]awslambda.Architecture `field:"optional" json:"compatibleArchitectures" yaml:"compatibleArchitectures"`
	// The runtimes compatible with the python layer.
	// Default: - Only Python 3.7 is supported.
	//
	// Experimental.
	CompatibleRuntimes *[]awslambda.Runtime `field:"optional" json:"compatibleRuntimes" yaml:"compatibleRuntimes"`
}

Properties for PythonLayerVersion.

Example:

python.NewPythonLayerVersion(this, jsii.String("MyLayer"), &PythonLayerVersionProps{
	Entry: jsii.String("/path/to/my/layer"),
})

Experimental.

Directories

Path Synopsis
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL