Promoting builds with Artifactory and Jenkins

24 June 2014

We wanted to provide a facility to allow a person to promote a specific build artefact to a release artefact. We use Artifactory to upload and store all our build artefacts from jenkins. These artefacts currently expire after 7 days since they are transient in nature and stored in their own repository.

We used the Groovy plugin to execute some groovy (system script) to perform this change as a build step. The general gist of the script was to download a zip from a sourceUrl and upload using the Http PUT verb to the targetUrl.

The code below is imperfect but should be enough to get you going.

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.http.entity.FileEntity;
import org.apache.commons.httpclient.methods.FileRequestEntity;
import hudson.model.*

def version = build.buildVariableResolver.resolve("PUBLISHED_VERSION")
def name = build.buildVariableResolver.resolve("NAME")
def buildNo = build.buildVariableResolver.resolve("PARENT_BUILD_NUMBER")

def sourceUrl = "http://artifactory:8080/transient/builds/jenkins-$name-${buildNo}/${name}.zip";
def targetUrl = "http://artifactory:8080/ext-release-local/company/$name/${version}/$name-${version}.zip";

println 'BuildNo:' + buildNo;
println 'Version:' + version;
println 'sourceUrl' + sourceUrl;
println 'targetUrl' + targetUrl;
println 'Will copy artifact to ' + targetUrl;

creds = new UsernamePasswordCredentials("username", "password");
client = new HttpClient()
client.getState().setCredentials(new AuthScope("artifactory", 8080, AuthScope.ANY_REALM), creds)

// download the file
file = File.createTempFile("publishing_artifact", "tmp")
get = new GetMethod(sourceUrl)
input = get.getResponseBodyAsStream()
fout = new FileOutputStream(file)
b = new byte[65536];
len = 0;
while ((len = != -1) {
  fout.write(b, 0, len);

// upload file
println 'Got file';

client = new HttpClient()
client.getState().setCredentials(new AuthScope("artifactory", 8080, AuthScope.ANY_REALM), creds)
put = new PutMethod(targetUrl)
entity = new FileRequestEntity(file, "binary/octet-stream");

println put.getResponseBodyAsString().toString()

try {
}catch(Exception e) {}
CI Jenkins-CI