Update Sls Stack

To have a succesful code pipeline with AWS CDK, we must update the sls_stack.py to match with our pipeline.

Add a LambdaDeploymentGroup to stack

Our stack includes the lambda_code property, which is an instance of the CfnParametersCode class. This property represents the code that is supplied later by the pipeline. Because the pipeline needs access to the object, we expose it as a public property of our class.

from datetime import datetime

from aws_cdk import (
    core,
    aws_lambda,
    aws_dynamodb,
    aws_apigateway,
    aws_codedeploy
)


class SlsAppStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        
        ## 1. Define the table that count number of times the path is hitted.
        table = aws_dynamodb.Table(
            self, 
            "counter-table",
            partition_key={
                'name': 'path',
                'type': aws_dynamodb.AttributeType.STRING
            }
        )
        
        ## 2.1. Defines Lambda resource & API-Gateway request handler
        ## All API requests will go to the same function.
        self.lambda_code = aws_lambda.Code.from_cfn_parameters()
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        handler = aws_lambda.Function(self, "CounterFunction",
            description=f"Generated on {now}",
            function_name='CounterFunction',
            code=self.lambda_code,
            handler='index.handler',
            runtime=aws_lambda.Runtime.PYTHON_3_8
        )
        
        current_version = handler.current_version
        alias = current_version.add_alias('Prod')
        
        ## 2.2. Pass the table name to the handler through an env variable 
        ## and grant the handler read/write permissions on the table.
        table.grant_read_write_data(handler)
        handler.add_environment('TABLE_NAME', table.table_name)
        
        ## 3. Define the API endpoint and associate the handler
        api = aws_apigateway.LambdaRestApi(self, "CounterAPI",
                                           handler=handler)
                                         
        ## 4. Define new Lambda application                                         
        app = aws_codedeploy.LambdaApplication(
            self,
            "ApplicationDeploy"
        )
        
        ## 5. Create LambdaDeploymentGroup for our lambda
        aws_codedeploy.LambdaDeploymentGroup(self,
            'DeploymentGroup',
            alias=alias,
            application=app,
            deployment_config=aws_codedeploy.LambdaDeploymentConfig.ALL_AT_ONCE
        )

The alias uses a Lambda version obtained using the function’s currentVersion property. This ensures that every invocation of the AWS CDK code publishes a new version of the function.