Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Current »

Below are some sample Webhook Listener use cases and how to implement them.

The Default Listener (POST Webhook)

When creating a new Listener, the script will default to the below which simply forwards the payload via a REST Post request. This script emulates an outbound webhook in the truest sense since no payload modification or logic is done. Simply update the postUrl variable with your endpoint and its ready to go.

//Carry out any custom action you wish for this event. Check out the documentation for reference or ideas.
//Optionally filter out events you dont want to execute by returning false on the filter script tab.
def listenerName = "myListener";
LOG.info("Running listener: ${listenerName}");

def postUrl = "";
def responseCode = REST.forward(postUrl,EVENT);

LOG.setMessage("Message forwarded (${responseCode}) to ${postUrl}");

End Release After Snapshot Deploys to Production

Note that this function may no longer needed as Release Settings incorporate this functionality.

To take advantage of ending a release after a pipeline execution completes you can create a new listener and select the Pipeline Stage Completed. You will then need to check whether the completed stage is the final stage in the pipeline. You can do this in a number of ways. One way is shown below by checking the environment code and comparing it to our final PROD stage.

Example Groovy Code

//Carry out any custom action you wish for this event. Check out the documentation for reference or ideas.
//Optionally filter out events you dont want to execute by returning false on the filter script tab.
def listenerName = "endReleaseListener";
LOG.info("Running listener: ${listenerName}");
         
if(EVENT.payload.environment.environmentCode.equals("PROD")){
     LOG.setMessage("Release ${EVENT.payload.release.releaseName} has completed moving through the pipeline. Ending release.");
     FLEXDEPLOY.forceEndRelease(EVENT.payload.release.releaseId);
}

Another way to take advantage of this is to use the Webhook Listener’s filter. This filter is also groovy script where you can determine whether the event should be processed by the Listener. In this example, we will filter the events so that only pipeline stage completed events that have completed the Prod stage in the pipeline are allowed through.

Logically, both approaches will accomplish the same task, however, using the Filter will automatically hide it from the Outgoing Webhook Messages display. This will reduce some of the noise and allow you to easily find the messages you care about.

Pipeline Stage Completed Filter

if(!EVENT.payload.environment.environmentCode.equals("PROD")){
  return false;
}else{
  return true;
}

Send a Slack Notification After Approval Task Is Created

This will send a notification to the specified slack channel when an approval task is created. To implement this you will simply need to set up your Slack Messaging Account and add a short script to your listener. In this example we are filtering for APPROVAL tasks only.

For a more comprehensive overview of how you can integrate Slack with your FlexDeploy Approval process check out this blog

TaskCreated Script

//Carry out any custom action you wish for this event. Check out the snippets for reference or ideas.
def listenerName = "TaskCreated";
LOG.info("Running listener: ${listenerName}");

def channel = 'testing';

//Slack account code defined in Configuration->Integration->Messaging
def account = 'SLACK';

//Create and post a FlexDeploy Slack Message object with interactive buttons to approve/reject
def message = SLACK.makeTaskCreatedMessage(EVENT.payload,true);
def tsId = SLACK.postMessage(account,channel,message);

LOG.setMessage("Posted task ${EVENT.payload.taskId} to Slack");

TaskCreated Filter

return EVENT.payload.taskType == "APPROVAL";

Attach Failed Plugin Logs to Jira Issue

One of the bigger use cases of the Workflow Completed event is to send the logs to another application. In this particular example we are uploading the logs to the Jira Issue associated to the project. We also have a filter setup to only execute this listener for workflows with a ‘FAILURE’ status and when the Workflow Execution has Jira Issues associated.

This script uses FLEXDEPLOY.getIntegrationInstance to get a configured Jira instance within FlexDeploy. This is a great alternative to putting a plain text password in the script

Upload Logs Jira Listener Script

import flexagon.ff.common.core.exceptions.FlexCheckedException;

//Carry out any custom action you wish for this event. Check out the snippets for reference or ideas.
def listenerName = "Add logs to Jira";
LOG.info("Running listener: ${listenerName}");

//Prior to 5.4.0.1 this function only returned a list of input streams. Update accordingly
//The second argument specifies we only want the error streams returned.
def streams = FLEXDEPLOY.getPluginLogInputStreams(EVENT.payload.workflowExecutionId, true);

//upfront validation on streams
if(!streams || streams.size() == 0) {
  LOG.setMessage("Received failure event but couldn't find any plugin log streams");
  return;
}

//We should only ever have one errored plugin execution, so grab first entry.
def failedPlugin = streams.entrySet().iterator().next();

def properties = getJiraProperties('JIRA');

LOG.info("${EVENT.payload.issueNumbers}");

for(def issue: EVENT.payload.issueNumbers) {
  LOG.info("Upload logs to issue: ${issue}");
  
  //create our form data body
  failedPlugin.getValue().reset();
  def body = REST.getClient().createFormDataWithInputStream(['file': failedPlugin.getValue()], "${failedPlugin.getKey()}.txt");
  
  //send request
  def client = REST.getClient().url(properties.url).addHeader('X-Atlassian-Token', 'no-check').basicauth(properties.user,properties.password);
  def response = client.path("/rest/api/2/issue/${issue}/attachments").post(body);
  LOG.setMessage("Uploaded logs to ${issue}. Response: ${response.getResponseCode()}");
}

//helper function to get jira properties from integration instance
def getJiraProperties(String code) {
  def instance = FLEXDEPLOY.findIntegrationInstance(code,'ITS');
  def properties = instance.getProperties();
  def url = properties.find { it.getPropertyName() == 'JIRA_URL' }.getPropertyValue();
  def user = properties.find { it.getPropertyName() == 'JIRA_USER_NAME' }.getPropertyValue();
  def password = properties.find { it.getPropertyName() == 'JIRA_PASSWORD' }.getPropertyValue();
  return ['url':url, 'user': user, 'password': password];
}

The next step is to set up our filter to only process failed workflow completed events with Jira issue numbers.

Workflow Completed Filter

return "FAILURE".equals(EVENT.payload.executionStatus) && EVENT.payload.issueNumbers.size() > 0;

Create ServiceNow Incident on Workflow Failure

In the below example we make use of the ChangeManagementSystemService to allow us to create an incident through FlexDeploy’s internal ServiceNow integration. The only thing that needs to be configured ahead of time is your ServiceNow instance in Configuration->Integrations->Change Management

Create Incident Script

//Carry out any custom action you wish for this event. Check out the documentation for reference or ideas.
//Optionally filter out events you dont want to execute by returning false on the filter script tab.
def listenerName = "Create Incident";
LOG.info("Running listener: ${listenerName}");

def cmsFields = [:];
cmsFields.short_description = "Deployment failed for ${EVENT.payload.project.projectName}";
cmsFields.description = "Deployment failed for ${EVENT.payload.project.projectName}. Environment ${EVENT.payload.environment.environmentName} executionid ${EVENT.payload.workflowExecutionId} requestor ${EVENT.payload.updatedBy}";
 
LOG.fine("Creating Service Now Incident ${cmsFields}");

def cmsObject = FLEXDEPLOY.createIncidentForWorklowRequest(EVENT.payload.workflowRequest.workflowRequestId, cmsFields, "SERVICENOW",null);
LOG.setMessage("Successfully created Service Now Incident ${cmsObject.getNumber()}");

Configured offscreen is a Filter script for only failed workflows.

Send Test Results to Teams

The Workflow Completed Event includes all of the test execution data for any TEST workflow type. The below example shows how this data can be used by sending a Teams message with the data neatly formatted in an html table.

Tests Completed Script

//Carry out any custom action you wish for this event. Check out the documentation for reference or ideas.
//Optionally filter out events you dont want to execute by returning false on the filter script tab.
def listenerName = "Tests Completed";
LOG.info("Running listener: ${listenerName}");

def builder = new StringBuilder();
builder.append("<h1 style=\"padding: 10px 0\">Tests ${EVENT.payload.testRun.runStatus} for ${getProjectLink(EVENT.payload.project.projectName, EVENT.payload.project.projectId)} in ${EVENT.payload.environment.environmentName}</h1>");

builder.append("<table><tr><th style=\"padding: 0 10px 5px 0\">Test Def Name</th><th style=\"padding: 0 10px 5px 0\">Testing Tool</th><th style=\"padding: 0 10px 5px 0\">Test Case Name</th><th style=\"padding: 0 10px 5px 0\">Status</th></tr>");

EVENT.payload.testSuiteExec.each{ testSuite ->
  LOG.fine("Processing test suite execution ${testSuite.testSuiteExecutionId}");
  
  testSuite.testExecutions.each{ testExec ->
    LOG.fine("Processing test execution ${testExec.name}");
    
    def testingTool = testExec.toolName;
    
    testExec.testResults.each{ testResult -> 
      def testCaseName = testResult.testCaseName;
      def status = testResult.status;
      
      builder.append("<tr><td style=\"padding-right: 10px\">${testDefName}</td><td style=\"padding-right: 10px\">${testingTool}</td><td style=\"padding-right: 10px\">${testCaseName}</td><td style=\"padding-right: 10px\">${status}</td></tr>");
    }
  }
}

builder.append("</table>");

