Skip to content

Instantly share code, notes, and snippets.

@CitizenOfRome
Last active November 28, 2017 08:03
Show Gist options
  • Save CitizenOfRome/8dbe4096e827a2cce22fe5ae1f933d93 to your computer and use it in GitHub Desktop.
Save CitizenOfRome/8dbe4096e827a2cce22fe5ae1f933d93 to your computer and use it in GitHub Desktop.
Easily deploy to your server via SSH and GIT with a single BASH file

Easily deploy to your server via SSH and GIT with a single BASH file

Setup

  1. Have 2 git repositories - one for your code and a seperate one for deploying to your server in directories named main_repo_dir and deployment_repo_dir respectively, sharing a common parent folder

    Directory structure:

     -- .
       -- main_repo_dir
       -- deployment_repo_dir
         -- easy_git_and_ssh_based_deployer.sh
    
  2. Setup your target server to be able to pull the deployment repo

  3. Kindly skim through the easy_git_and_ssh_based_deployer.sh file - it can be further customized to suit your specific project

#!/bin/bash
cd "`dirname $0`"
# The commit/deployment message
MESSAGE='Uh...'
[ -n "${1}" ] && MESSAGE=${1}
# ----- Part 1 - Prep the source/main repo -----
cd ../main_repo_dir
# Here you can also run grunt/gulp, etc to prep for deployment
# Commit, Pull & Push any changes
git add . -A
git commit -am "$MESSAGE"
git pull
git push
# ----- Part 2 - Update the deployment repo -----
# Create an archive with all the changed files - https://git-scm.com/docs/git-diff#git-diff---diff-filterACDMRTUXB82308203
git archive --format=zip HEAD `git diff --name-only HEAD~1 HEAD --no-renames --diff-filter=AMCBTXU` > ../rangergo-backend-deploy/update.zip
# Create a text file containing all the delted file names
git diff --name-only HEAD~1 HEAD --no-renames --diff-filter=D > ../rangergo-backend-deploy/deleted.log
cd ../deployment_repo_dir
# Delete the files deleted in the original repo - https://stackoverflow.com/a/10150682/937891
xargs -a deleted.log -d'\n' rm
# Create a temporary directory for extracting and then copying files from the source repo
mkdir easy_git_and_ssh_based_deployer_tmp && cd easy_git_and_ssh_based_deployer_tmp
unzip -o ../update.zip
cd ..
cp -rf ./easy_git_and_ssh_based_deployer_tmp/* ./ # Here you may instead selectively copy dist or deployment specific folders
# Clean up
rm -rf ./easy_git_and_ssh_based_deployer_tmp
rm update.zip
rm deleted.log
# Commit and push the deployment repo
git add . -A
git commit -am "$MESSAGE"
git pull
git push
# ----- Part 3 - Deploy to the server -----
# Login via SSH and pull the updated repo on the server
ssh user@my_server_to_deploy.io <<'ENDSSH'
#commands to run on remote host
cd /var/www/my_server_dir
git pull
# php artisan migrate --force # Can do stuff like migrating if laravel, etc
ENDSSH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment