Auto Deploy Your Code With Git!

On an assignment recently, I worked with a dev-ops team that refused to have anything to do with FTP, and rightly so..it can be a very inefficient and insecure way to transfer files.

When I asked “well, how do I get the code to the server then?” I was told it was all done behind the scenes when I commit to git. I was intrigued and wanted to do that for my personal projects …and this is how I did it.

First I log into my production server (really, this can be set up for any type of server), and create a folder outside of where the public folder lives that will be our target for commits. We create a ‘bare’ repository

git init --bare ~/project.git

Then create the script to be executed when it receives a commit..this is called a ‘hook’
and will live here: project.git/hooks/

#!/bin/bash
TRAGET="/home/webuser/deploy-folder"
GIT_DIR="/home/webuser/www.git"
BRANCH="master"

while read oldrev newrev ref
do
	# only checking out the master (or whatever branch you would like to deploy)
	if [[ $ref = refs/heads/$BRANCH ]];
	then
		echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
		git --work-tree=$TRAGET --git-dir=$GIT_DIR checkout -f
	else
		echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
	fi
done

Now we’re ready to set up things locally where our code is:

$ cd ~/path/to/working-copy/
$ git remote add production demo@yourserver.com:project.git

Now all that’s left to do is to deploy that wonderful code..and profit!

$ git push production master

Less time moving files = more time developing new features!