Skip to content

Instantly share code, notes, and snippets.

@sgoger
Last active August 25, 2017 14:28
Show Gist options
  • Save sgoger/848fa7518daeaac7ae6bc055a5845d56 to your computer and use it in GitHub Desktop.
Save sgoger/848fa7518daeaac7ae6bc055a5845d56 to your computer and use it in GitHub Desktop.
Minimalistic shell deployment script
#!/bin/bash
############################################
################### USAGE ##################
############################################
# releaseWanted:
# amount of releases to keep on destination server
# 0 will keep them all
# destRootPath:
# path to project root on destination server
# fyi: a directory called "releases" will automatically be created in destRootPath
# user:
# ssh user to use
#
# Usage: deploy.sh IP[:PORT] [destinationPath]
# deploy.sh HOSTNAME[:PORT]" [destinationPath]
releasesWanted=3
destRootPath="/path/to/project"
user="sshUser"
############################################
####### DO NOT CHANGE ANYTHING BELOW #######
############################################
set -e
termcols=$(tput cols)
normal="$(tput sgr0)"
green="$(tput setaf 2)"
red="$(tput setaf 1)"
distantServer=$1
destRootPath=$2
releasesPath="$destRootPath/releases"
if [ -z $distantServer]; then
echo "${red}Missing destination host"
echo "Usage: deploy.sh IP[:PORT]"
echo " deploy.sh HOSTNAME[:PORT]"${normal}
exit 1
fi
now=$(date +'%Y%m%d%H%M%S')
# Starting deployment
echo "${green}# Starting deployment to $releasesPath/$now${normal}"
rsync --rsync-path="mkdir -p $releasesPath && rsync" -vFar --progress . $user@$distantServer:$releasesPath/$now
# Updating symlink
echo "${green}# Updating symlink${normal}"
ssh $user@$distantServer "ln -sfn $releasesPath/$now $destRootPath/current"
# Removing surplus releases
directoriesTotal=$(ssh $user@$distantServer "ls -l $releasesPath | grep -c ^d")
if [ $releasesWanted -gt 0 ] && [ "$directoriesTotal" -gt "$releasesWanted" ]; then
AmountOfDirectoriesToRemove=`expr $directoriesTotal - $releasesWanted`
echo "${green}# Removing $AmountOfDirectoriesToRemove legacy release(s)${normal}"
ssh $user@$distantServer "cd $releasesPath && ls -r |tail -n-$AmountOfDirectoriesToRemove |xargs rm -Rf"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment