Skip to content

Instantly share code, notes, and snippets.

@jsonmaur jsonmaur/deploy.sh
Created Oct 16, 2016

Embed
What would you like to do?
Deploy new image to ECS service with CircleCI
#!/usr/bin/env bash
DIR="$(dirname "$( cd $(dirname $0) ; pwd -P )")"
JQ="jq -Merc"
ORG_NAME="zablabs"
COMMIT=${CIRCLE_SHA1:-$(git rev-parse HEAD~0)}
NAME=$1
ENV=$2
PROFILE_NAME=$3
if [[ ! -z $PROFILE_NAME ]]; then
PROFILE="--profile $PROFILE_NAME"
fi
if [[ -z $PROFILE ]]; then
aws configure set default.region $AWS_REGION
aws configure set default.output json
fi
function if_failed {
if [ $? == 1 ]; then
echo "FAILED: $1"
exit 1
fi
}
if [[ -z $(git diff --name-only HEAD~0 HEAD~1 | grep "^$NAME\/") ]]; then
echo "No changes found for this service."
exit 0
fi
cd $DIR/$NAME
echo "Building and pushing $ORG_NAME/$NAME..."
docker build --rm=false \
-t $ORG_NAME/$NAME:$COMMIT \
-t $ORG_NAME/$NAME:$ENV .
docker push $ORG_NAME/$NAME:$COMMIT
docker push $ORG_NAME/$NAME:$ENV
echo "Getting cluster name..."
CLUSTER=$(aws ecs list-clusters $PROFILE \
| $JQ ".clusterArns[] | select(contains(\"zab-cluster-$ENV\"))" \
| sed "s/.*:cluster\/\(.*\)$/\1/")
if_failed "Could not get cluster name!"
# TODO: Sometimes this seems to get outdated tasks
echo "Updating service for $CLUSTER..."
FAMILY=$(aws ecs list-task-definition-families $PROFILE \
--family-prefix zab-$NAME-$ENV \
--status ACTIVE \
| $JQ ".families[0]")
if_failed "Could not get task family name!"
TEMP_FILE=$(mktemp)
trap "rm -f $TEMP_FILE" 0 2 3 15
echo "Modifying current task..."
aws ecs describe-task-definition $PROFILE \
--task-definition $FAMILY \
| sed "s/\(\"image\": \"$ORG_NAME\/$NAME:\).*\(\"\)/\1$COMMIT\2/" \
| $JQ ".taskDefinition.containerDefinitions" > $TEMP_FILE
if_failed "Could not get current task!"
echo "Creating task revision for $FAMILY..."
REVISION_NUMBER=$(aws ecs register-task-definition $PROFILE \
--family $FAMILY \
--container-definitions file://$TEMP_FILE \
| $JQ ".taskDefinition.taskDefinitionArn" \
| sed "s/.*:\(.*\)$/\1/")
if_failed "Could not create task revision!"
if ! [[ "$REVISION_NUMBER" =~ ^[0-9]+$ ]]; then
echo "Invalid task revision number: $REVISION_NUMBER"
exit 1
fi
echo "Getting service name..."
SERVICE=$(aws ecs list-services $PROFILE \
--cluster $CLUSTER \
| $JQ ".serviceArns[] | select(contains(\"zab-$NAME-$ENV\"))" \
| sed "s/.*:service\/\(.*\)/\1/")
if_failed "Could not get service name!"
echo "Updating $SERVICE with task revision #$REVISION_NUMBER..."
RESULT=$(aws ecs update-service $PROFILE \
--service $SERVICE \
--cluster $CLUSTER \
--task-definition $FAMILY:$REVISION_NUMBER)
if_failed "Could not update service!"
echo "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.