def htmlMessage = builder.toString();

LOG.fine("Sending test results table to Teams: ${htmlMessage}");
MICROSOFTTEAMS.sendTeamsMessage("TEAMS","FD Developers","Testing",htmlMessage,null);

LOG.setMessage("Successfully sent test results message to teams for ${EVENT.payload.project.projectName}");

def getProjectLink(String pProjectName, Long pProjectId)
{
  String link = String.format("%s/flexdeploy/faces/projects?objecttype=Project&projectid=%s&projectname=%s", FLEXDEPLOY.getFlexDeployBaseUrl(), pProjectId, pProjectName);
  return String.format("<a href=%s>%s</a>", link, pProjectName);
}

Tests Completed Filter

return EVENT.payload.workflow.workflowType == 'TEST';

Naturally you can edit the table/style in any way you wish. The below screen shot is a sample message from the listener:

Build Dependent FlexDeploy Project

This use case can be helpful when you have a FlexDeploy Project that is dependent on some other Project building first. Generally speaking you would try to handle this on the source control side of things but sometimes that just isn't possible. In the below example we are initiating a build on Project with Id 10241 only after a build has successfully completed for the Project with Id 10002.

Build Dependent Project Script

//Carry out any custom action you wish for this event. Check out the documentation for reference or ideas.
//Optionally filter out events you dont want to execute by returning false on the filter script tab.
def listenerName = "Build Dependent Project";
LOG.info("Running listener: ${listenerName}");

def streamId = FLEXDEPLOY.findStreamId(10241L,'master');
FLEXDEPLOY.buildProject(streamId,10241L);

LOG.setMessage("Successfully initiated a build for 10241");

Build Dependent Project Filter

//the project that should be built first
def initiator = 10002;

//only run when we have a successful build of project 10002
return EVENT.payload.executionStatus == "SUCCESS" && EVENT.payload.workflow.workflowType == "BUILD" && EVENT.payload.project.projectId == initiator;

Send email with logs on Workflow Failed

The example below makes use of the FLEXDEPLOY.getPluginLogInputStreams method to send workflow logs as attachments in an email. The message body simply consists of the json payload for the event.

This function is listening to the ‘Workflow Completed’ Event.

import flexagon.ff.model2.pojo.communication.EmailAttachment;
import groovy.json.JsonOutput;

//Carry out any custom action you wish for this event. Check out the documentation for reference or ideas.
//Optionally filter out events you dont want to execute by returning false on the filter script tab.
def listenerName = "Email Failed Logs";
LOG.info("Running listener: ${listenerName}");

//retrieve plugin log input stream map
def logs = FLEXDEPLOY.getPluginLogInputStreams(EVENT.payload.workflowExecutionId);
def attachments = [];

//for each entry create and add a new attachment
//prior to 5.4.0.1 logs would be a list instead of a map
logs.each { log -> 
  attachments.add(new EmailAttachment(log.value,"${log.key}.txt","text/plain"));
}

LOG.info("Sending email with ${attachments.size()} attachments.");

//send email
def subject = "${EVENT.payload.project.projectName} failed in ${EVENT.payload.environment.environmentName}";
def message = JsonOutput.prettyPrint(JsonOutput.toJson(EVENT.payload));
def recipients = ["my.user@domain.com"];

EMAIL.sendEmail(subject, message, recipients, attachments);

LOG.setMessage("Sent email message to ${recipients}");

Email Failed Logs Filter

return EVENT.payload.executionStatus == 'FAILURE';

Create Teams Approval Tasks

This sample sends an interactive message to a Microsoft Teams channel that allows members of the channel to approve or reject an associated FlexDeploy task. As shown in this script, you can add conditions to handle sending to multiple different channels in one listener depending on some condition. (e.g. environment, pipeline, release, etc.) You could also apply similar logic to the webhook listener filter to customize when and where the Teams message should be sent.

See the incoming samples also. An incoming webhook is needed to capture the button clicks that users perform on the Teams messages and ultimately approve/reject the task in FlexDeploy.

Send Teams Approval Message Listener

// Function Script - Create Approvable Tasks in Teams Channels (Outgoing Webhook) - Available in 5.5.0.2
String message = MICROSOFTTEAMS.makeTaskCreatedMessageForWebhook(EVENT.payload,"https://<urlToYourFlexDeployServerOrExternalProxy>/flexdeploy/webhooks/v1/<uri setup in Incoming Webhook>");

String webhookUrlBI = "https://flexagon.webhook.office.com/webhookb2/cb7f2430-...9ee6-98a7eae43f9f";
String webhookUrlMule = "https://flexagon.webhook.office.com/webhookb2/cb7f2430-9...-98a7eae43f9f";
String webhookUrlSF = "https://flexagon.webhook.office.com/webhookb2/cb7f2430-96dc-4....-98a7eae43f9f";

