Trigger jenkins deployment from github push with ansible

We are looking at a simple and robust way to automate deployment. The following show some of the non-intuitive things necessary to set this up.

Jenkins

  • I recommend using the github oauth plugin for authentication and of course the github plugin to easily clone github repos.
  • use https://wiki.jenkins-ci.org/display/JENKINS/Build+Token+Root+Plugin – because the default endpoint to trigger builds cannot be accessed by anonymous users
  • Do not allow job names with spaces: In the jenkins global settings look for Restrict project naming and enter \S*
  • Set up a jenkins job for the repository that contains your ansible deploy script
  • Set up jenkins like this with the following Dockerfile
FROM jenkins
# if we want to install via apt
USER root
# stuff required by jenkins jobs, inlcuding ansible
RUN apt-get update && apt-get install -y php5-cli php5-curl python-setuptools python-dev build-essential libssl-dev libffi-dev

RUN easy_install pip
RUN pip install virtualenv

USER jenkins

Ansible

This script bootstraps ansible

#!/bin/bash

# exit the bash script if one of the command returns an error code
set -e

# Setup a proper path, I call my virtualenv dir "venv" and
# I've got the virtualenv command installed in /usr/local/bin

echo "setting path variable"
PATH=$WORKSPACE/venv/bin:/usr/local/bin:$PATH

echo "create virtualenv"
if [ ! -d "venv" ]; then
    virtualenv venv
fi

echo "activate virtualenv"
source venv/bin/activate

echo "installing ansible"
pip install ansible boto httplib2

echo "tossing in some secrets"
# use the secret file function in jenkins to fill in these variables
mkdir credentials
echo "move $all_yml, $deploy_key_pem and $server_stage_pem to $(pwd)/credentials"
mv "$all_yml" credentials/
mv "$deploy_key_pem" credentials/
mv "$server_stage_pem" credentials/

chmod 600 -R credentials/*

# if ansible roles are pulled in from other git repos:
git submodule update --recursive

echo "deploying"
./deploy stage 3-deploy-site.yml

Github

  • Set up a webhook. Example: http://jenkins.what.digital/buildByToken/build?job=Job-Name&token=2093....234