CfnParametersCode

class aws_cdk.aws_lambda.CfnParametersCode(*, bucket_name_param=None, object_key_param=None)

Bases: Code

Lambda code defined using 2 CloudFormation parameters.

Useful when you don’t have access to the code of your Lambda from your CDK code, so you can’t use Assets, and you want to deploy the Lambda in a CodePipeline, using CloudFormation Actions - you can fill the parameters using the {@link #assign} method.

ExampleMetadata:

lit=test/integ.lambda-deployed-through-codepipeline.lit.ts infused

Example:

lambda_stack = cdk.Stack(app, "LambdaStack")
lambda_code = lambda_.Code.from_cfn_parameters()
lambda_.Function(lambda_stack, "Lambda",
    code=lambda_code,
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_14_X
)
# other resources that your Lambda needs, added to the lambdaStack...

pipeline_stack = cdk.Stack(app, "PipelineStack")
pipeline = codepipeline.Pipeline(pipeline_stack, "Pipeline")

# add the source code repository containing this code to your Pipeline,
# and the source code of the Lambda Function, if they're separate
cdk_source_output = codepipeline.Artifact()
cdk_source_action = codepipeline_actions.CodeCommitSourceAction(
    repository=codecommit.Repository(pipeline_stack, "CdkCodeRepo",
        repository_name="CdkCodeRepo"
    ),
    action_name="CdkCode_Source",
    output=cdk_source_output
)
lambda_source_output = codepipeline.Artifact()
lambda_source_action = codepipeline_actions.CodeCommitSourceAction(
    repository=codecommit.Repository(pipeline_stack, "LambdaCodeRepo",
        repository_name="LambdaCodeRepo"
    ),
    action_name="LambdaCode_Source",
    output=lambda_source_output
)
pipeline.add_stage(
    stage_name="Source",
    actions=[cdk_source_action, lambda_source_action]
)

# synthesize the Lambda CDK template, using CodeBuild
# the below values are just examples, assuming your CDK code is in TypeScript/JavaScript -
# adjust the build environment and/or commands accordingly
cdk_build_project = codebuild.Project(pipeline_stack, "CdkBuildProject",
    environment=codebuild.BuildEnvironment(
        build_image=codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_1_0
    ),
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "install": {
                "commands": "npm install"
            },
            "build": {
                "commands": ["npm run build", "npm run cdk synth LambdaStack -- -o ."
                ]
            }
        },
        "artifacts": {
            "files": "LambdaStack.template.yaml"
        }
    })
)
cdk_build_output = codepipeline.Artifact()
cdk_build_action = codepipeline_actions.CodeBuildAction(
    action_name="CDK_Build",
    project=cdk_build_project,
    input=cdk_source_output,
    outputs=[cdk_build_output]
)

# build your Lambda code, using CodeBuild
# again, this example assumes your Lambda is written in TypeScript/JavaScript -
# make sure to adjust the build environment and/or commands if they don't match your specific situation
lambda_build_project = codebuild.Project(pipeline_stack, "LambdaBuildProject",
    environment=codebuild.BuildEnvironment(
        build_image=codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_1_0
    ),
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "install": {
                "commands": "npm install"
            },
            "build": {
                "commands": "npm run build"
            }
        },
        "artifacts": {
            "files": ["index.js", "node_modules/**/*"
            ]
        }
    })
)
lambda_build_output = codepipeline.Artifact()
lambda_build_action = codepipeline_actions.CodeBuildAction(
    action_name="Lambda_Build",
    project=lambda_build_project,
    input=lambda_source_output,
    outputs=[lambda_build_output]
)

pipeline.add_stage(
    stage_name="Build",
    actions=[cdk_build_action, lambda_build_action]
)

