In my previous post, I described a technique for putting your Jenkins server configuration under version control. It’s a great way to ensure that your changes are always tracked and that you can recover if/when things get out of whack. However, if it requires you to regularly log onto the Jenkins box and manually run a bunch of git commands, you are likely to either forget or simply never get around to capturing the ever-changing configuration updates. The natural extension of this is to set Jenkins up to handle things automatically.

There are two jobs I usually create to handle this:

  • GitStatus – run Git status in the .jenkins directory to see what has changed. I even tacked on ‘git diff’ to the end of the job so I could see the specifics.
  • GitCommit – run the commits. I take a “COMMENT” parameter for the job so that I can record a message about what I changed.

GitStatus Job

The “Status” job is really just a utility that helps you look at changes that have been made on the server. Create a simple job called “GitStatus” with no parameters. Then, add a shell block:

#!/bin/bash

# terminate on error
set -e

cd $JENKINS_HOME

echo "Checking status of $JENKINS_HOME"
git status

echo "##################################################"

echo "Recent changes:"
git log -10 --stat

Then, just run it whenever you want to see what has changed.

GitCommit Job

For the “Commit” job, I usually add a “COMMENT” string parameter.

  • Name: GIT_COMMENT
  • Default: Auto-commit from DevOps Demo Jenkins
  • Description: The “-m” comment that Git will use during commit of any changes. Set it to a custom comment if you manually commit and want to have a unique entry in the git log.

Then, set up a build trigger to run on a regular interval. In my case, I set it up to run nightly some time between midnight and 8 AM:

H H(0-7) * * *

The heavy lifting is done with a script block:

#!/bin/bash
# terminate on error
set -e

cd $JENKINS_HOME
echo "Recent changes:"
git log -5 --pretty=oneline --stat

echo "Checking status of $JENKINS_HOME"
git status

echo "Adding new files..."
git add .

echo "Git status:"
git status

echo "Committing changes..."
# Only try commit if something changed, otherwise this produces an error.
git diff-index --quiet HEAD || git commit -m "$GIT_COMMENT"

# Push changes upstream
git push

And that’s it. Your “commit” job will start running daily to capture all of the changes on your Jenkins server.

Leave a comment

Your email address will not be published. Required fields are marked *

X