Jira ScriptRunner is a powerful tool for automating and extending Jira's capabilities
through custom scripts written in Groovy. Here are some common examples of how you
can use ScriptRunner in Jira:
### 1. Automating Issue Transitions
Automate the transition of issues based on specific conditions.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def workflowManager = [Link]()
def user = [Link]().getLoggedInUser()
Issue issue = [Link]("TEST-1")
// Check if issue meets the condition
if ([Link]().getName() == "To Do") {
def workflowTransitionUtil =
[Link]([Link]
)
[Link](issue)
[Link]([Link])
[Link](11) // ID of the transition action
[Link]()
[Link]()
}
```
### 2. Automatically Assign Issues
Automatically assign issues to a user based on certain criteria.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def userManager = [Link]()
MutableIssue issue = [Link]("TEST-1")
def user = [Link]("jdoe")
if ([Link]().getName() == "High") {
[Link](user)
[Link]()
```
### 3. Creating Sub-Tasks Automatically
Create sub-tasks when an issue is created.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def subTaskManager = [Link]()
def issueFactory = [Link](IssueFactory)
def user = [Link]().getLoggedInUser()
MutableIssue parentIssue = [Link]("TEST-1")
if ([Link]().getName() == "Task") {
def subTask = [Link]()
[Link]("Sub-task for " + [Link]())
[Link](parentIssue)
[Link]("5") // Sub-task issue type ID
[Link]([Link]())
[Link](user, subTask)
```
### 4. Sending Custom Notifications
Send custom email notifications based on issue events.
```groovy
import [Link]
import [Link]
import [Link]
def mailServer =
[Link]().getDefaultSMTPMailServer()
def issueManager = [Link]()
if (mailServer) {
def issue = [Link]("TEST-1")
def emailAddr = [Link]().getEmailAddress()
def email = new Email(emailAddr)
[Link]("Issue Updated: ${[Link]()}")
[Link]("The issue ${[Link]()} has been updated. Please review the
changes.")
[Link](email)
} else {
[Link]("No SMTP mail server configured")
```
### 5. Adding Comments Programmatically
Add a comment to an issue based on a condition.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def commentManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
if ([Link]().getName() == "Critical") {
[Link](issue, user, "This is a critical issue that requires immediate
attention.", true)
```
These examples showcase various ways you can utilize Jira ScriptRunner to enhance
your Jira workflows. Always ensure you test scripts in a staging environment before
applying them to production to prevent any disruptions.
Sure, here are some more advanced examples of how you can use Jira ScriptRunner to
automate and extend Jira functionalities.
### 6. Bulk Update Custom Fields
Update a custom field for all issues in a particular project.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def searchService = [Link](SearchProvider)
def query = "project = TEST" // JQL query
def user = [Link]().getLoggedInUser()
def parseResult = [Link](user, query)
def results = [Link]([Link], user,
[Link]())
def customField =
[Link]("CustomFieldName")
[Link]().each { issue ->
def mutableIssue = [Link]([Link])
[Link](customField, "New Value")
[Link](user, mutableIssue,
EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 7. Cloning Issues with Links
Clone an issue and create a link between the original and the clone.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueFactory = [Link]()
def issueLinkManager = [Link]()
def user = [Link]().getLoggedInUser()
Issue issue = [Link]("TEST-1")
def clone = [Link](issue)
[Link]("Clone of " + [Link]())
[Link](user, clone)
[Link]([Link], [Link], 10000, 1, user) // 10000 is the link
type ID for "Cloners"
```
### 8. Escalating Issues Based on SLA
Escalate issues by changing their priority if SLA is breached.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
def searchService = [Link](SearchProvider)
def issueManager = [Link]()
def constantsManager = [Link]()
def user = [Link]().getLoggedInUser()
def query = "project = TEST AND \"Time to resolution\" <= remaining(\"1d\") AND
status != Resolved"
def parseResult = [Link](user, query)
def results = [Link]([Link], user,
[Link]())
def highPriority = [Link]("2") // "2" is typically the ID for
High priority
[Link]().each { issue ->
MutableIssue mutableIssue = [Link]([Link])
[Link](highPriority)
[Link](user, mutableIssue, EventDispatchOption.ISSUE_UPDATED,
false)
```
### 9. Transition Issues in Bulk
Transition multiple issues to a different status based on a condition.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
def searchService = [Link](SearchProvider)
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def query = "project = TEST AND status = 'Open'"
def parseResult = [Link](user, query)
def results = [Link]([Link], user,
[Link]())
[Link]().each { issue ->
def transitionInput = new [Link]([Link](), 31,
user) // 31 is the ID for the transition action
def transitionResult = [Link](user, transitionInput, new
[Link]().skipPermissions().build())
if ([Link]()) {
[Link](user, transitionResult)
```
### 10. Setting Security Levels on Issues
Automatically set security levels on issues based on certain conditions.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def securityLevelManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def securityLevel = [Link](10000) // ID of the security
level
if ([Link]().getName() == "High") {
MutableIssue mutableIssue = [Link]([Link])
[Link]([Link])
[Link](user, mutableIssue, EventDispatchOption.ISSUE_UPDATED,
false)
```
These examples demonstrate the versatility of ScriptRunner in Jira, allowing you to
automate complex workflows and customize your Jira instance to fit your organization's
needs. As always, ensure thorough testing in a staging environment before applying
these scripts in production.
Certainly! Here are more advanced ScriptRunner examples to help you further automate
and extend your Jira workflows:
### 11. Enforcing Field Validation
Ensure a custom field is filled out before transitioning an issue.
```groovy
import [Link]
import [Link]
def customFieldManager = [Link]()
def issueManager = [Link]()
def customField =
[Link]("CustomFieldName")
def issue = [Link]("TEST-1")
def fieldValue = [Link](customField)
if (!fieldValue) {
throw new InvalidInputException("Custom field must be filled before transitioning.")
```
### 12. Auto-Close Issues After a Period
Automatically close issues that have been in a specific status for more than a certain
number of days.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
def searchService = [Link](SearchProvider)
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def query = "project = TEST AND status = 'Resolved' AND resolved <= -7d" // JQL for
issues resolved more than 7 days ago
def parseResult = [Link](user, query)
def results = [Link]([Link], user,
[Link]())
[Link]().each { issue ->
def transitionInput = new [Link]([Link](), 31,
user) // 31 is the ID for the transition action to close
def transitionResult = [Link](user, transitionInput)
if ([Link]()) {
[Link](user, transitionResult)
```
### 13. Linking Related Issues
Link issues together based on custom field values.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def issueLinkManager = [Link]()
def user = [Link]().getLoggedInUser()
def customField =
[Link]("RelatedIssueKey")
def issue = [Link]("TEST-1")
def relatedIssueKey = [Link](customField)
if (relatedIssueKey) {
def relatedIssue = [Link]([Link]())
if (relatedIssue) {
[Link]([Link], [Link], 10000, 1, user) //
10000 is the link type ID for "Relates"
```
### 14. Setting Due Dates Based on Priority
Automatically set due dates for issues based on their priority.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issue = [Link]("TEST-1")
def today = [Link]()
MutableIssue mutableIssue = [Link]([Link])
switch ([Link]().getName()) {
case "Highest":
[Link]([Link]([Link](1).atStartOfDay([Link]
ault()).toInstant()))
break
case "High":
[Link]([Link]([Link](3).atStartOfDay([Link]
ault()).toInstant()))
break
case "Medium":
[Link]([Link]([Link](7).atStartOfDay([Link]
ault()).toInstant()))
break
case "Low":
[Link]([Link]([Link](14).atStartOfDay([Link]
fault()).toInstant()))
break
case "Lowest":
[Link]([Link]([Link](30).atStartOfDay([Link]
fault()).toInstant()))
break
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.ISSUE_UPDATED, false)
```
### 15. Escalate to Different Project
Automatically clone and escalate issues to another project if they meet certain criteria.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueFactory = [Link]()
def user = [Link]().getLoggedInUser()
def issueLinkManager = [Link]()
def issue = [Link]("TEST-1")
if ([Link]().getName() == "Critical") {
MutableIssue clone = [Link](issue)
[Link](10200) // Target project ID
[Link]("10001") // Target issue type ID
[Link]("Escalated: " + [Link]())
[Link](user)
[Link]()
[Link](user, clone)
[Link]([Link], [Link], 10001, 1, user) // 10001 is the
link type ID for "Escalates"
```
### 16. Custom Workflow Validators
Add custom validators to workflows to enforce business rules.
```groovy
import [Link]
import [Link]
def customFieldManager = [Link]()
def issueManager = [Link]()
def customField = [Link]("Approval")
def issue = [Link]("TEST-1")
def approvalValue = [Link](customField)
if (!approvalValue || [Link]() != "Approved") {
throw new InvalidInputException("Issue must be approved before transitioning.")
}
```
### 17. Generate and Attach PDF Report
Generate a PDF report for an issue and attach it to the issue.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link].PDType1Font
def issueManager = [Link]()
def attachmentManager = [Link]()
def user = [Link]().getLoggedInUser()
MutableIssue issue = [Link]("TEST-1")
PDDocument document = new PDDocument()
PDPage page = new PDPage()
[Link](page)
PDPageContentStream contentStream = new PDPageContentStream(document, page)
[Link]([Link], 12)
[Link]()
[Link](100, 700)
[Link]("Issue Key: " + [Link]())
[Link](0, -20)
[Link]("Summary: " + [Link]())
[Link]()
[Link]()
def tempFile = [Link]("issue-report", ".pdf")
[Link](tempFile)
[Link]()
[Link](tempFile, "[Link]", "application/pdf",
user, issue, null, new Date())
[Link]()
```
### 18. Dynamic Priority Adjustment
Adjust issue priority based on custom logic involving multiple fields.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def constantsManager = [Link]()
def issue = [Link]("TEST-1")
def priority = [Link]([Link])
def urgency =
[Link]([Link]().getCustomFi
eldObjectByName("Urgency"))
def impact =
[Link]([Link]().getCustomFi
eldObjectByName("Impact"))
if (urgency == "High" && impact == "High") {
priority = [Link]("1") // Highest
} else if (urgency == "High" || impact == "High") {
priority = [Link]("2") // High
} else {
priority = [Link]("3") // Medium
MutableIssue mutableIssue = [Link]([Link])
[Link](priority)
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.ISSUE_UPDATED, false)
```
### 19. Automatically Watch Issues
Automatically add watchers to an issue based on custom field values.
```groovy
import [Link]
import [Link]
def issue
Sure, here are additional advanced ScriptRunner examples for Jira:
### 19. Automatically Watch Issues (Continued)
Automatically add watchers to an issue based on custom field values.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def watcherManager = [Link]()
def userManager = [Link]()
def issue = [Link]("TEST-1")
def customField = [Link]("Watchers")
def watcherUsernames = [Link](customField) as List<String>
watcherUsernames?.each { username ->
def user = [Link](username)
if (user) {
[Link](user, issue)
}
```
### 20. Custom Scripted Conditions
Condition to check if a user belongs to a specific group before allowing a transition.
```groovy
import [Link]
def user = [Link]().getLoggedInUser()
def groupManager = [Link]()
def groupName = "jira-administrators"
def group = [Link](groupName)
if ([Link](user, group)) {
return true
} else {
return false
```
### 21. Sending Slack Notifications
Send a notification to a Slack channel when an issue is updated.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issue = [Link]("TEST-1")
def slackWebhookUrl = "[Link]
def payload = [
text: "Issue ${[Link]} has been updated. Summary: ${[Link]}",
username: "JiraBot",
icon_emoji: ":jira:"
def restClient = new RESTClient(slackWebhookUrl)
[Link](
body: new JsonBuilder(payload).toString(),
requestContentType: 'application/json'
```
### 22. Reopening Closed Issues
Automatically reopen issues if a comment is added after they are closed.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
IssueEvent issueEvent = event as IssueEvent
def issue = [Link]
if ([Link]().name == "Closed" && [Link] ==
EventType.ISSUE_COMMENTED_ID) {
def transitionValidationResult = [Link](user, [Link], 3, new
IssueInputParametersImpl()) // 3 is the transition ID for reopen
if ([Link]()) {
[Link](user, transitionValidationResult)
```
### 23. Assign Issues Based on Round-Robin
Automatically assign issues to a team in a round-robin fashion.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def userManager = [Link]()
def projectManager = [Link]()
def customFieldManager = [Link]()
def issue = [Link]("TEST-1")
def project = [Link]([Link]())
def assigneeUsernames = ["user1", "user2", "user3"]
def customField = [Link]("Last Assignee")
def lastAssignee = [Link](customField) as String
def nextAssignee = assigneeUsernames[([Link](lastAssignee) + 1)
% [Link]()]
def user = [Link](nextAssignee)
[Link](user)
[Link]()
[Link](customField, nextAssignee)
```
### 24. Synchronizing Issue Data with External System
Synchronize issue data with an external system via REST API.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issue = [Link]("TEST-1")
def externalSystemUrl = "[Link]
def payload = [
issueKey: [Link],
summary: [Link],
description: [Link],
status: [Link]().getName()
def restClient = new RESTClient(externalSystemUrl)
[Link](
body: new JsonBuilder(payload).toString(),
requestContentType: 'application/json'
```
### 25. Validating Issue Fields on Transition
Ensure specific fields meet criteria before allowing a transition.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def issue = [Link]("TEST-1")
def customField =
[Link]("CustomFieldName")
def fieldValue = [Link](customField)
if (!fieldValue || [Link]() < 5) {
throw new InvalidInputException("Custom field must be at least 5 characters long
before transitioning.")
```
### 26. Custom Email Notifications
Send custom email notifications based on issue events.
```groovy
import [Link]
import [Link]
import [Link]
def mailServer =
[Link]().getDefaultSMTPMailServer()
def issueManager = [Link]()
if (mailServer) {
Absolutely, here are additional ScriptRunner examples for further automation and
customization in Jira:
### 26. Custom Email Notifications (Continued)
Send custom email notifications based on issue events.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def mailServer =
[Link]().getDefaultSMTPMailServer()
def issueManager = [Link]()
def issue = [Link]("TEST-1")
if (mailServer) {
def emailAddr = [Link]().getEmailAddress()
def email = new Email(emailAddr)
[Link]("Issue Updated: ${[Link]()}")
[Link]("The issue ${[Link]()} has been updated. Please review the
changes.")
[Link](email)
} else {
[Link]("No SMTP mail server configured")
```
### 27. Auto-Create Linked Issues in Another Project
Automatically create a linked issue in another project when an issue is created.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def issueLinkManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def projectKey = "OTHERPROJECT"
def issueTypeId = "10001" // Issue type ID for the new issue
def issueInputParameters = new IssueInputParametersImpl()
[Link](projectKey)
[Link](issueTypeId)
[Link]("Linked issue for: " + [Link]())
[Link]([Link])
[Link]("This issue is linked to " + [Link]())
def validationResult = [Link](user, issueInputParameters)
if ([Link]()) {
def createResult = [Link](user, validationResult)
if ([Link]()) {
[Link]([Link], [Link], 10000, 1, user) //
10000 is the link type ID for "Relates"
```
### 28. Enforcing Sub-Task Closure Before Parent Closure
Ensure all sub-tasks are closed before allowing the parent issue to be closed.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def subTaskManager = [Link]()
def issue = [Link]("TEST-1")
if ([Link]()) {
return
def subTasks = [Link](issue)
def openSubTasks = [Link] { [Link]().getName() != "Closed" }
if (openSubTasks) {
throw new InvalidInputException("All sub-tasks must be closed before closing the
parent issue.")
```
### 29. Dynamic Field Update Based on Linked Issue Status
Update a custom field based on the status of linked issues.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def customFieldManager = [Link]()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect {
[Link] }
def linkedIssuesStatus = linkedIssues*.getStatus().collect { [Link]() }
def customField =
[Link]("LinkedIssuesStatus")
def linkedIssuesStatusStr = [Link](", ")
MutableIssue mutableIssue = [Link]([Link])
[Link](customField, linkedIssuesStatusStr)
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 30. Auto-Assign Based on Components
Automatically assign issues based on the components selected.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def userManager = [Link]()
def componentManager = [Link]()
def issue = [Link]("TEST-1")
def components = [Link]()
def userToAssign
[Link] { ProjectComponent component ->
if ([Link]() == "Database") {
userToAssign = [Link]("database_user")
} else if ([Link]() == "UI") {
userToAssign = [Link]("ui_user")
}
if (userToAssign) {
MutableIssue mutableIssue = [Link]([Link])
[Link](userToAssign)
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 31. Setting Issue Priority Based on Linked Bug Severity
Set issue priority based on the severity of linked bug issues.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def constantsManager = [Link]()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect {
[Link] }
def highestSeverity = [Link] { [Link]().getName() == "Bug"
}?.getPriority()?.getName()
def priority
if (highestSeverity == "Blocker") {
priority = [Link]("1") // Highest
} else if (highestSeverity == "Critical") {
priority = [Link]("2") // High
if (priority) {
MutableIssue mutableIssue = [Link]([Link])
[Link](priority)
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 32. Notifying on Issue Creation in Specific Projects
Send an email notification to a specific group when an issue is created in a specific
project.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def mailServer =
[Link]().getDefaultSMTPMailServer()
def issueManager = [Link]()
def groupManager = [Link]()
def userManager = [Link]()
def issue = [Link]("TEST-1")
if (mailServer && [Link]().getKey() == "SPECIALPROJECT") {
def group = [Link]("special-group")
def emailAddresses = [Link](group).collect {
[Link]() }.join(",")
def email = new Email(emailAddresses)
[Link]("New Issue Created: ${[Link]()}")
[Link]("A new issue ${[Link]()} has been created in project
SPECIALPROJECT. Summary: ${[Link]()}")
[Link](email)
```
### 33. Triggering Builds on CI Server
Trigger a build on a CI server (e.g., Jenkins) when an issue transitions.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issue = [Link]("TEST-1")
def ciServerUrl = "[Link]
def apiToken = "your-api-token"
def restClient = new RESTClient(ciServerUrl)
def response = [Link](
headers: ['Authorization': "Bearer ${apiToken}"],
body: [issueKey: [Link]()],
requestContentType: 'application/json'
if ([Link] != 200) {
[Link]("Failed to trigger CI build: ${[Link]}")
```
### 34. Generate and Attach CSV Report
Generate a CSV report for an issue and attach it to the issue.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def attachmentManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def csvContent = "Key,Summary,Status\n
Certainly! Here are even more advanced ScriptRunner examples for Jira:
### 34. Generate and Attach CSV Report (Continued)
Generate a CSV report for an issue and attach it to the issue.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def attachmentManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def csvContent =
"Key,Summary,Status\n${[Link]},${[Link]},${[Link]}\n"
def tempFile = [Link]("issue-report", ".csv")
[Link](csvContent)
[Link](tempFile, "[Link]", "text/csv", user,
issue, null, new Date())
[Link]()
```
### 35. Bulk Update Issues
Bulk update the description of all issues in a project.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
def searchService = [Link](SearchService)
def searchProvider = [Link](SearchProvider)
def issueManager = [Link]()
def user = [Link]().getLoggedInUser()
def jqlQuery = "project = TEST"
def parseResult = [Link](user, jqlQuery)
def searchResults = [Link](user, [Link],
[Link]())
[Link] { documentIssue ->
MutableIssue issue = [Link]([Link])
[Link]("Updated description")
[Link](user, issue, EventDispatchOption.ISSUE_UPDATED, false)
```
### 36. Automatically Close Issues Based on Comment Content
Automatically close issues if a comment contains a specific keyword.
```groovy
import [Link]
import [Link]
import [Link]
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
IssueEvent issueEvent = event as IssueEvent
def issue = [Link]
if ([Link] == EventType.ISSUE_COMMENTED_ID) {
def comment = [Link]
if (comment && [Link]("close issue")) {
def transitionValidationResult = [Link](user, [Link], 5,
new IssueInputParametersImpl()) // 5 is the transition ID for close
if ([Link]()) {
[Link](user, transitionValidationResult)
}
```
### 37. Calculate and Set Due Date Based on Custom Field
Calculate and set the due date based on a custom field value.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def customField = [Link]("Time to
Complete (days)")
def daysToComplete = [Link](customField) as Integer
if (daysToComplete != null) {
def dueDate = new Date() + daysToComplete
[Link](dueDate)
[Link](user, issue, EventDispatchOption.DO_NOT_DISPATCH,
false)
}
```
### 38. Automatically Set Labels Based on Summary
Automatically set issue labels based on keywords in the summary.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def summary = [Link]()
def labels = [Link]()
if ([Link]("urgent")) {
[Link]("urgent")
if ([Link]("bug")) {
[Link]("bug")
[Link](labels)
[Link](user, issue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 39. Sync Custom Field Value with External System
Sync a custom field value with an external system via REST API.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def customField = [Link]("External ID")
def externalId = [Link](customField)
def externalSystemUrl = "[Link]
def payload = [
issueKey: [Link],
externalId: externalId
def restClient = new RESTClient(externalSystemUrl)
def response = [Link](
body: new JsonBuilder(payload).toString(),
requestContentType: 'application/json'
)
if ([Link] != 200) {
[Link]("Failed to sync with external system: ${[Link]}")
```
### 40. Auto-Transition Based on Linked Issues
Auto-transition an issue when all linked issues reach a certain status.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect { [Link] }
def allResolved = [Link] { [Link]().getName() == "Resolved" }
if (allResolved) {
def transitionValidationResult = [Link](user, [Link], 31, new
IssueInputParametersImpl()) // 31 is the transition ID for close
if ([Link]()) {
[Link](user, transitionValidationResult)
```
### 41. Bulk Clone Issues
Bulk clone issues in a project and link them to the original issues.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def issueFactory = [Link]()
def issueLinkManager = [Link]()
def user = [Link]().getLoggedInUser()
def jqlQuery = "project = TEST"
def searchService = [Link](SearchService)
def parseResult = [Link](user, jqlQuery)
def searchResults = [Link](user, [Link],
[Link]())
[Link] { issueDocument ->
def issue = [Link]([Link])
def clonedIssue = [Link](issue)
[Link]([Link]().getId())
[Link]([Link]().getId())
[Link]("Clone of " + [Link]())
[Link](user)
def inputParams = new IssueInputParametersImpl(clonedIssue)
def createResult = [Link](user, inputParams)
if ([Link]()) {
[Link]([Link], [Link], 10000, 1, user) //
10000 is the link type ID for "Relates"
```
These examples should give you a broader range of automation and customization
options for your Jira environment using ScriptRunner. Feel free to adapt and combine
these scripts according to your specific requirements.
Certainly! Here are even more advanced ScriptRunner examples for Jira:
### 42. Update Issue Custom Field Based on Linked Issue Field
Update a custom field in an issue based on a field value from linked issues.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def customFieldManager = [Link]()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect {
[Link] }
def linkedPriorities = linkedIssues*.getPriority().collect { [Link] }
def highestPriority = [Link] { it }.first()
def customField = [Link]("Linked Issue
Priority")
MutableIssue mutableIssue = [Link]([Link])
[Link](customField, highestPriority)
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 43. Restrict Issue Transition Based on Time of Day
Restrict issue transitions to business hours only.
```groovy
import [Link]
import [Link]
def currentTime = new Date().format("HH:mm", [Link]("UTC"))
def startTime = "09:00"
def endTime = "17:00"
if (currentTime < startTime || currentTime > endTime) {
throw new InvalidInputException("Issue transitions are only allowed during business
hours (09:00 - 17:00 UTC).")
```
### 44. Copy Comments from Linked Issues
Copy comments from linked issues to the current issue.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def commentManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect { [Link] }
[Link] { linkedIssue ->
def comments = [Link](linkedIssue)
[Link] { comment ->
[Link](issue, user, "Copied from ${[Link]}:
${[Link]}", false)
```
### 45. Automatically Assign Issue to Reporter of Linked Issue
Automatically assign an issue to the reporter of a linked issue.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def userManager = [Link]()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect {
[Link] }
def reporter = linkedIssues?.first()?.getReporter()
if (reporter) {
MutableIssue mutableIssue = [Link]([Link])
[Link](reporter)
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 46. Send Email Notification for Specific Label Addition
Send an email notification when a specific label is added to an issue.
```groovy
import [Link]
import [Link]
import [Link]
def mailServer =
[Link]().getDefaultSMTPMailServer()
def issueManager = [Link]()
def userManager = [Link]()
def issue = [Link]("TEST-1")
def labels = [Link]()
if ([Link]("important")) {
def emailAddr = [Link]().getEmailAddress()
def email = new Email(emailAddr)
[Link]("Important Label Added to Issue: ${[Link]}")
[Link]("The important label has been added to the issue ${[Link]}. Please
review it immediately.")
[Link](email)
```
### 47. Calculate and Set SLA Breach Custom Field
Calculate SLA breach time and set it in a custom field.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def issue = [Link]("TEST-1")
def slaStart = [Link]()
def slaEnd = new Date() // Assuming this is the end of the SLA period
def slaDuration = [Link]([Link](), [Link]()).toHours()
def customField = [Link]("SLA Breach
(hours)")
MutableIssue mutableIssue = [Link]([Link])
[Link](customField, [Link]())
[Link]([Link]().getLogg
edInUser(), mutableIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 48. Create Sub-Tasks Automatically Based on Issue Type
Automatically create specific sub-tasks when an issue of a certain type is created.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
if ([Link] == "Story") {
["Design", "Development", "Testing"].each { subTaskSummary ->
def issueInputParameters = new IssueInputParametersImpl()
[Link]([Link]().getId())
[Link]("5") // Assuming "5" is the issue type ID for
sub-task
[Link]([Link]())
[Link](subTaskSummary)
issueInput
Certainly! Here are even more advanced ScriptRunner examples for Jira:
### 48. Create Sub-Tasks Automatically Based on Issue Type (Continued)
Automatically create specific sub-tasks when an issue of a certain type is created.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
if ([Link] == "Story") {
["Design", "Development", "Testing"].each { subTaskSummary ->
def issueInputParameters = new IssueInputParametersImpl()
[Link]([Link]().getId())
[Link]("5") // Assuming "5" is the issue type ID for
sub-task
[Link]([Link]())
[Link](subTaskSummary)
[Link]([Link])
def validationResult = [Link](user,
issueInputParameters)
if ([Link]()) {
[Link](user, validationResult)
} else {
[Link]("Failed to create sub-task: ${[Link]}")
```
### 49. Transition Linked Issues When Parent Issue Transitions
Automatically transition linked issues when the parent issue transitions.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect { [Link] }
[Link] { linkedIssue ->
def transitionValidationResult = [Link](user, [Link],
31, new IssueInputParametersImpl()) // 31 is the transition ID for close
if ([Link]()) {
[Link](user, transitionValidationResult)
} else {
[Link]("Failed to transition linked issue: ${[Link]}")
```
### 50. Set Issue Components Based on Custom Field
Set the issue components based on a custom field value.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def componentManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def customField = [Link]("Component
Selector")
def selectedComponentName = [Link](customField) as String
if (selectedComponentName) {
def projectComponents =
[Link]([Link]().id)
def selectedComponent = [Link] { [Link] ==
selectedComponentName }
if (selectedComponent) {
[Link]([selectedComponent] as Collection<ProjectComponent>)
[Link](user, issue, EventDispatchOption.DO_NOT_DISPATCH,
false)
```
### 51. Sync Status Between Parent and Sub-Tasks
Automatically sync the status between a parent issue and its sub-tasks.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def issueLinkManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
if ([Link]()) {
def parentIssue = [Link]()
if ([Link] == "Done" && [Link] != "Done") {
def transitionValidationResult = [Link](user,
[Link], 31, new IssueInputParametersImpl()) // 31 is the transition ID for Done
if ([Link]()) {
[Link](user, transitionValidationResult)
} else {
def subTasks = [Link]()
if ([Link] == "Done") {
[Link] { subTask ->
if ([Link] != "Done") {
def transitionValidationResult = [Link](user,
[Link], 31, new IssueInputParametersImpl()) // 31 is the transition ID for Done
if ([Link]()) {
[Link](user, transitionValidationResult)
}
```
### 52. Automatically Watch Issue Based on Field Value
Automatically add a watcher to an issue based on a custom field value.
```groovy
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def watcherManager = [Link]()
def userManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def customField = [Link]("Watch User")
def userName = [Link](customField) as String
if (userName) {
def userToWatch = [Link](userName)
if (userToWatch) {
[Link](userToWatch, issue)
```
### 53. Prevent Issue Creation During Certain Times
Prevent issue creation during non-business hours.
```groovy
import [Link]
import [Link]
import [Link]
def currentTime = new Date().format("HH:mm", [Link]("UTC"))
def startTime = "09:00"
def endTime = "17:00"
if (currentTime < startTime || currentTime > endTime) {
throw new InvalidInputException("Issue creation is only allowed during business
hours (09:00 - 17:00 UTC).")
def issueManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def issueInputParameters = [Link]()
```
### 54. Sync Comments Between Linked Issues
Sync comments between linked issues.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def commentManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect { [Link] }
def newCommentBody = "New comment on linked issues"
[Link] { linkedIssue ->
[Link](linkedIssue, user, newCommentBody, false)
```
### 55. Automatically Create Linked Issue in Different Project
Automatically create a linked issue in a different project when an issue is created.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def issueLinkManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def projectKey = "OTHERPROJECT"
def issueTypeId = "10001" // Issue type ID for the new issue
def issueInputParameters = new IssueInputParametersImpl()
[Link](projectKey)
[Link](issueTypeId)
[Link]("Linked issue for: " + [Link]())
[Link]([Link])
[Link]("This issue is linked to " + [Link]())
def validationResult = [Link](user, issueInputParameters)
if ([Link]()) {
def createResult = [Link](user, validationResult)
if ([Link]()) {
[Link]([Link], [Link], 10000, 1, user) //
10000 is the link type ID for "Relates"
```
### 56. Transition Issue Based on Custom Field Value
Transition an issue based on a specific custom field value.
```groovy
import [Link]
Certainly! Here are more advanced ScriptRunner examples for Jira:
### 56. Transition Issue Based on Custom Field Value (Continued)
Transition an issue based on a specific custom field value.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def customField = [Link]("Status Change
Trigger")
def triggerValue = [Link](customField) as String
if (triggerValue == "Close") {
def transitionValidationResult = [Link](user, [Link], 31, new
IssueInputParametersImpl()) // 31 is the transition ID for Close
if ([Link]()) {
[Link](user, transitionValidationResult)
}
```
### 57. Calculate and Update Remaining Estimate
Calculate and update the remaining estimate based on work log entries.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def worklogManager = [Link]()
def issue = [Link]("TEST-1")
def worklogs = [Link](issue)
def totalLoggedTime = [Link] { [Link]() } ?: 0
def originalEstimate = [Link]() ?: 0
def remainingEstimate = originalEstimate - totalLoggedTime
[Link](remainingEstimate)
[Link]([Link]().getLogg
edInUser(), issue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 58. Auto-Transition Based on Linked Issue Resolution
Automatically transition an issue when a linked issue is resolved.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueLinkManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def linkedIssues = [Link]([Link]).collect { [Link] }
if ([Link] { [Link] }) {
def transitionValidationResult = [Link](user, [Link], 31, new
IssueInputParametersImpl()) // 31 is the transition ID for Close
if ([Link]()) {
[Link](user, transitionValidationResult)
```
### 59. Send Weekly Summary Report via Email
Send a weekly summary report of issues via email.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
def mailServer =
[Link]().getDefaultSMTPMailServer()
def searchService = [Link](SearchService)
def searchProvider = [Link](SearchProvider)
def user = [Link]().getLoggedInUser()
def jqlQuery = "project = TEST AND created >= -1w"
def parseResult = [Link](user, jqlQuery)
def searchResults = [Link](user, [Link],
[Link]())
def emailBody = "Weekly Summary Report:\n\n"
[Link] { issue ->
emailBody += "Key: ${[Link]}, Summary: ${[Link]}, Status:
${[Link]}\n"
def email = new Email("recipient@[Link]")
[Link]("Weekly Jira Report")
[Link](emailBody)
[Link](email)
```
### 60. Auto-Assign Issue Based on Component Lead
Automatically assign an issue to the component lead.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def componentManager = [Link]()
def userManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def components = [Link]()
if (components) {
def componentLead = [Link]().getLead()
if (componentLead) {
[Link](componentLead)
[Link](user, issue, EventDispatchOption.DO_NOT_DISPATCH,
false)
```
### 61. Auto-Close Resolved Issues After 7 Days
Automatically close resolved issues after 7 days.
```groovy
import [Link]
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def issueService = [Link]()
def user = [Link]().getLoggedInUser()
def jqlQuery = "status = Resolved AND resolved <= -7d"
def searchService = [Link](SearchService)
def parseResult = [Link](user, jqlQuery)
def searchResults = [Link](user, [Link],
[Link]())
[Link] { issue ->
def transitionValidationResult = [Link](user, [Link], 31, new
IssueInputParametersImpl()) // 31 is the transition ID for Close
if ([Link]()) {
[Link](user, transitionValidationResult)
}
```
### 62. Update Due Date Based on Priority
Update the due date based on the priority of the issue.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def priority = [Link]().getName()
def dueDateOffset = [
"Highest": 1,
"High": 3,
"Medium": 5,
"Low": 7,
"Lowest": 10
def dueDate = new Date() + dueDateOffset[priority]
[Link](dueDate)
[Link](user, issue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 63. Prevent Issue Deletion Based on Conditions
Prevent issue deletion if certain conditions are met.
```groovy
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def issue = [Link]("TEST-1")
def customField = [Link]("Prevent
Deletion")
def preventDeletion = [Link](customField) as Boolean
if (preventDeletion) {
throw new InvalidInputException("Issue cannot be deleted due to custom field
setting.")
```
### 64. Set Issue Security Level Based on Issue Type
Automatically set the issue security level based on the issue type.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def securityLevelManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def issueType = [Link]().getName()
def securityLevelName = issueType == "Bug" ? "Internal" : "Public"
def securityLevel =
[Link]([Link]().id,
securityLevelName)
[Link]([Link])
[Link](user, issue, EventDispatchOption.DO_NOT_DISPATCH, false)
```
### 65. Sync Issue Fields with External System
Sync certain issue fields with an external system using REST API.
```groovy
import [Link]
import [Link]
import [Link]
def issueManager = [Link]()
def customFieldManager = [Link]()
def user = [Link]().getLoggedInUser()
def issue = [Link]("TEST-1")
def customField = [Link]("External System
ID")
def externalSystemId = [Link](customField)
def externalSystemUrl = "[Link]
def payload = [
issueKey: [Link],
externalSystemId: externalSystemId,
summary: [Link],
status: [Link]
def restClient = new RESTClient(externalSystemUrl)
def response = [Link](
body: new JsonBuilder(payload).