Automating Jira with Python
Python Automation Script for Creating JIRA Subtasks
Overview
This guide outlines the creation of a Python script designed to automate the creation of subtasks in JIRA. The script supports two modes of operation: creating predefined "standard" subtasks and creating custom subtasks based on user input.
Requirements
- Python 3
- requests library (pip install requests)
- JIRA Personal Access Token (PAT)
- config.ini file for sensitive and configurable data
Key Features
- Standard Subtasks Creation: Allows the creation of multiple predefined subtasks with a single command.
- Custom Subtasks Creation: Supports creating a subtask with specific details provided via command line arguments.
- Dynamic Parent Issue Specification: Enables specifying the parent issue key for standard subtasks dynamically via command line arguments.
Script Components
Configuration Management
Sensitive data like JIRA URL and PAT are stored in a config.ini file, enhancing security and making the script easily configurable.
config.ini Example:
iniCopy code
[DEFAULT]
JiraUrl = https://yourjiradomain.atlassian.net
PersonalAccessToken = YourPersonalAccessToken
Functions
- create_subtask: Makes an HTTP POST request to the JIRA API to create a subtask. It takes parameters such as project key, parent issue key, summary, description, and issue type ID.
- create_standard_subtasks: Uses predefined parameters to create a set of standard subtasks under a specified parent issue.
- main: Orchestrates the script's flow, handling command line arguments to determine the operation mode (standard or custom subtask creation) and executing the appropriate function.
Usage Instructions
- Standard Subtasks: Run python script.py standard PARENT_ISSUE_KEY to create predefined subtasks under the specified parent issue.
- Custom Subtask: Run python script.py PROJECT_KEY PARENT_ISSUE_KEY "Subtask Summary" "Subtask Description" ISSUE_TYPE_ID to create a subtask with custom details.
Script Modifications for Advanced Use Cases
- Dynamic Parent Issue Key: The script has been adapted to accept the parent issue key as a command line argument for standard subtasks, allowing for greater flexibility.
- Error Handling and Logging: Basic error handling and logging are implemented, ensuring the script can gracefully manage failures and provide useful execution feedback.
Conclusion
This Python script provides a versatile tool for automating the creation of subtasks in JIRA, streamlining project management tasks. By accommodating both standard and custom subtask creation, it offers flexibility to fit various workflows and project requirements.
import requests
import json
import logging
import sys
from configparser import ConfigParser
# Setup logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
# Read configurations
config = ConfigParser()
config.read("config.ini")
JIRA_URL = config.get("DEFAULT", "JiraUrl")
PAT = config.get("DEFAULT", "PersonalAccessToken")
HEADERS = {
"Authorization": f"Bearer {PAT}",
"Accept": "application/json",
"Content-Type": "application/json",
}
def create_subtask(project_key, parent_issue_key, summary, description, issue_type_id):
"""Create a subtask in JIRA."""
data = {
"fields": {
"project": {"key": project_key},
"parent": {"key": parent_issue_key},
"summary": summary,
# "description": description,
"issuetype": {"id": issue_type_id},
}
}
response = requests.post(
f"{JIRA_URL}/rest/api/2/issue/", headers=HEADERS, data=json.dumps(data)
)
if response.status_code == 201:
logging.info("Subtask created successfully.")
return response.json()
else:
logging.error(
f"Failed to create subtask. Status code: {response.status_code}, Response: {response.text}"
)
return None
def create_standard_subtasks(parent_issue_key):
standard_subtasks = [
{
"summary": "Initial analysis for the ticket requirements",
"issue_type_id": "5",
},
{
"summary": "Coding | Development process",
"issue_type_id": "5",
},
{
"summary": "Fixing | Creating unit tests",
"issue_type_id": "5",
},
{
"summary": "Code Review | PR for the ticket",
"issue_type_id": "5",
},
{
"summary": "QA - Steps to test the ticket.",
"issue_type_id": "5",
},
{
"summary": "Show to Greg for approval",
"issue_type_id": "5",
},
{
"summary": "Merge the PR - Deployment to Production",
"issue_type_id": "5",
},
]
for subtask in standard_subtasks:
create_subtask(
"TRIF",
parent_issue_key,
subtask["summary"],
"", # description
subtask["issue_type_id"],
)
def main():
if len(sys.argv) > 1 and sys.argv[1].lower() == "standard":
parent_issue_key = sys.argv[2]
result = create_standard_subtasks(parent_issue_key)
if result:
logging.info(f"Standard subtask created with Key: {result['key']}")
else:
if len(sys.argv) < 6:
logging.error(
"For custom subtask, usage: script.py <project_key> <parent_issue_key> <summary> <description> <issue_type_id>"
)
logging.info(
"Or, use 'standard' to create a standard subtask with predefined parameters."
)
sys.exit(1)
project_key, parent_issue_key, summary, description, issue_type_id = sys.argv[
1:6
]
result = create_subtask(
project_key, parent_issue_key, summary, description, issue_type_id
)
if result:
logging.info(f"Custom subtask created with Key: {result['key']}")
if __name__ == "__main__":
main()