Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Expand
titleExample Groovy Code
Code Block
languagegroovy
//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 throghthrough the pipeline. Ending release.");
     FLEXDEPLOY.endRelease(EVENT.payload.release.releaseId);
}

...

Expand
titleTaskCreated Script
Code Block
languagegroovy
//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 Topology->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'");
Expand
titleTaskCreated Filter
Code Block
languagegroovy
return EVENT.payload.taskType == "APPROVAL";

...

Expand
titleUpload Logs Jira Listener Script
Code Block
languagegroovy
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 = "Upload Logs To Jira";
LOG.info("Running listener: ${listenerName}");

def//Prior streamsto = FLEXDEPLOY.getPluginLogInputStreams(EVENT.payload.workflowExecutionId);

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

//We receive a stream for each plugin execution. Since we are filtering for errors, the last stream would be the failed plugin
def errorStream = streams[streams.size()-1];

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.logMessage("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();

//create our form data body
def body = REST.getClient().createFormDataWithInputStream(['file': errorStreamfailedPlugin.getValue()], 'FailedPlugin"${failedPlugin.getKey()}.txt'");

def properties = getJiraProperties('JIRA');

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

for(def issue: EVENT.payload.issueNumbers) {
  LOG.info("Upload logs to issue: ${issue}");
  
  //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];
}

...

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 isnt 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.

...

Expand
titleBuild Dependent Project Filter
Code Block
languagegroovy
//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.

Expand
titleEmail Failed Logs Script
Code Block
languagegroovy
import flexagon.ff.adfext.common.model.pojos.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}");
Expand
titleEmail Failed Logs Filter
Code Block
languagegroovy
return EVENT.payload.executionStatus == 'FAILURE';

Create Teams Approval Tasks

@Since 5.5.0.2

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.

...

Expand
titleSend Teams Approval Message Listener
Code Block
languagegroovy
// 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

@Since 5.5.0.3

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.

...

Expand
titleExample Groovy Code
Code Block
languagegroovy
//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");
  }