Both problems (automatically handling your deployments and avoiding useless work, e.g. running a grunt
task if nothing changed) are what git
hooks are for.
So my advice would be to get rid of cron
tasks altogether and switch to managing your repositories via hooks as soon as possible.
The way this is usually done is described in detail here, and basically requires you to have a bare
repository (a hub repo) to push to/pull from and a checked-out version of the same repo (a live repo) located in the appropriate path, say /srv/www/html
, for example.
I like to use gitolite3
to handle the hub repo, but that is not a requirement, though it's rather convenient to have fine-grained access control bound to your LDAP of choice if needs be.
It is also a good practice to limit the capabilities of the gitolite3
user via sudo
, and handle the hooks by means of sudo
calls. This is a working example using gitolite3
hooks (feel free to adapt them -or enhance/fix them- to suit your needs):
hub repo post-update
hook:
#!/bin/sh
echo "****"
echo "**** Calling publisher-hub2live script [Hub's post-update hook]"
echo "****"
sudo /usr/local/sbin/publisher-hub2live "/srv/www/html" "root:apache" "2750" "640"
exit 0
publisher-hub2live
script:
#!/bin/sh
echo "****"
echo "**** Pulling changes into Live [publisher-hub2live]"
echo "****"
cd "$1" || exit
umask 0022
unset GIT_DIR
/usr/bin/git pull hub master
# custom actions here
# e.g call grunt tasks
/bin/chown -R "$2" "$1"
/bin/find "$1" -type d -exec chmod "$3" {} +
/bin/find "$1" -type f -exec chmod "$4" {} +
/bin/chmod u+x "$1"/.git/hooks/post-commit
/sbin/restorecon -R -v "$1"
exec /usr/bin/git update-server-info
exit 0
A live repo post-commit
hook can useful too, if you ever make changes in the checked-out working tree of the live repo and want to sync the hub.
This infrastructure requires the following entries (or equivalent ones) in your sudoers
file:
Cmnd_Alias GITOLITE_CMDS = /usr/bin/git, /bin/chown, /bin/find, /bin/chmod, /sbin/restorecon, /usr/local/sbin/publisher-hub2live
Defaults:gitolite3 !requiretty
Defaults:gitolite3 lecture=never
gitolite3 ALL = (root)NOPASSWD: GITOLITE_CMDS
Also, a Match
block in your sshd_config
would be useful, depending on how you manage identity in your machines:
Match Group gitolite3
Banner /etc/issue.empty
RequiredAuthentications2 publickey
With all this in place, pushing to the hub repo triggers the post-update
hook, ensuring that your custom actions are executed only when there's something new .