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 or CloudBees.

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 PipelineStack.java:

// Declare build output as artifacts
Artifact buildOutput = new Artifact("buildOutput");

// Declare a new CodeBuild project
PipelineProject buildProject = new PipelineProject(this, "Build", PipelineProjectProps.builder()
        .environment(BuildEnvironment.builder()
                .buildImage(AMAZON_LINUX_2).build())
        .environmentVariables(Collections.singletonMap("PACKAGE_BUCKET", BuildEnvironmentVariable.builder()
                .value(artifactsBucket.getBucketName())
                .build()))
        .build());

// Add the build stage to our pipeline
CodeBuildAction buildAction = new CodeBuildAction(CodeBuildActionProps.builder()
        .actionName("Build")
        .project(buildProject)
        .input(sourceOutput)
        .outputs(Collections.singletonList(buildOutput))
        .build());

pipeline.addStage(StageOptions.builder()
        .stageName("Build")
        .actions(Collections.singletonList(buildAction))
        .build());
Click here to see how the entire file should look like

Deploy the pipeline

From your terminal, run the following commands to deploy the pipeline:

mvn package
cdk deploy

Verify pipeline creation

Navigate to the AWS CodePipeline Console and click on your newly created pipeline!

VerifyPipeline

The Build step should have failed. Don’t worry! this is expected because we haven’t specified what commands to run during the build yet, so AWS CodeBuild doesn’t know how to build our Serverless application.

VerifyPipeline

Let’s fix that.