Simple deploy from git on a web server that has ssh access

Tags : Git

tl;dr

A friend of mine asked me for help with deploying a git repo to their web server, this post explains my solution.

Rationale

I didn’t want to spend too much time playing with services like https://codeship.com/ As they had ssh access to the server, and git installed - I figured a script would be the easiest way to go.

Approach

I’ve used python fabric for ci deploys before, but that seemed a tad excessive so I decided to use a bash script.

First, authenticate git by following the instructions here: https://help.github.com/articles/generating-ssh-keys/

Then make a note of directories

Git repo structure:

 
Stuff
other stuff
public_html
random file
readme.md

Location of existing web root: ~/public_html

Aim of the script

  • Clone git repo to folder
  • create a symbolic link to the public_html directory in the git repo from the web root

I figured version control would be useful too – every time we clone, we want to it to a timestamp directory. We could use git releases here and checkout the corresponding tags, but that was out of scope for this task.

Problems encountered

Bash didn’t know what the command ‘git’ was. This is fixed by adding to the path variable. Which git or type –p git should give you the location.

 
PATH=$PATH:/usr/bin/

The authentication to git was reset, so I added

 
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/git_rsa

A note on permissions

Web servers should have 755 on folders and 644 on directories, this is easily fixed with chmod and find.

 
#Find and change recursively on directories
find $deployFolder -type d -exec chmod 755 {} +
 
#Find and change recursively on files
find $deployFolder -type f -exec chmod 644 {} +

If you’re hosting provider doesn’t like symbolic links, then use the following instead

 
rm -r $webRoot/*
cp -R $deployFolder/public_html $webRoot/.

The Resulting Script

We’re all set to run

 
sh deploy.sh

To rollback:

 
ln -sfn webDeploys/WORKINGTIMESTAMP/public_html/ /home/user/public_html 

Done - in about 10 minutes too.