AWS Builder Center
SAM Builds in CodePipeline: A buildspec.yml Deep Dive

SAM Builds in CodePipeline: A buildspec.yml Deep Dive

Deep-dive into configuring your SAM application with CodePipeline and CodeBuild using buildspec.yaml, highlighting key configurations for seamless deployments.

📌 Step-by-Step Configuration:

1️⃣ Add a Proper  buildspec.yaml  File

Your CodeBuild project uses a  buildspec.yaml  to run the AWS SAM commands for packaging and deployment:
YAML
version: 0.2
phases:
pre_build:
commands:
- echo Logging in to SAM build...
- aws --version
- sam --version
- mvn --version
build:
commands:
- echo Build started on `date`
- cd HelloWorldFunction
- mvn clean compile install -DskipTests=true
- cd ..
- sam validate -t template.yaml --lint
- echo ${S3_BUCKET} # S3_BUCKET defined in the environment variables of the code build
- sam package --template-file template.yaml --s3-bucket ${S3_BUCKET} --output-template-file packaged.yaml --no-resolve-s3
post_build:
commands:
- echo Build completed on `date`
artifacts:
files:
- HelloWorldFunction/target/HelloWorld-1.0.jar
- packaged.yaml
  • ✅ Note: The packaged SAM template ( packaged.yaml ) is generated from your original  template.yaml . This  packaged.yaml  is referenced explicitly in your pipeline for deployment.



2️⃣ CodePipeline Configuration with CloudFormation Actions

Ensure your AWS CodePipeline explicitly uses the  packaged.yaml  created during the build stage:
YAML
- Name: Deploy
OnFailure:
Result: ROLLBACK
Actions:
- Name: CreateChangeSet
ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: '1'
InputArtifacts:
- Name: BuildOutput
Configuration:
ActionMode: CHANGE_SET_REPLACE
StackName: !Sub "${StackName}-${AWS::AccountId}-${AWS::Region}"
Capabilities: CAPABILITY_IAM,CAPABILITY_AUTO_EXPAND,CAPABILITY_NAMED_IAM
ChangeSetName: !Sub "CodePipelineChangeSet-${AWS::AccountId}-${AWS::Region}"
TemplatePath: "BuildOutput::packaged.yaml"
RoleArn: !GetAtt CodePipelineRole.Arn
RunOrder: 1

- Name: ExecuteChangeSet
ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CloudFormation
Version: '1'
InputArtifacts:
- Name: BuildOutput
Configuration:
ActionMode: CHANGE_SET_EXECUTE
StackName: !Sub "${StackName}-${AWS::AccountId}-${AWS::Region}"
Capabilities: CAPABILITY_IAM,CAPABILITY_AUTO_EXPAND,CAPABILITY_NAMED_IAM
ChangeSetName: !Sub "CodePipelineChangeSet-${AWS::AccountId}-${AWS::Region}"
TemplatePath: "BuildOutput::packaged.yaml"
RoleArn: !GetAtt CodePipelineRole.Arn
RunOrder: 2
  • ✅ Note: The  OnFailure: ROLLBACK  ensures that failed deployments automatically roll back to the last known stable configuration.



3️⃣ Configuring AWS CodeBuild with Environment Variables

The AWS CodeBuild environment explicitly specifies the artifact bucket ( S3_BUCKET ) as an environment variable:
YAML
CodeBuildProject:
Type: AWS::CodeBuild::Project
Properties:
Name: CodeBuildMaven
LogsConfig:
CloudWatchLogs:
Status: ENABLED
GroupName: !Ref CodeBuildLogGroup
Source:
Type: CODEPIPELINE
BuildSpec: "buildspec.yaml"
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Image: "aws/codebuild/amazonlinux-x86_64-standard:5.0"
Type: LINUX_CONTAINER
EnvironmentVariables:
- Name: S3_BUCKET
Type: PLAINTEXT
Value: !Ref ArtifactBucketName
ServiceRole: !GetAtt CodeBuildRole.Arn
Artifacts:
Type: CODEPIPELINE
  • ✅ Tip: This setup ensures secure and easy management of environment-specific configurations.



4️⃣ Utilizing Correct Artifact Paths in SAM Templates

Your SAM  template.yaml  should correctly reference the artifact files created during the build:
YAML
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: HelloWorldFunction/target/HelloWorld-1.0.jar
Handler: helloworld.App::handleRequest
Runtime: java11
Architectures:
- x86_64
MemorySize: 512
Environment:
Variables:
PARAM1: VALUE
JAVA_TOOL_OPTIONS: -XX:+TieredCompilation -XX:TieredStopAtLevel=1
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
  • ✅ Important: The  CodeUri  path aligns precisely with the artifacts specified in  buildspec.yaml .



🎯 Putting It All Together:

This robust SAM build and deployment setup allows seamless integration into your CI/CD workflow, ensuring consistent, automated deployments and rollbacks.
For a complete walk-through on the AWS CodePipeline automatic rollback integration, refer to my detailed blog:


🔖 Summary & Key Takeaways:
  • Clearly configure your build and deploy stages with  buildspec.yaml .
  • Use environment variables effectively for secure, maintainable pipelines.
  • Ensure precise artifact referencing to avoid deployment inconsistencies.
  • Automatically roll back to maintain application stability.
Now you're ready to build more resilient, serverless applications with AWS SAM and CodePipeline! 🚀


🎉 About the Author PBKN is a 12x AWS Certified (AWStronaut) & Official AWS SME & Community Builder
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article