Build stage

The Build Stage is where your Serverless application gets built and packaged by SAM. We are going to use AWS CodeBuild as the Build provider for our pipeline. It is worth mentioning that CodePipeline also supports other providers like Jenkins, TeamCity.

Why AWS Code Build?

AWS CodeBuild is a great option because you only pay for the time where your build is running, which makes it very cost effective compared to running a dedicated build server 24 hours a day when you really only build during office hours. It is also container-based which means that you can bring your own Docker container image where your build runs, or use a managed image provided by CodeBuild.

Add the build stage

Let’s go ahead and add a Build stage to you sls_app/pipeline_stack.py:

from aws_cdk import (
    core,
    aws_codecommit,
    aws_codepipeline,
    aws_codepipeline_actions,
    aws_codebuild,
    aws_lambda
)

class PipelineStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, lambda_code: aws_lambda.CfnParametersCode = None, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        
        code_repo = aws_codecommit.Repository.from_repository_name(
            self, 
            "CodeRepo", 
            repository_name="sls-app"
        )
        
        source_output = aws_codepipeline.Artifact()
        cdk_build_output = aws_codepipeline.Artifact('CdkBuildOutput')
        lambda_build_output = aws_codepipeline.Artifact('LambdaBuildOutput')
        
        pipeline = aws_codepipeline.Pipeline(self,
            'Pipeline'
        )
        
        pipeline.add_stage(
            stage_name='Source',
            actions=[
                aws_codepipeline_actions.CodeCommitSourceAction(
                    action_name='Source_CodeCommit',
                    repository=code_repo,
                    output=source_output,
                )
            ]
        )
        
        build_project = aws_codebuild.PipelineProject(
            self,
            'Build',
            build_spec=aws_codebuild.BuildSpec.from_object({
                'version': '0.2',
                'phases': {
                    # `npm install` and run `cdk synth` to generate CloudFormation templates
                    'install': {
                       'runtime-versions': {
                            'python': 3.8
                        },
                        'commands': [
                            'echo "--------INSTALL PHASE--------"',
                            'npm install -g aws-cdk',
                            'pip3 install -r requirements.txt'
                            
                        ]
                    },
                    'build': {
                        'commands': 'cdk synth'
                    }
                },
                'artifacts': {
                    'secondary-artifacts': {
                        'CdkBuildOutput': {
                            'base-directory': 'cdk.out',
                            'files': ['**/*']
                        },
                        'LambdaBuildOutput': {
                            'base-directory': 'lambda',
                            'files': ['**/*']
                        }
                    }
                }
            })
        )
        
        pipeline.add_stage(
            stage_name='Build',
            actions=[
                aws_codepipeline_actions.CodeBuildAction(
                    action_name='Build_CodeBuild',
                    project=build_project,
                    input=source_output,
                    outputs=[cdk_build_output, lambda_build_output]
                )
            ]
        )

Update the main app

Before deploy CDK, we need to modify sls-app/app.py to add new stack.

#!/usr/bin/env python3

from aws_cdk import core

from sls_app.sls_app_stack import SlsAppStack
from sls_app.pipeline_stack import PipelineStack


app = core.App()
sls_stack = SlsAppStack(app, "sls-app")

PipelineStack(app, "PipelineStack",
    lambda_code=sls_stack.lambda_code)
    
app.synth()

Deploy the pipeline

Because we added the new stack PipelineStack and this stack is used to be deploy our app (includes sls-app), so we just need to deploy PipelineStack. Run it now.

cdk deploy PipelineStack

CDK will show for you the different between old version and new version, confirm deploy by press ‘y’. Confirm You can verify the new stack by open the CloudFormation console.

The important thing here is the Code Pipeline, so switch to AWS CodePipeline and see your result. Pipeline

We have 2 stages (Source and Build), but this is not enough, go to next chapter to complete the pipeline 👉