Last active
May 24, 2016 17:29
-
-
Save twhid/ce14d9f25bca2fe37192bb820f7e6889 to your computer and use it in GitHub Desktop.
bash script to build docker images of node apps via jenkins jobs. Requires jq and the Jenkins GitHub plugin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# AWS domain | |
DOMAIN=${AWS_DOMAIN} | |
# Set CI_TEST to true to exit the script before build commences. | |
TEST=${CI_TEST:-'false'} | |
# Defaults for testing (variables supplied by Jenkins when in that environment). | |
GIT_URL=${GIT_URL:-"[email protected]:foo/foo-bar-baz-qux.git"} | |
BUILD_NUMBER=${BUILD_NUMBER:-456} | |
GIT_BRANCH=${GIT_BRANCH:-"origin/release"} | |
# GIT_BRANCH will be set to 'develop' if that string | |
# is at the end of GIT_BRANCH. | |
GIT_BRANCH=`echo ${GIT_BRANCH} | grep -o "develop$"` | |
# Get the version from package.json; requires "jq" to be installed. | |
VERSION=`cat ./package.json | jq -r ".version"`.${BUILD_NUMBER} | |
# Derive the IMAGE_NAME from GIT_URL env var supplied by Jenkins. | |
# NOTE: important to follow the convention: git repo name === image name | |
IMAGE_NAME=`echo ${GIT_URL} | grep -o "/.*\." | sed 's/^\/\(.*\).$/\1/'` | |
# Builds from develop branch are always "latest" tag. | |
# All other builds get the version number from package.json. | |
TAG=$([ "$GIT_BRANCH" == "develop" ] && echo "latest" || echo "$VERSION") | |
echo "Building image with tag: "${DOMAIN}/${IMAGE_NAME}:${TAG} | |
# Exit if testing. | |
[ "$TEST" == "true" ] && exit 0 | |
# login to AWS | |
$(aws ecr get-login --region us-east-1) | |
# do the build and push to AWS | |
docker build -t ${DOMAIN}/${IMAGE_NAME}:${TAG} . | |
# clean up "latest" tags | |
if [ "$TAG" == "latest" ]; then | |
echo "Removing from the registry: ${IMAGE_NAME}:${TAG}" | |
aws ecr batch-delete-image --repository-name ${IMAGE_NAME} --image-ids imageTag=${TAG} | |
fi | |
docker push ${DOMAIN}/${IMAGE_NAME}:${TAG} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment