Jekyll + Github pages + Travis CI, sitting in a tree

I use Jekyll and Github Pages to host several sites. However because Github builds Jekyll projects using the --safe flag, you are restricted to only a handful of supported plugins.

I recently had the need to use additional custom plugins, which means I can no longer push my gh-pages branch to Github and let them do the rest. Instead I've used Travis CI to automate the build step and push the changes back into my remote repository. Here's how:

Firstly, keep using develop or master as your working branch. Travis will push the built site into gh-pages, so remove any existing files in that branch with a git rm *.

Add a .travis.yml file to the repository. I'm using the following:

# tell Travis to spin up a ruby 2.2.0 environment
language: ruby
rvm:
- 2.2

script:
- bundle exec jekyll build

# after building, copy the site into the gh-pages branch
# and push back to Github
after_success:
- git clone https://$GITHUB_REPO
- cd $(basename ${GITHUB_REPO%.git})
- git config user.name "Travis CI"
- git config user.email ${EMAIL}
- rsync -az --delete --exclude '.git*' ../_site/ .
- touch .nojekyll
- git add -A .
- git commit -m "Generated Jekyll site by Travis CI - ${TRAVIS_BUILD_NUMBER}"
- git push --force "https://${DEPLOY_KEY}@${GITHUB_REPO}" HEAD:${REPO_TARGET_BRANCH}

env:
  global:
  - NOKOGIRI_USE_SYSTEM_LIBRARIES=true
  - GITHUB_REPO: github.com/YOUR_USERNAME/YOUR_REPO_NAME.git
  - REPO_TARGET_BRANCH: gh-pages

Update GITHUB_REPO and REPO_TARGET_BRANCH to match your repository.

Before this will work, however, you need to allow Travis access to your repository. To do this:

  1. Create a new personal access token. Name is something memorable such as Deploy repo X with Travis.
  2. gem install travis on your machine.
  3. Encrypt your email address and access token, which will automatically add them as secret properties to the .travis.yml file:
# your Github verified email address
$ travis encrypt EMAIL=me@domain.com --add

# your personal access token
$ travis encrypt DEPLOY_KEY=token --add

Commit and deploy. Travis should pick up the commit, build your project, commit the files back into the gh-pages branch and Github will serve this at http://your_username.github.io/your_repo_name.

Magic.