Automatic Drupal Site Deployment with Git
Set up Git-based deployment to automatically deploy Drupal changes from local to remote server.
In this article I will show how to setup git and Drupal in such a way that you can keep editing your site’s modules, themes and libraries on your local machines and every time to do ‘git push’ it automatically deploys to your public Drupal site - without having to login into your webhosting provider and doing checkout/reset on your working tree.
Assumptions:
- You’re using Git for version control and Drupal for site hosting.
- You’re hosted in a place where you have ssh access and git installed on the server.
- You already know the basics of Git and Drupal.
Setup:
- Your site is example.com hosted on a remote server (Linux).
- Your Drupal site directory on the remote server is ~/drupal/sites/example.com.
- You have some modules/themes/libraries etc. in ~/drupal/sites/example.com.
Steps:
On remote server:
cd <drupal-root>/sites/example.com
git init
This turns your site-dir into a git repository and a git working directory (non-bare). Now on your local machine:
git clone [email protected]:~/drupal/sites/example.com
Make some code changes, commit locally, and then try to push.
... make changes ...
git commit -am'your commit message'
git push
Oops! Push is rejected, with a bad error message. That’s because a non-bare Git repository does not accept pushes automatically. To fix that do this on remote server:
cd ~/drupal/sites/example.com
git config receive.denyCurrentBranch ignore
Now push again. On local machine:
git push
It should work this time. Now your remote repository has your changes, but those changes are sitting in the repository database, not in the working directory. For automatic deployment, you need every push from local machine to also cause the server to update the working directory.
That is where Git hooks come in. One of the Git hooks is post-receive hook. It executes every time a push is accepted. On the remote server, put the following in ~/drupal/sites/example.com/.git/hooks/post-receive:
#!/bin/sh
cd ..
GIT_DIR='.git'
umask 002 && git reset --hard
export DRUSH_PHP=/usr/local/bin/php5
~/drush/drush cc all
That’s it. From here on, you can make changes to your local Git repository and every time you do git push, your changes are reflected in the live site (remote git repository).