Skip to content

Instantly share code, notes, and snippets.

@stanleegoodspeed
Last active December 16, 2022 10:37
Show Gist options
  • Save stanleegoodspeed/f88dc7f10457a1627bfd45bca0486c43 to your computer and use it in GitHub Desktop.
Save stanleegoodspeed/f88dc7f10457a1627bfd45bca0486c43 to your computer and use it in GitHub Desktop.
script to build / tag / push / update docker swarm services that were changed since the last push
#! /bin/bash
# Only process first job in matrix (TRAVIS_JOB_NUMBER ends with ".1")
if [[ ! $TRAVIS_JOB_NUMBER =~ \.1$ ]]; then
echo "Skipping deploy since it's not the first job in matrix"
exit 0
fi
# Don't process pull requests
# $TRAVIS_PULL_REQUEST will be the PR number or "false" if not a PR
if [[ -n "$TRAVIS_PULL_REQUEST" ]] && [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then
echo "Skipping deploy because it's a pull request"
exit 0
fi
# Don't process non-deploy branches
if [[ $TRAVIS_BRANCH != 'master' && $TRAVIS_BRANCH != 'staging' ]]; then
echo "Skipping deploy because this is not a deployable branch"
exit 0
fi
### Get all the changes that were made since the last push
CHANGES=$(git diff --name-only $TRAVIS_COMMIT_RANGE)
### Set env vars for correct environment
if [ $TRAVIS_BRANCH == 'master' ]; then
MANAGER_IP=$PROD_IP
... set other environment vars
fi
if [ $TRAVIS_BRANCH == 'staging' ]; then
MANAGER_IP=$STAGING_IP
... set other environment vars
fi
### Loop through ./services directory and build/push/tag Docker images if changes were made
for service in $THE_SERVICE_LIST
do
echo 'Looking to see if '$service' was updated....'
[ "`grep $service <<< "$CHANGES"`" ] && ./build-tag-push.sh $service || echo "No change detected for this service"
done
### Substitue env vars into stack file
envsubst < ./docker-stack.yml > $TRAVIS_BRANCH-stack.yml
### Copy stack file to swarm manager
echo "Copying docker-stack to the swarm manager..."
scp -o StrictHostKeyChecking=no $TRAVIS_BRANCH'-stack.yml' docker@$MANAGER_IP:~/
### Deploy stack update on manager node
echo "Deploying stack to the swarm..."
ssh -o StrictHostKeyChecking=no docker@$MANAGER_IP 'docker login -u' $DOCKER_HUB_USERNAME '-p' $DOCKER_HUB_PASSWORD '&& docker stack deploy -c' $TRAVIS_BRANCH'-stack.yml mystack --with-registry-auth --resolve-image always'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment