Create Sub-tasks when an Issue is Created

Overview

This script automatically creates sub-tasks when a new issue is created.

Example

I require a set of sub-tasks to be added to each new issue I create. Usually, I have to create these sub-tasks manually, which is time consuming. Using this script I can automate the process, creating sub-tasks for each new issue without the need for manual configuration.

Good to Know

  • This script is not executed when sub-tasks are created.
  • Sub-tasks are added to a particular issue with the same type as parent issue.

Requirements

Jira Jira

//If issue is a subtask, script is not executed
if (issue.fields.issuetype.subtask) {
    return
}

// New created issue
def issueKey = issue.key

// Get the issue
def issueResp = get("/rest/api/2/issue/${issueKey}").asObject(Map)
assert issueResp.status == 200
def issue = issueResp.body as Map

// Get the issue types for the instance
def typeResp = get('/rest/api/2/issuetype').asObject(List)
assert typeResp.status == 200
def issueTypes = typeResp.body as List

def listOfsummaries = ['Subtask summary 1', 'Subtask summary 2'] // The summaries to use for
def issueType = "Sub-task" // The Sub Task Issue Type to Use

// Get the sub task issue type to use
def issueTypeId = issueTypes.find { it.subtask && it.name == issueType }?.id
assert issueTypeId: "No subtasks issue type found called '${issueType}'"

// Get the project to create the subtask in
def project = (issue.fields as Map).project

listOfsummaries.forEach { summary ->
    // Create the subtask
    def resp = post("/rest/api/2/issue")
        .header("Content-Type", "application/json")
        .body(
            fields: [
                project  : project,
                issuetype: [
                    id: issueTypeId
                ],
                parent   : [
                    id: issue.id
                ],
                summary  : summary
            ])
        .asObject(Map)

    // Get and validate the newly created subtask
    def subtask = resp.body

    // If the sub task created successfully return a success message along with its key
    if (resp.status >= 200 && resp.status < 300 && subtask && subtask.key != null) {
        logger.info('Success - Sub Task Created with the key of ' + resp.body.key.toString())
    } else {
        logger.error("${resp.status}: ${resp.body}")
    }
}
Discovered an issue? Report it here

Suggested for you