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

The script targets a specific parent issue for sub-task creation. Ensure that the project is company-managed, as the script is designed to work within this type of project.

In this example, the script automatically creates a sub-task under an existing parent issue in a company-managed project.

groovy
def 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

The comment can include dynamic content, such as the creator's name or specific details about the issue.
groovy
def 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

The Script Listener events must be associated with project-related actions, such as Project Created, Project Updated, or Project Deleted. This allows for seamless integration with project management workflows, ensuring that tasks are created in response to relevant project changes.
groovy
def 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.

groovy
def 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

This script can be used in various contexts where you need to access custom field values of an issue. It is useful for scripting tasks in Jira where you need to manipulate or report on custom field data.
groovy
issue.getCustomFieldValue('customFieldName')

Sum Sprint By User

This script sums up the estimate values of issues in a sprint by assignee.

Good to know

The script assumes each issue has an estimate and is assigned to an assignee. Unassigned issues can be grouped separately or skipped.

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.

groovy
def 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.

groovy
def 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

This script can be used in various contexts where you need to update the summary of an issue. It is useful for scripting tasks in Jira where you need to modify issue descriptions based on status changes or when automating bulk updates to issue titles for consistency across tasks.
groovy
Issues.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

Useful when implementing bulk updates or when consolidating multiple changes into a single workflow transition.
groovy
def 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 you want to restrict the script to work only within a specific project, you can use a condition like:
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.

groovy
def 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

The script can be triggered on most of the events related to Issue events (created, updated or deleted). From the dropdown "On these events" in Script Listeners choose the Issue event preferred. When you update the parent issue, the "subtask count" field will automatically reflect the subtasks the issue contains. 

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.

groovy
def 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

This script can be used in various contexts where you need to update the resolution of an issue. It is useful for scripting tasks in Jira where you need to dynamically update the resolution when moving tickets through different workflow stages, such as when closing tasks, handling issue duplication, or marking them as completed.
groovy
Issues.getByKey("ISSUE_KEY").transition('Done') { // Can set any resolutions used in your version of Jira setResolution('Duplicate') }




On this page