Automating JIRA Ticket Creation with a Flask API: A GitHub Webhook Integration Guide

Automating JIRA Ticket Creation with a Flask API: A GitHub Webhook Integration Guide

Streamline your workflow by automatically generating JIRA tickets from GitHub issue comments using Python and Flask

·

8 min read

💡 Introduction

Welcome to the world of DevOps! Today, we are diving into an exciting project that bridges Jira and GitHub for seamless integration. The goal of this project is to automate the creation of Jira tickets directly from GitHub issue comments, saving time and reducing manual effort for developers.

Here’s how we’ll tackle this project:

  1. Set up a Flask API: We’ll launch a t2.micro Ubuntu-based EC2 instance to host our Flask application.

  2. Configure Jira: We’ll create a project on Jira and use its API for ticket creation.

  3. Integrate APIs: By providing a Jira API token to our Flask app, we’ll enable it to interact with Jira.

Once everything is set up, our Flask app will act as a webhook API for GitHub. Anytime a developer comments /jira on a GitHub issue, the program will automatically create a corresponding Jira ticket, visible on the Jira dashboard. Exciting, right? Let’s get started!


💡Pre-requisites

Before diving into the project, make sure you have the following ready:

  1. GitHub and Jira Accounts: You’ll need active accounts on both platforms to configure the integration.

  2. Flask Installed: Ensure Flask is set up in your Python environment. If not, you can install it using:

     pip install flask
    
  3. Basic Understanding of EC2 and Flask: Familiarity with setting up an EC2 instance and creating simple Flask applications will help you follow along smoothly.

With these prerequisites in place, you're all set to kickstart this project!


💡 Setting Up the EC2 Instance and Flask Application

Let’s begin the project by creating and setting up an EC2 instance for hosting our Flask application. Follow these steps:

Step 1: Create the EC2 Instance

  1. Navigate to the AWS EC2 Dashboard and create a new t2.micro Ubuntu-based instance.

  2. Name the instance jira-github-integration.

  3. Download the key-pair file for SSH access.

  4. Open port 5000 in the security group to access the flask application.

Step 2: SSH into the Instance

Use the downloaded key-pair file to SSH into the instance:

ssh -i your-key.pem ubuntu@<instance-public-ip>

Step 3: Set Up Python Environment

Run the following commands to install Python and Flask:

sudo apt update  
sudo apt install python3-pip python3-venv  
python3 -m venv myvenv  
source myvenv/bin/activate  # Activate the virtual environment  
pip3 install flask          # Install Flask in the virtual environment

This will set up all the necessary dependencies for the project.

Step 4: Create the Flask Application

  1. Create a new file named github_jira.py:

     nano github_jira.py
    
  2. Add the following content to the file:

     import requests
     from requests.auth import HTTPBasicAuth
     import json
     from flask import Flask, request
    
     app = Flask(__name__)
    
     # Define a route that handles POST requests
     @app.route('/createJira', methods=['POST'])
     def createJira():
         # The comment's body field in the GitHub payload
         comment_data = request.json.get("comment", {})
         comment_body = comment_data.get("body", "")
    
         # Check if the body field of the comment is "/jira"
         if comment_body == "/jira":
             print("Condition met. Proceeding with POST request...")
    
             # Jira API details
             url = "https://<Your-Atlassian-domain>/rest/api/3/issue"
             API_TOKEN = "<YOUR_API_TOKEN>"
             auth = HTTPBasicAuth("<YOUR_EMAIL_ADDRESSS_CONNECTED_TO_THE_ACCOUNT>", API_TOKEN)
    
             headers = {
                 "Accept": "application/json",
                 "Content-Type": "application/json"
             }
    
             payload = json.dumps({
                 "fields": {
                     "description": {
                         "content": [
                             {
                                 "content": [
                                     {
                                         "text": "Order entry fails when selecting supplier.",
                                         "type": "text"
                                     }
                                 ],
                                 "type": "paragraph"
                             }
                         ],
                         "type": "doc",
                         "version": 1
                     },
                     "project": {
                         "key": "<YOUR_KEY>"
                     },
                     "issuetype": {
                         "id": "<YOUR_ISSUE_ID>"
                     },
                     "summary": "Main order flow broken",
                 },
                 "update": {}
             })
    
             # POST request to create an issue in Jira
             response = requests.post(url, data=payload, headers=headers, auth=auth)
             print("POST request response:", response.status_code, response.text)
    
             # Return the response back
             return json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))
         else:
             print("No matching comment found. POST request will not be made.")
             return json.dumps({"error": "No matching comment found. POST request was not made."}, sort_keys=True, indent=4, separators=(",", ": "))
    
     if __name__ == '__main__':
         app.run(host='0.0.0.0', port=5000)
    

💡Generating an Atlassian API Token

Before running the github_jira.py script, we need two critical pieces of information:

  1. Atlassian API Token

  2. Your Atlassian Domain Name

Steps to Generate the Atlassian API Token:

  1. Log in to Your Atlassian Account:
    Visit Atlassian and log in with your credentials.

  2. Navigate to Account Settings:

    • Click on your profile picture or avatar in the top-right corner.

    • Select Account settings from the dropdown menu.

  3. Go to the Security Tab:

    • In the Account settings page, click on the Security tab.

    • Under the API tokens section, click on Create API token.

  4. Create a New API Token:

    • Provide a description (e.g., GitHub Jira Integration) and set an expiry date for the token if prompted.

    • Click Create and your API token will be generated.

  5. Copy the API Token:

    • Click the Copy button to copy the token.

    • Paste the token into the API_TOKEN variable in your github_jira.py script:

        API_TOKEN = "<Your-Generated-API-Token>"
      
  6. Add Your Atlassian Domain:
    Replace <Your-Atlassian-domain> in the url variable with your Atlassian domain name. For example, if your Jira dashboard URL is https://yourworkspace.atlassian.net, use yourworkspace.atlassian.net as the domain.


