Welcome to cdk-chalice’s documentation!

If you are looking for information on a specific class or method, this documentation is for you.

Table of Contents


class cdk_chalice.Chalice(*args, **kwargs)[source]

Chalice construct.

Adds the provided stage configuration to source_dir/.chalice/config.json. Stage name will be the string representation of current CDK scope.

Packages the application into AWS SAM format and imports the resulting template into the construct tree under the provided scope.

__init__(scope: aws_cdk.core.Construct, id: str, *, source_dir: str, stage_config: dict, package_config: cdk_chalice.PackageConfig = None, preserve_logical_ids: bool = True, **kwargs) → None[source]
  • source_dir (str) – Path to Chalice application source code.

  • stage_config (dict) – Chalice stage configuration. The configuration object should have the same structure as Chalice JSON stage configuration.

  • package_config (PackageConfig) – Configuration for packaging the Chalice application.

  • preserve_logical_ids (bool) – Whether the resources should have the same logical IDs in the resulting CDK template as they did in the original CloudFormation template file. If you’re vending a Construct using cdk-chalice, make sure to pass this as False. Note: regardless of whether this option is true or false, the sam_template’s get_resource and related methods always uses the original logical ID of the resource/element, as specified in the template file.


ChaliceError – Error packaging the Chalice application.


(PackageConfig) If not provided, PackageConfig instance with default arguments is used.


(aws_cdk.cloudformation_include.CfnInclude) AWS SAM template updated with AWS CDK values where applicable. Can be used to reference, access, and customize resources generated by chalice package command as CDK native objects.


(str) Path to Chalice application source code.


(dict) Chalice stage configuration. The object has the same structure as Chalice JSON stage configuration.


(str) Chalice stage name. It is automatically assigned the encompassing CDK scope’s name.


class cdk_chalice.PackageConfig(use_container: bool = False, image: str = None, env: Dict[str, str] = None)[source]

Configuration for packaging Chalice app.

If your functions depend on packages that have natively compiled dependencies, build your functions inside a Docker container. In order to instruct Chalice class to do so, set use_container to True.

When packaging the Chalice app in Docker container, the default image closely mimics AWS Lambda execution environment. If a custom container image is used, it is the owner responsibility to make sure it mimics Lambda execution environment.

__init__(use_container: bool = False, image: str = None, env: Dict[str, str] = None) → None[source]
  • use_container (bool) – Package the Chalice app in Docker container.

  • image (str) – Docker image name. Defaults to image that closely mimics AWS Lambda execution environment.

  • env (Dict[str,str]) – Environment variables to set for packaging. AWS_DEFAULT_REGION is set to us-east-1 unless explicitly specified otherwise.


(Dict[str,str]) Environment variables used during packaging.


(str) Docker image name. Used when use_container is set to True.


(bool) If True, package the Chalice app in Docker container. By default packages the app in subprocess.

Usage Example

Example of using Chalice class in a stack that creates a basic web API.

Note the customization of Chalice-generated resources using self.chalice.sam_template attribute. cdk-chalice uses aws_cdk.cloudformation_include module to expose resources in the SAM template as native CDK objects. For example, rest_api variable below is an instance of aws_cdk.aws_sam.CfnApi class. This capability allows to reference or customize Chalice application resources within the broader CDK application.

The workflow for customization would be as follows:

  • Implement the initial Chalice application using stage configuration (stage_config)

  • Run cdk synth

  • Open the generated chalice.out/<package ID>/sam.json file, and find the logical ID of the relevant resource

  • Retrieve the CDK object for the resource using self.chalice.sam_template.get_resource('<logical ID>') method

Any modifications made to the resource will be reflected in the resulting CDK template.

import os

from aws_cdk import (
    aws_dynamodb as dynamodb,
    aws_iam as iam,
    core as cdk
from cdk_chalice import Chalice

class WebApi(cdk.Stack):


    def __init__(self, scope: cdk.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        partition_key = dynamodb.Attribute(name='username', type=dynamodb.AttributeType.STRING)
        self.dynamodb_table = dynamodb.Table(self, 'UsersTable', partition_key=partition_key,
        cdk.CfnOutput(self, 'UsersTableName', value=self.dynamodb_table.table_name)

        lambda_service_principal = iam.ServicePrincipal('lambda.amazonaws.com')
        self.api_handler_iam_role = iam.Role(self, 'ApiHandlerLambdaRole', assumed_by=lambda_service_principal)


        # Assuming 'runtime' is a relative directory in the same project/repository
        runtime_source_dir = os.path.join(os.path.dirname(__file__), os.pardir, 'runtime')
        chalice_stage_config = self._create_chalice_stage_config()
        self.chalice = Chalice(self, 'WebApi', source_dir=runtime_source_dir, stage_config=chalice_stage_config)
        rest_api = self.chalice.sam_template.get_resource('RestAPI')
        rest_api.tracing_enabled = True

    def _create_chalice_stage_config(self):
        chalice_stage_config = {
            'api_gateway_stage': 'v1',
            'lambda_functions': {
                'api_handler': {
                    'manage_iam_role': False,
                    'iam_role_arn': self.api_handler_iam_role.role_arn,
                    'environment_variables': {
                        'DYNAMODB_TABLE_NAME': self.dynamodb_table.table_name
                    'lambda_memory_size': WebApi._API_HANDLER_LAMBDA_MEMORY_SIZE,
                    'lambda_timeout': WebApi._API_HANDLER_LAMBDA_TIMEOUT

        return chalice_stage_config