if(condition for BI Approval){
MICROSOFTTEAMS.sendTeamsWebhookMessage(webhookUrlBI,message);
} else if(condition for Mule Approval){
MICROSOFTTEAMS.sendTeamsWebhookMessage(webhookUrlMule,message);
} else if(condition for SF Approval){
MICROSOFTTEAMS.sendTeamsWebhookMessage(webhookUrlSF,message);
}

Execute Utility Project

This sample executes a specific FlexDeploy Utility Project called “RunSonar”. In the script below, we are executing the “RunSonar” project whenever a Build workflow with the specified projectId completes successfully. As an extension of the executeUtility function, we can pass ExecuteOptions which allows you to configure which instances the utility project will run on and also the ability to pass inputs and flexfields values to the utility workflow. If no ExecuteOptions are passed as parameters, then the utility will execute on all instances associated in the project configuration.

This function is listening to the ‘Workflow Completed’ Event.

Example Groovy Code

//Carry out any custom action you wish for this event. Check out the documentation for reference or ideas.
//Optionally filter out events you dont want to execute by returning false on the filter script tab.
def listenerName = "myListener";
LOG.info("Running listener: ${listenerName}");

def projectId = EVENT.payload.project.projectId;
def projectName = EVENT.payload.project.projectName;
def workflowType = EVENT.payload.workflow.workflowType;
def executionStatus = EVENT.payload.executionStatus;

if (projectId == 516098 && workflowType == "BUILD" && executionStatus == "SUCCESS") {
  LOG.info("Executing Utility Project : ${listenerName}");
  def sonarScanProjectId = FLEXDEPLOY.findProjectId("RunSonar");
  def environmentCode = "DEV";
  
  def workflowRequestId = FLEXDEPLOY.executeUtility(sonarScanProjectId, environmentCode);
  
  if (workflowRequestId) {
    LOG.info("Run Sonar Utility was successfully executed");
  }
  else {
    LOG.severe("Run Sonar Utility failed");
  }

Update Package to Completed After Production Deployment

Note that this function may no longer needed as Release Settings incorporate this functionality.

You may want to change a package’s status to completed to indicate it successfully deployed to its final environment. This webhook handles changing the status for you using the Workflow Completed Event. You could update the filter to only update the status for certain projects, releases, instances, etc.

Webhook Listener

​def releaseName = EVENT.payload.release.releaseName
def projectId = EVENT.payload.project.projectId
def packageName = EVENT.payload.packageName

FLEXDEPLOY.updatePackageStatus(projectId, packageName, "COMPLETED")

Webhook Filter

return "SUCCESS".equals(EVENT.payload.executionStatus) && "PRODUCTION".equals(EVENT.payload.environment.environmentCode) && EVENT.payload.packageName != null

Set the Assignee of the Work Item on Work Item Creation

To prevent user error when creating a work item, you set the default Assignee for the Work Item to the user who created the work item if it was not set. This webhook will only set the assignee at creation time using the Work Item Created Event.

Webhook Listener

FlxWorkItemDataObject workItem = FLEXDEPLOY.findWorkItemByNumber(EVENT.payload.workItemNumber)

// check if the assignee is not already set
if (!workItem.getAssignee()?.trim())
{
  FLEXDEPLOY.updateWorkItemAssignee(EVENT.payload.workItemNumber, EVENT.payload.createdBy)
}

Enable Webhook on Project Creation

The following script demonstrates how to automatically enable the webhook after creating new projects.

Webhook Listener

Select the Event Types as Project Created from the drop-down

image-20240701-150647.png
import flexagon.fd.model.pojos.rest.project.*;
import flexagon.fd.model2.pojo.ProjectDataObject;

LOG.info("Running listener: ${FUNCTION_NAME}");
LOG.info(EVENT.payload.projectName);

def projectDataObject = new ProjectDataObject();
projectDataObject.setProjectId(EVENT.payload.projectId);

def resProjects = FLEXDEPLOY.searchProjects(projectDataObject,10,0).getItems();

def proj = new ProjectPojo();
proj.setWebhooksEnabled(true);

for (def project:resProjects)
{
  def projectId = project.getProjectId();
  FLEXDEPLOY.patchProject(projectId, proj);
}
LOG.setMessage("Webhook is now enabled for Project " + EVENT.payload.projectName);

Users can customize their Match Script according to their needs. If a match script filter is not provided, the webhook will automatically be enabled for all newly created projects. This approach ensures seamless integration for every project, regardless of specific requirements.

  • No labels