# finally, deploy your Lambda Stack
pipeline.add_stage(
    stage_name="Deploy",
    actions=[
        codepipeline_actions.CloudFormationCreateUpdateStackAction(
            action_name="Lambda_CFN_Deploy",
            template_path=cdk_build_output.at_path("LambdaStack.template.yaml"),
            stack_name="LambdaStackDeployedName",
            admin_permissions=True,
            parameter_overrides=lambda_code.assign(lambda_build_output.s3_location),
            extra_inputs=[lambda_build_output
            ]
        )
    ]
)
Parameters:
  • bucket_name_param (Optional[CfnParameter]) – The CloudFormation parameter that represents the name of the S3 Bucket where the Lambda code will be located in. Must be of type ‘String’. Default: a new parameter will be created

  • object_key_param (Optional[CfnParameter]) – The CloudFormation parameter that represents the path inside the S3 Bucket where the Lambda code will be located at. Must be of type ‘String’. Default: a new parameter will be created

Methods

assign(*, bucket_name, object_key, object_version=None)

Create a parameters map from this instance’s CloudFormation parameters.

It returns a map with 2 keys that correspond to the names of the parameters defined in this Lambda code, and as values it contains the appropriate expressions pointing at the provided S3 location (most likely, obtained from a CodePipeline Artifact by calling the artifact.s3Location method). The result should be provided to the CloudFormation Action that is deploying the Stack that the Lambda with this code is part of, in the parameterOverrides property.

Parameters:
  • bucket_name (str) – The name of the S3 Bucket the object is in.

  • object_key (str) – The path inside the Bucket where the object is located at.

  • object_version (Optional[str]) – The S3 object version.

Return type:

Mapping[str, Any]

bind(scope)

Called when the lambda or layer is initialized to allow this object to bind to the stack, add resources and have fun.

Parameters:

scope (Construct) –

Return type:

CodeConfig

bind_to_resource(_resource, *, resource_property=None)

Called after the CFN function resource has been created to allow the code class to bind to it.

Specifically it’s required to allow assets to add metadata for tooling like SAM CLI to be able to find their origins.

Parameters:
  • _resource (CfnResource) –

  • resource_property (Optional[str]) – The name of the CloudFormation property to annotate with asset metadata. Default: Code

Return type:

None

Attributes

bucket_name_param
is_inline

Determines whether this Code is inline code or not.

object_key_param

Static Methods

classmethod asset(path)

(deprecated) DEPRECATED.

Parameters:

path (str) –

Deprecated:

use fromAsset

Stability:

deprecated

Return type:

AssetCode

classmethod bucket(bucket, key, object_version=None)

(deprecated) DEPRECATED.

Parameters:
  • bucket (IBucket) –

  • key (str) –

  • object_version (Optional[str]) –

Deprecated:

use fromBucket

Stability:

deprecated

Return type:

S3Code

classmethod cfn_parameters(*, bucket_name_param=None, object_key_param=None)

(deprecated) DEPRECATED.

Parameters:
  • bucket_name_param (Optional[CfnParameter]) – The CloudFormation parameter that represents the name of the S3 Bucket where the Lambda code will be located in. Must be of type ‘String’. Default: a new parameter will be created

  • object_key_param (Optional[CfnParameter]) – The CloudFormation parameter that represents the path inside the S3 Bucket where the Lambda code will be located at. Must be of type ‘String’. Default: a new parameter will be created

Deprecated:

use fromCfnParameters

Stability:

deprecated

Return type:

CfnParametersCode

classmethod from_asset(path, *, readers=None, source_hash=None, exclude=None, follow=None, ignore_mode=None, follow_symlinks=None, asset_hash=None, asset_hash_type=None, bundling=None)

Loads the function code from a local disk path.

Parameters:
  • path (str) – Either a directory with the Lambda code bundle or a .zip file.

  • readers (Optional[Sequence[IGrantable]]) – A list of principals that should be able to read this asset from S3. You can use asset.grantRead(principal) to grant read permissions later. Default: - No principals that can read file asset.

  • source_hash (Optional[str]) – (deprecated) Custom hash to use when identifying the specific version of the asset. For consistency, this custom hash will be SHA256 hashed and encoded as hex. The resulting hash will be the asset hash. NOTE: the source 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 source hash, you will need to make sure it is updated every time the source changes, or otherwise it is possible that some deployments will not be invalidated. Default: - automatically calculate source hash based on the contents of the source file or directory.

  • exclude (Optional[Sequence[str]]) – (deprecated) Glob patterns to exclude from the copy. Default: nothing is excluded

  • follow (Optional[FollowMode]) – (deprecated) A strategy for how to handle symlinks. Default: Never

  • ignore_mode (Optional[IgnoreMode]) – (deprecated) The ignore behavior to use for exclude patterns. Default: - GLOB for file assets, DOCKER or GLOB for docker assets depending on whether the ‘

  • follow_symlinks (Optional[SymlinkFollowMode]) – A strategy for how to handle symlinks. Default: SymlinkFollowMode.NEVER

  • asset_hash (Optional[str]) – 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

  • asset_hash_type (Optional[AssetHashType]) – Specifies the type of hash to calculate for this asset. If assetHash is configured, this option must be undefined or AssetHashType.CUSTOM. Default: - the default is AssetHashType.SOURCE, but if assetHash is explicitly specified this value defaults to AssetHashType.CUSTOM.

  • bundling (Union[BundlingOptions, Dict[str, Any], None]) – Bundle the asset by executing a command in a Docker container or a custom bundling provider. The asset path will be mounted at /asset-input. The Docker container is responsible for putting content at /asset-output. The content at /asset-output will be zipped and used as the final asset. Default: - uploaded as-is to S3 if the asset is a regular file or a .zip file, archived into a .zip file and uploaded to S3 otherwise

Return type:

AssetCode

classmethod from_asset_image(directory, *, cmd=None, entrypoint=None, working_directory=None, build_args=None, file=None, invalidation=None, network_mode=None, platform=None, repository_name=None, target=None, extra_hash=None, exclude=None, follow=None, ignore_mode=None, follow_symlinks=None)

Create an ECR image from the specified asset and bind it as the Lambda code.

Parameters:
  • directory (str) – the directory from which the asset must be created.

  • cmd (Optional[Sequence[str]]) – Specify or override the CMD on the specified Docker image or Dockerfile. This needs to be in the ‘exec form’, viz., [ 'executable', 'param1', 'param2' ]. Default: - use the CMD specified in the docker image or Dockerfile.

  • entrypoint (Optional[Sequence[str]]) – Specify or override the ENTRYPOINT on the specified Docker image or Dockerfile. An ENTRYPOINT allows you to configure a container that will run as an executable. This needs to be in the ‘exec form’, viz., [ 'executable', 'param1', 'param2' ]. Default: - use the ENTRYPOINT in the docker image or Dockerfile.

  • working_directory (Optional[str]) – Specify or override the WORKDIR on the specified Docker image or Dockerfile. A WORKDIR allows you to configure the working directory the container will use. Default: - use the WORKDIR in the docker image or Dockerfile.

  • build_args (Optional[Mapping[str, str]]) – Build args to pass to the docker build command. Since Docker build arguments are resolved before deployment, keys and values cannot refer to unresolved tokens (such as lambda.functionArn or queue.queueUrl). Default: - no build args are passed

  • file (Optional[str]) – Path to the Dockerfile (relative to the directory). Default: ‘Dockerfile’

  • invalidation (Union[DockerImageAssetInvalidationOptions, Dict[str, Any], None]) – Options to control which parameters are used to invalidate the asset hash. Default: - hash all parameters

  • network_mode (Optional[NetworkMode]) – Networking mode for the RUN commands during build. Support docker API 1.25+. Default: - no networking mode specified (the default networking mode NetworkMode.DEFAULT will be used)

  • platform (Optional[Platform]) – Platform to build for. Requires Docker Buildx. Default: - no platform specified (the current machine architecture will be used)

  • repository_name (Optional[str]) – (deprecated) ECR repository name. Specify this property if you need to statically address the image, e.g. from a Kubernetes Pod. Note, this is only the repository name, without the registry and the tag parts. Default: - the default ECR repository for CDK assets

  • target (Optional[str]) – Docker target to build to. Default: - no target

  • extra_hash (Optional[str]) – (deprecated) Extra information to encode into the fingerprint (e.g. build instructions and other inputs). Default: - hash is only based on source content

  • exclude (Optional[Sequence[str]]) – (deprecated) Glob patterns to exclude from the copy. Default: nothing is excluded

  • follow (Optional[FollowMode]) – (deprecated) A strategy for how to handle symlinks. Default: Never

  • ignore_mode (Optional[IgnoreMode]) – (deprecated) The ignore behavior to use for exclude patterns. Default: - GLOB for file assets, DOCKER or GLOB for docker assets depending on whether the ‘

  • follow_symlinks (Optional[SymlinkFollowMode]) – A strategy for how to handle symlinks. Default: SymlinkFollowMode.NEVER

