Thursday, August 10, 2017

Local docker deployment update with AWS CodeBuild

#!/usr/bin/env bash

# Prerequisites
# $WORKDIR/.env - environment variables
# awscli installed virtualenv env dir in $WORKDIR

set -e

WORKDIR=
PROJECT=project name
DOCKER_REPO=codebuild docker image
REPO_TAG=latest

cd $WORKDIR

while [[ $# -gt 0 ]]
do
key="$1"
case $key in
    -h|--help)
    echo '  -s|--skip-build - skip building image'
    exit 0
    ;;
    -s|--skip-build)
    SKIP_BUILD=yes
    ;;
    *)
    echo "Unknown option $2."
    exit 2
    ;;
esac
shift
done

print() {
    echo -e "\033[0;33m$1\033[0m"
}

if [ -z "$SKIP_BUILD" ]
then
    print 'Starting build'
    ARN=$(env/bin/aws codebuild start-build --project-name $PROJECT | python -c 'import json,sys;print(json.load(sys.stdin))["build"]["arn"]')
    print "Build started (ARN $ARN)"
    print "Waiting 3m"

    secs=180
    while [ $secs -gt 0 ]; do
        echo -ne "Time remaining: ${secs}s...\033[0K\r"
        sleep 1
        : $((secs--))
    done
    echo -ne '\033[0K\r'

    print "Checking if it's ready."
    while [ $(env/bin/aws codebuild batch-get-builds --ids "$ARN" | python -c 'import json,sys;print(json.load(sys.stdin))["builds"][0]["buildComplete"]') != 'True' ]
    do
        echo "...not ready yet. Waiting 5s."
        sleep 5s
    done
    print "Build's ready. Update docker container."
else
    print "Using existing build."
fi

sudo $(env/bin/aws ecr get-login --no-include-email --region us-east-1)
sudo docker pull $DOCKER_REPO:$REPO_TAG
sudo docker tag $DOCKER_REPO $PROJECT
sudo docker rm -f $PROJECT
sudo docker run -d --restart=always --env-file $WORKDIR/.env -p 8001:8000 --name=$PROJECT $PROJECT

print "Update finished."

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.