Wednesday, February 23, 2011

Deploy only tested code with Jenkins and Ruby

Moved here

Deploying software builds that don't pass the unit tests is a waste of time. It prevents QA from doing their job, it causes delays while a fixed build is prepared, and it could even lead to more ops time to fix if the broken build breaks something on the machines it's being deployed to. If you use Jenkins to run your tests, there's a better way. Using the Jenkins API, we can get the last revision that passed for a project, and adjust our behavior based on that revision number.

Jenkins.rb is a Ruby wrapper for the Jenkins API. gem install jenkins.rb should give you everything you need. Then, you can whip up a quick ruby script:

require 'jenkins'
require 'fileutils'

Jenkins::Api.setup_base_url(:host => 'jenkins-host.example.com')

# Pull the project name from the command line
project = ARGV[0]

# Retrieve the last successful build number (123, for example)
successful_build = Jenkins::Api.job(project)["lastSuccessfulBuild"]["number"]

# Retrieve information about the actual build, and grab the last built revision out of it
build_info = Jenkins::Api.get("/job/#{project}/#{successful_build}/api/json")
sha = build_info['actions'].detect {|h| h["lastBuiltRevision"] }["lastBuiltRevision"]["SHA1"]
puts sha

When this script is run with ruby script.rb project-name, it'll return the most recent revision of project-name that passed all the tests, which the build script can use by calling git reset --hard number or something else like that.

No comments: