Thursday, April 26, 2012

Resolve JIRA issue after Jenkins build using API

Jenkins and JIRA integration is quite poor - there are few plugins, but they are quite far from being practical. Even such simple action like issue transition after build is missing. It is generally possible by using smart comments, but they trigger on commit, not after successful build.
Fortunately, there is a lot of customization options for Jenkins, and Jira has great API.
So, to implement issue transition it is good to have Groovy plugin and Jira Issue Updater plugin (for Jira libs). Then it is needed to add new Build step - Execute system Groovy script; and add this simple Groovy script there:

import hudson.model.*
import com.atlassian.jira.rpc.soap.client.*

def thr = Thread.currentThread()
def build = thr?.executable

def rss = new XmlParser().parseText(  new File("${build.getEnvVars()['WORKSPACE']}/../builds/${build.getEnvVars()['BUILD_ID']}/changelog.xml").getText()  )
def ids = []
rss.logentry.each {
   def match =  it.msg.text() =~ /(\w+-\d+)/
   match.each {
       ids << it[0]

JiraSoapServiceServiceLocator jiraSoapServiceLocator = new JiraSoapServiceServiceLocator();
def jiraSoapService = jiraSoapServiceLocator.getJirasoapserviceV2(new URL(''));
String token = jiraSoapService.login('login', 'password');
def issues = jiraSoapService.getIssuesFromJqlSearch(token, "project=PROJECT1 and issuekey in (${ids.join(', ')})", 20)
String[] resolutions = ["23"]
for (RemoteIssue issue : issues) {
    def actions = jiraSoapService.getAvailableActions(token, issue.getKey() );
    for (RemoteNamedObject action : actions) {
         if (action.getName().equalsIgnoreCase('Resolve')) {
               RemoteFieldValue[] vals = [  new RemoteFieldValue("resolution", resolutions  )  ]
               jiraSoapService.progressWorkflowAction(token, issue.getKey(), action.getId(), vals );

This basically looks for all Jira IDs in commit comments, then queries specific project for all issues with these IDs and sets status to Resolved if it is applicable.
It is easy to customize this script to add special keys, like to ignore some commits or something.

1 comment:

  1. Good tip, but I have a problem When i try to run this example