💡 Configuring Required Fields in the github_jira.py Script

Before running the script, you need to update a few important fields in the github_jira.py file to ensure the integration works seamlessly with your Jira account.

1. HTTP Basic Authentication (Email Address)

  • Replace the first parameter in the HTTPBasicAuth with the email address linked to your Jira account.

      auth = HTTPBasicAuth("<your-email-address>", API_TOKEN)
    

2. Project Key

  • The Project Key uniquely identifies the Jira project where the tickets will be created.

  • To find your project key:

    1. Go to the Jira Dashboard.

    2. Under the Projects tab, locate the project where tickets will be created.

    3. The project key is displayed in simple brackets (()). For example, in the project Project ABC [SCRUM], the key is AB.

  • Replace the "key" field under fields in the script:

      "project": {
          "key": "YOUR_KEY"  # Replace 'YOUR_KEY' with your project key
      }
    

3. Issue Type ID

  • The issue type ID is a unique identifier for the type of issue (e.g., Bug, Story, Task).

  • To find the issue ID:

    1. In your Jira dashboard, click the three dots in the top-right corner and select Manage Custom Fields.

    2. In the Project Settings, navigate to Issue Types from the left-hand menu.

    3. Click on Story or the issue type you want to use.

    4. Look at the URL in your browser. At the end of the URL, you’ll find a numeric value (e.g., 10005). This is your issue type ID.

  • Replace the "id" field under issuetype in the script:

      "issuetype": {
          "id": "YOUR_ID"  # Replace 'YOUR_ID' with your issue type ID
      }
    

Example of Updated Fields in the Script:

auth = HTTPBasicAuth("your-email@example.com", API_TOKEN)  # Replace with your email and API token

payload = json.dumps({
    "fields": {
        "description": {
            "content": [
                {
                    "content": [
                        {
                            "text": "Order entry fails when selecting supplier.",
                            "type": "text"
                        }
                    ],
                    "type": "paragraph"
                }
            ],
            "type": "doc",
            "version": 1
        },
        "project": {
            "key": "AB"  # Replace 'AB' with your project key
        },
        "issuetype": {
            "id": "10005"  # Replace '10005' with your issue type ID
        },
        "summary": "Main order flow broken",
    },
    "update": {}
})

Final Step: Run the Script

Once these fields are updated, run the script using:

python github_jira.py

Your script is now fully configured and ready to integrate GitHub comments with Jira ticket creation!


💡Adding the Webhook to Complete the Integration

Now that our script is ready, the final step is to configure a webhook in your GitHub repository. This webhook will listen for specific events (in this case, issue comments) and trigger the Flask application.

Steps to Add the Webhook:

  1. Navigate to the GitHub Repository:
    Open the GitHub repository where you want to test this project.

  2. Access Repository Settings:

    • Click on the Settings tab located in the repository menu.

    • In the left-hand navigation bar, select Webhooks under the "Code and automation" section.

  3. Add a New Webhook:

    • Click on the Add webhook button.
  4. Configure the Webhook:

    • Payload URL:
      Enter the URL of your Flask application. This should include your EC2 instance's public DNS and the route for the Flask endpoint:

        http://<YOUR-EC2-INSTANCE-PUBLIC-DNS>:5000/createJira
      
    • Content Type:
      Select application/json from the dropdown menu.

    • Triggers:

      • Select the option "Let me select individual events".

      • Check the box for Issue comments only.

  5. Save the Webhook:

    • Click the Add Webhook button to save your settings.

Testing the Integration

  1. Create an Issue on GitHub:

    • Navigate to the Issues tab of your repository.

    • Click on New Issue, provide a title and description, and save it.

  2. Comment on the Issue:

    • Open the created issue and add a comment with /jira.
  3. Observe the Magic:

    • The webhook will trigger and send a POST request to the Flask server.

    • The Flask application will process the request and create a Jira ticket using the Jira API.

  4. Verify on the Jira Dashboard:

    • Open your Jira dashboard and navigate to the project specified in your script.

    • You should see a newly created ticket corresponding to the GitHub issue comment.


💡Conclusion

Congratulations! 🎉 You've successfully completed a hands-on project integrating GitHub and Jira. By leveraging a Flask application as an intermediary, we automated the process of creating Jira tickets directly from GitHub issue comments.

In this project, we covered:

  • Setting up an EC2 instance to host a Flask app.

  • Configuring the Flask app to interact with the Jira API.

  • Creating and adding a GitHub webhook to trigger the workflow.

  • Observing the seamless creation of Jira tickets from GitHub comments.

This integration simplifies collaboration between developers and project managers by reducing manual effort and ensuring that important tasks don't slip through the cracks. It’s a practical demonstration of how automation can enhance productivity in a DevOps workflow.

Feel free to build upon this foundation to customize the integration further or explore additional use cases, such as automating GitHub Pull Request tracking in Jira or integrating other tools into your workflow.

We hope you found this project informative and engaging. 🚀 For more informative blog, Follow me on Hashnode, X(Twitter) and LinkedIn.

Happy coding and automating! 🚀

Did you find this article valuable?

Support Pravesh's blog by becoming a sponsor. Any amount is appreciated!

Â