Skip to content

Instantly share code, notes, and snippets.

@maximeaubaret
Last active November 27, 2018 18:03
Show Gist options
  • Select an option

  • Save maximeaubaret/39e6a2cb4c688aa5273baeb40e5842c8 to your computer and use it in GitHub Desktop.

Select an option

Save maximeaubaret/39e6a2cb4c688aa5273baeb40e5842c8 to your computer and use it in GitHub Desktop.
Simple AWS CodeBuild Build script for Docker with caching
#!/bin/sh
readonly REPO=${REGISTRY}/${REPO_NAME}
# Figure out which REF_NAME to use
if [[ -z "${REF_NAME}" ]]; then
if [[ -z "${CODEBUILD_WEBHOOK_TRIGGER}" ]]; then
echo "If building manually, you must specify a REF_NAME environment variable."
exit 1
fi
case "$CODEBUILD_WEBHOOK_TRIGGER" in
"branch/master") REF_NAME="latest";;
"branch/develop") REF_NAME="staging";;
*) REF_NAME=$(echo $CODEBUILD_WEBHOOK_TRIGGER | tr "/: " -);;
esac
fi
echo "-----------------"
echo " Image name:"
echo " $REPO"
echo " Tag:"
echo " $REF_NAME"
echo "-----------------"
# Are we using the ECR Registry or another registry?
if [[ -z "${REGISTRY_NOT_ECR}" ]]; then
echo "Login to AWS ECR..."
$(aws ecr get-login --no-include-email)
else
if [[ -z "${REGISTRY_USERNAME}" || -z "${REGISTRY_PASSWORD}" ]]; then
echo "If using a custom registry, you need to set REGISTRY_USERNAME and REGISTRY_PASSWORD."
exit 1
fi
echo "Login to Registry..."
docker login -u $REGISTRY_USERNAME $REGISTRY -p $REGISTRY_PASSWORD
fi
echo "Try pulling the latest docker image of $REPO:$REF_NAME..."
if docker pull $REPO:$REF_NAME; then
CACHE_REF=$REF_NAME
echo "Success!"
else
CACHE_REF=latest
echo "This did not work. Fallback to latest."
docker pull $REPO:latest
fi
echo "Build the image..."
docker build --cache-from $REPO:$CACHE_REF --tag $REPO:$REF_NAME --tag $REPO:ref-$CODEBUILD_RESOLVED_SOURCE_VERSION .
echo "Push the image $REPO:$REF_NAME to the registry..."
docker push $REPO:$REF_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment