Webhook receives data from Jenkins

From Planfix
Jump to: navigation, search

In a large team collaborating on a project, it is sometimes helpful to know whether a new update in the project is ready for work. Such a notification as a comment can be sent to the developers in the corresponding Planfix task when the new improvements are ready. This functionality can be implemented using Jenkins and incoming webhooks.

How to do it

  • Create commits of this type: 123456 - commit text, where 123456 is the task number in Planfix.
  • Create a webhook to receive commits.
  • Add code in Jenkins Pipeline that sends data to the webhook.

Webhook setup

0Zvave.jpg

Code in Jenkins

Two auxiliary functions:

@NonCPS
def getTaskNumber(text) {
   def m = (text =~ /\d+/);
   def taskNumber = m ? m[0] : "";
   return taskNumber
}


@NonCPS
def getChangesByTaskNumber() {
   def changes = [:]
   def maxMessages = 50;

   def changeLogSets = currentBuild.changeSets

   for (int i = 0; i < changeLogSets.size(); i++) {
       def entries = changeLogSets[i].items
       for (int j = 0; j < entries.length && i + j < maxMessages; j++) {
           def entry = entries[j]
           def taskNumber = getTaskNumber(entry.msg);
           if(taskNumber != "") {
               if(!changes.containsKey(taskNumber)) {
                   changes[taskNumber] = "";
               }
               changes[taskNumber] += entry.msg + "<br>"
           }
       }
   }

   return changes
}


Code for insertion after operations have been completed:

def deployedTasks = getChangesByTaskNumber()
deployedTasks.eachWithIndex { key, value, i -> 
    httpRequest contentType: "APPLICATION_JSON_UTF8", httpMode: "POST", requestBody: "{ \"task\" : ${key}, \"comment\" : \"${value.replaceAll('"','\\\\"')}\", \"project\" : \"project-name\", \"branch\" : \"${env.gitlabBranch}\"}", responseHandle: "NONE", url: "https://myacc.planfix.ru/webhook/json/b7mh-dead-687f-lpwq";, consoleLogResponseBody: true
}


Final result

The developer will see a similar comment in the task:

E6hGY1.jpg


Go To