Return type:

AssetImageCode

classmethod from_bucket(bucket, key, object_version=None)

Lambda handler code as an S3 object.

Parameters:
  • bucket (IBucket) – The S3 bucket.

  • key (str) – The object key.

  • object_version (Optional[str]) – Optional S3 object version.

Return type:

S3Code

classmethod from_cfn_parameters(*, bucket_name_param=None, object_key_param=None)

Creates a new Lambda source defined using CloudFormation parameters.

Parameters:
  • bucket_name_param (Optional[CfnParameter]) – The CloudFormation parameter that represents the name of the S3 Bucket where the Lambda code will be located in. Must be of type ‘String’. Default: a new parameter will be created

  • object_key_param (Optional[CfnParameter]) – The CloudFormation parameter that represents the path inside the S3 Bucket where the Lambda code will be located at. Must be of type ‘String’. Default: a new parameter will be created

Return type:

CfnParametersCode

Returns:

a new instance of CfnParametersCode

classmethod from_docker_build(path, *, image_path=None, output_path=None, build_args=None, file=None, platform=None)

Loads the function code from an asset created by a Docker build.

By default, the asset is expected to be located at /asset in the image.

Parameters:
  • path (str) – The path to the directory containing the Docker file.

  • image_path (Optional[str]) – The path in the Docker image where the asset is located after the build operation. Default: /asset

  • output_path (Optional[str]) – The path on the local filesystem where the asset will be copied using docker cp. Default: - a unique temporary directory in the system temp directory

  • build_args (Optional[Mapping[str, str]]) – Build args. Default: - no build args

  • file (Optional[str]) – Name of the Dockerfile, must relative to the docker build path. Default: Dockerfile

  • platform (Optional[str]) – Set platform if server is multi-platform capable. Requires Docker Engine API v1.38+. Example value: linux/amd64 Default: - no platform specified

Return type:

AssetCode

classmethod from_ecr_image(repository, *, cmd=None, entrypoint=None, tag=None, tag_or_digest=None, working_directory=None)

Use an existing ECR image as the Lambda code.

Parameters:
  • repository (IRepository) – the ECR repository that the image is in.

  • cmd (Optional[Sequence[str]]) – Specify or override the CMD on the specified Docker image or Dockerfile. This needs to be in the ‘exec form’, viz., [ 'executable', 'param1', 'param2' ]. Default: - use the CMD specified in the docker image or Dockerfile.

  • entrypoint (Optional[Sequence[str]]) – Specify or override the ENTRYPOINT on the specified Docker image or Dockerfile. An ENTRYPOINT allows you to configure a container that will run as an executable. This needs to be in the ‘exec form’, viz., [ 'executable', 'param1', 'param2' ]. Default: - use the ENTRYPOINT in the docker image or Dockerfile.

  • tag (Optional[str]) – (deprecated) The image tag to use when pulling the image from ECR. Default: ‘latest’

  • tag_or_digest (Optional[str]) – The image tag or digest to use when pulling the image from ECR (digests must start with sha256:). Default: ‘latest’

  • working_directory (Optional[str]) – Specify or override the WORKDIR on the specified Docker image or Dockerfile. A WORKDIR allows you to configure the working directory the container will use. Default: - use the WORKDIR in the docker image or Dockerfile.

Return type:

EcrImageCode

classmethod from_inline(code)

Inline code for Lambda handler.

Parameters:

code (str) – The actual handler code (limited to 4KiB).

Return type:

InlineCode

Returns:

LambdaInlineCode with inline code.

classmethod inline(code)

(deprecated) DEPRECATED.

Parameters:

code (str) –

Deprecated:

use fromInline

Stability:

deprecated

Return type:

InlineCode