Sample Scripts
Create a Subtask
This script allows you to create a sub task for a specified parent issue inside a company-managed project.
Good to know
In this example, the script automatically creates a sub-task under an existing parent issue in a company-managed project.
groovydef projectKey = project.key as String // create two issues Issues.create(projectKey, 'Task') { summary = "Create Confluence space associated to the project" description = "Don't forget to do this!." } Issues.create(projectKey, 'Task') { summary = "Bootstrap connect add-on" description = "Some other task" }
Add Comment On Issue Created
This script illustrates how to automatically add a comment to a newly created issue in Jira. This functionality enhances communication by ensuring that relevant information is provided immediately upon issue creation.
Good to know
groovydef author = event.issue.getCreator().displayName event.issue.addComment("""Thank you ${author} for creating a support request. We'll respond to your query within 24hrs. In the meantime, please read our documentation: http://example.com/documentation""
Add Label To Issue with Escalation Service
With this script you can add a label to all issues matching the escalation service JQL query.
In this example, I want to add a label to every issue matching my JQL query in Escalation Service. I can use this snippet to achieve that.
groovy// you can *add* a label to existing labels issue.update { setLabels { add('MY_LABEL_1') } } // *OR* you can set multiple labels at once (this syntax overwrites all labels) issue.update { setLabels('MY_LABEL_1', 'MY_LABEL_2') } // you can *remove* or *replace* labels issue.update { setLabels { remove('MY_LABEL_1') replace('MY_LABEL_2', 'MY_LABEL_3') } }
Create Issues Script
This script demonstrates how to create issues of the type "Task" in Jira. It automates the process of issue creation, ensuring that tasks are generated based on specific triggers.
Good to know
groovydef projectKey = project.key as String // create two issues Issues.create(projectKey, 'Task') { summary = "Create Confluence space associated to the project" description = "Don't forget to do this!." } Issues.create(projectKey, 'Task') { summary = "Bootstrap connect add-on" description = "Some other task" }
Defensive code for context variables
With this script you can write code in Script Listeners that preemptively checks for the presence of all the context variables needed in the script.
Good to know
Script Listeners provide access to different context variables depending on the selected trigger events. For this script to function correctly, it must have access to the 'user
' and 'issue
' context variables.
For instance, the 'issue_updated
' event provides these variables, whereas 'attachment_created
' does not. By selecting both events as triggers, defensive coding ensures that the script performs the desired task when possible (e.g., for 'issue_updated
') and gracefully fails while logging useful information when not (e.g., for 'attachment_created
').
This example demonstrates how to safely write a script for a Script Listener, triggered by an issue update or attachment addition, to add a comment to the issue. The comment mentions the display name of the user who initiated the event.
groovy// Variables ISSUE and USER are being used in the script, so the logic first check their availability def missingVariables = ['issue', 'user'].findAll { !binding.hasVariable(it) } if (missingVariables.isEmpty()) { issue.addComment("Last updated by: ${user.displayName}") } else { logger.warn("No variable(s) [${missingVariables.join(', ')}] available in the context for event [${webhookEvent}]") }
Get select list custom field option
This example shows how to retrieve the value of a select list custom field.
groovydef issueKey = 'KAN-1' def customFieldName = 'myCustomField' def customField = Issues.getByKey(issueKey).getCustomFieldValue(customFieldName) if (customField != null) { "The value of the select list from the ${customFieldName} custom field is: ${customField}" } else { return "${customFieldName} field is null" }
Get Custom Field Value
This example shows how you can extract the value of a custom field for an issue using the custom field name.
Good to know
groovyissue.getCustomFieldValue('customFieldName')
Sum Sprint By User
This script sums up the estimate values of issues in a sprint by assignee.
Good to know
This example demonstrates how to write a script to sum the estimates of all issues in a sprint, grouped by the assignee. It calculates and outputs the total estimate for each team member involved in the sprint.
groovydef SPRINT_ID = 1 // make search def issues = Issues.search("sprint = ${SPRINT_ID}") assert issues != null // helper method for clarity def sumOfOriginalEstimate = { fields -> fields*.timeoriginalestimate.inject(0) { acc, estimate -> acc + (estimate ?: 0) // default to 0 } } def issuesByAssignee = issues*.fields.groupBy { it.assignee?.name } issuesByAssignee.collectEntries { k, v -> [(k): sumOfOriginalEstimate(v)] }
Transition issues with Escalation Service
With this script you can transition all issues matching the escalation service JQL query.
In this example, I want to transition every issue matching my JQL query in Escalation Service.
groovydef transitionName = 'Start progress' try { issue.transition(transitionName) return "Issue ${issue.key} was transitioned by the escalation service." } catch (Exception e) { return "The escalation service failed to transition issue ${issue.key}." }
Update Issue Summary
This script demonstrates how to update the summary of an issue.
Good to know
groovyIssues.getByKey("ISSUE_KEY").update { setSummary("Updated by a script") }
Update Multiple Fields
This script demonstrates how to update multiple fields on a Jira issue in a single operation. It streamlines the process of modifying issue attributes, ensuring that relevant information is kept up to date efficiently.
Good to know
groovydef toUpdate1CfId = "Custom Field 1" def toUpdate2CfId = "Custom Field 2" def toUpdate3CfId = "Custom Field 3" def tomorrowStr = (new Date() + 1).format("yyyy-MM-dd'T'HH:mm:ssZ", TimeZone.getTimeZone("UTC")) // date format in iso8601 event.issue.update{ setFixVersions("1.1") setComponents("My Component") setDescription("A generated description") setCustomFieldValue(toUpdate1CfId, "Some text value") setCustomFieldValue(toUpdate2CfId, tomorrowStr) setCustomFieldValue(toUpdate3CfId, "admin") }
Update Parent With Estimate Sum
This script updates the parent issue by summing the time estimates from all associated subtasks. It is designed to optimise performance by fetching only the necessary estimate fields during the issue search. The script is lightweight and efficient, focusing on retrieving only the estimate fields, which reduces the time needed for the search operation.
Good to know
if (!(issue.subTask && issue.getProjectObject().key == '<ProjectKeyHere>')) {
return;
}
This helps to limit the scope of the script, ensuring it only affects the intended project.
In this example, I work in engineering, where we often have complex parent issues with multiple subtasks. Keeping the parent issue's time estimate up to date manually can be time-consuming. With this script, the parent issue is automatically updated whenever subtasks are modified, ensuring that we have an accurate sum of all the time estimates in real-time.
groovydef issue = event.issue if (!issue.getSubtasks().subTask) { return } // Retrieve all the subtasks of this issue's parent def parentKey = issue.getKey() def allSubtasks = issue.getSubtasks() logger.info("Total subtasks for ${parentKey}: ${allSubtasks.size()}") def estimate = issue.getSubtasks().collect { subtask -> subtask.getCustomFieldValue("Time Estimate") ?: 0 }.sum() // Update the parent issue issue.update{ setCustomFieldValue("Summed Subtask Estimate", estimate) }
Update Parent With Subtask Count
This script example automates the process of updating the parent issue with the count of its subtasks, saving from manually checking and updating it every time.
Good to know
In this example, I work in engineering, where we often break down larger tasks into multiple subtasks for better tracking and delegation. To keep a clear overview, it's crucial to know how many subtasks a parent issue has. Whenever a new subtask is created, updated, or deleted, the parent issue should reflect the current count of its subtasks.
groovydef subTasks= issue.getSubTaskObjects() def subTaskCount = subTasks.size() println("Total subtasks for ${issue.getKey()}: ${subTaskCount}") issue.update { setCustomFieldValue('Subtask Count', subTaskCount) }
Update Issue Resolution
This script demonstrates how to update the resolution of an issue when it transitions between workflows.
Good to know
groovyIssues.getByKey("ISSUE_KEY").transition('Done') { // Can set any resolutions used in your version of Jira setResolution('Duplicate') }