Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Thursday, October 7, 2021

Building Docker Images Using CodeBuild


 


In the previous post, we have used the CloudFormation to create all the AWS entities required for our CodeBuild project.

Now, we can finally write the actual docker build code.

We'll start with the simplest form of buildspec.yaml, which run a shell file from the CodeCommit Git repository, which is great, since we can update the build without updating anything in AWS itself, but by simply updating the source in the Git.


buildspec.yaml

version: 0.2

phases:
build:
commands:
- ./build_image.sh



The build images shell file does the following:

  • Authenticate to the ECR
  • Pull the previous built docker image to enable using docker cache for the current build
  • Builds the current image
  • Push the image to the ECR


build_image.sh

#!/bin/bash

set -e

ecr=${awsAccount}.dkr.ecr.${awsRegion}.amazonaws.com
localTag=${imageName}:${imageVersion}
remoteTag=${ecr}/${imageName}:${imageVersion}


log(){
message=$@
NOW=$(date +"%m-%d-%Y %T")
echo "${NOW} ${message}"
}

build(){
log "Pull cached image"
set +e
docker pull ${remoteTag}
set -e

log "Build docker image"
docker build --cache-from ${remoteTag} --tag ${localTag} images/${imageName}
docker tag ${localTag} ${remoteTag}

log "Push image"
docker push ${remoteTag}
}

authenticate(){
log "Authenticate to docker"
aws ecr get-login-password --region ${awsRegion} | docker login --username AWS --password-stdin ${ecr}
}


log "Starting build of image ${remoteTag}"
authenticate
build
log "Done"



Final Note


There are other items to cover as part of AWS CodeBuild, such as build triggers, wrappers to run builds and more. I will cover these in future posts.



No comments:

Post a Comment