Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Created May 9, 2020 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjarrett/59b4655be322c3b6a217ef53212bc3cf to your computer and use it in GitHub Desktop.
Save fjarrett/59b4655be322c3b6a217ef53212bc3cf to your computer and use it in GitHub Desktop.
Just an idea for a "Capistrano style" deploy setup
#!/usr/bin/env bash
# BASE (required) - Releases are stored here.
# TARGET (required) - This will be a symlink to the current release.
# REPO (required) - The address to your Git repo.
# KEEP - How many latest releases to keep around (default is 10).
#
# Example:
#
# BASE=/var/www/foo/releases TARGET=/var/www/foo/public_html REPO=git@github.com:foo/bar.git ./atomic_deploy.sh 2b5d4a
set -ex
if [[ $(id -u) > 0 ]]; then
echo -e "\e[101m\e[1m This script must be run as root or sudo! \e[0m\e[49m"
exit 1
fi
COMMIT_HASH=${1-master}
THIS_RELEASE="$BASE/$COMMIT_HASH"
# already the current release - do nothing
if [ "$(readlink -- "$TARGET")" = $THIS_RELEASE ]; then
echo -e "\e[106m\e[30m\e[1m $COMMIT_HASH is already the current release! \e[0m\e[39m\e[49m"
exit 0
fi
# ensure we have target dirs
mkdir -p $BASE
chown -R apache:apache $BASE
# skip if we already have this release on hand
if [ ! -d $THIS_RELEASE ] || [ ! "$(ls -A $THIS_RELEASE)" ]; then
if [ -d $BASE/.cache ]; then
# use a cached repo if we have it
echo -e "\e[107m\e[30m\e[1m Using cached repo... \e[0m\e[39m\e[49m"
cp -a $BASE/.cache $THIS_RELEASE
cd $THIS_RELEASE
su -s /bin/bash apache -c "git fetch --all && git reset --hard origin/master"
else
# otherwise create one from scratch
rm -f $THIS_RELEASE
mkdir -p $THIS_RELEASE
chown -R apache:apache $THIS_RELEASE
# clone as apache
su -s /bin/bash apache -c "git clone $REPO $THIS_RELEASE"
fi
# checkout the target commit
cd $THIS_RELEASE
git checkout $COMMIT_HASH
# update the cached copy of this repo
cp -a $THIS_RELEASE $BASE/.cache
# EVERYTHING STOPS HERE IF THE TESTS FAIL
# remove distignore files
cat .distignore | xargs rm -rf | bash
rm -f .distignore
else
echo -e "\e[107m\e[30m\e[1m Release already exists, rolling back... \e[0m\e[39m\e[49m"
fi
# release via symlink and atomic move "Capistrano style"
ln -s $THIS_RELEASE $BASE/current
chown -R apache:apache $BASE/current
mv -f $BASE/current $TARGET
# keep the 10 most recent releases, trim the rest
cd $BASE
ls -dtr */ | head -n -10 | xargs --no-run-if-empty rm -rf
# done
echo -e "\e[102m\e[30m\e[1m $COMMIT_HASH DEPLOYED \e[0m\e[39m\e[49m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment