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

Chalice

class cdk_chalice.Chalice(*args: Any, **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[str, Any], package_config: Optional[cdk_chalice.PackageConfig] = None, preserve_logical_ids: bool = True) None[source]
Parameters
  • source_dir (str) – Path to Chalice application source code.

  • stage_config (Dict[str, Any]) – Chalice stage configuration. The configuration object should have the same structure as Chalice JSON stage configuration.

  • package_config (Optional[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 are 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.

Raises

ChaliceError – Error packaging the Chalice application.

package_config

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

sam_template

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

source_dir

(str) Path to Chalice application source code.

stage_config

(Dict[str, Any]) Chalice stage configuration. The object has the same structure as Chalice JSON stage configuration.

stage_name

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

PackageConfig

class cdk_chalice.PackageConfig(use_container: bool = False, image: Optional[str] = None, env: Optional[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: Optional[str] = None, env: Optional[Dict[str, str]] = None) None[source]
Parameters
  • use_container (bool) – Package the Chalice app in Docker container.

  • image (Optional[str]) – Docker image name. If image argument is not provided, the attribute is set to AWS Serverless Application Model (AWS SAM) image from Amazon ECR Public. Current environment’s Python version is used to select the image repository. For example: public.ecr.aws/sam/build-python3.7.

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

env

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

image

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

use_container

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

    _API_HANDLER_LAMBDA_MEMORY_SIZE = 128
    _API_HANDLER_LAMBDA_TIMEOUT = 10

    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,
                                             removal_policy=cdk.RemovalPolicy.DESTROY)
        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)

        self.dynamodb_table.grant_read_write_data(self.api_handler_iam_role)

        # 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