Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

I need a script that will create a Jira issue in a specific project automatically

Christopher LeJeune
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
May 28, 2019

I know that Jira has a REST API interface. I don't have much experience querying API's. I'm looking for a quick bash or python script that I can use to create a ticket in the DevOps project for the Deployment issue type. That is all. I know this is probably an easy thing to do but I don't know how to do it. This script will be triggered through an automatic pipeline in gitlab.

 

This is the script we are using for Redmine, I need something similar for Jira:

 

#!/usr/bin/env bash
GIT_COMMIT=`git rev-parse HEAD`

REDMINE_DATA="{\"issue\":{\"project_id\":1,\"tracker_id\":4,\"status_id\":1,\"priority_id\":2,\"subject\":\"${CI_PROJECT_NAME} Deploy to Prod ${CI_COMMIT_TAG} (migrations: yes, seeds: no)\",\"description\":\"[![build status](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/badges/${CI_COMMIT_TAG}/build.svg)](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/commits/${CI_COMMIT_TAG})[![tag](https://img.shields.io/badge/release-v${CI_COMMIT_TAG}-blue.svg)](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/tree/${CI_COMMIT_TAG})[![tag](https://img.shields.io/badge/SHA-${GIT_COMMIT}-blue.svg)](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/tree/${CI_COMMIT_TAG})\",\"done_ratio\":0,\"spent_hours\":0.0,\"total_spent_hours\":0.0,\"custom_fields\":[{\"id\":18,\"name\":\"GitHub Code Reviewed\",\"value\":\"1\"},{\"id\":9,\"name\":\"QA Verified\",\"value\":\"1\"},{\"id\":10,\"name\":\"PO Approved\",\"value\":\"0\"},{\"id\":11,\"name\":\"Business Signoff\",\"value\":\"0\"},{\"id\":20,\"name\":\"Ops Approved\",\"value\":\"0\"},{\"id\":21,\"name\":\"Manager Approved\",\"value\":\"0\"},{\"id\":13,\"name\":\"Commits For Approval\",\"value\":\"${GIT_COMMIT}\"},{\"id\":17,\"name\":\"Deployment Completion Date\",\"value\":\"\"},{\"id\":16,\"name\":\"Verification Date\",\"value\":\"\"},{\"id\":19,\"name\":\"Pivotal Tracker Task ID\",\"value\":\"None\"}]}}"

REDMINE_API_KEY_HEADER="X-REDMINE-API-KEY: ${REDMINE_API_KEY}"
echo curl -k -v -H "Content-Type: application/json" --header "REDMINE_API_KEY_HEADER" -X POST "${REDMINE_URL}" -d "$REDMINE_DATA"
curl -k -v -H "Content-Type: application/json" --header "${REDMINE_API_KEY_HEADER}" -X POST "${REDMINE_URL}" -d "$REDMINE_DATA"

5 answers

1 vote
Pete Singleton
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
May 28, 2019

Below is a simple Python script to create a basic 'Story' issue type in a project with key"ABC" using the REST API.  It should work, but some if the indentation may be corrupted as a copy/pasted....


from urllib2 import Request, urlopen, URLError
import sys
import json
import base64
import os

def jira_rest_call(data):

# Set the root JIRA URL, and encode the username and password
url = '<url>/rest/api/2/issue'
base64string = base64.encodestring('%s:%s' % ('username', 'password')).replace('\n','')

# Build the request
restreq = Request(url)
restreq.add_header('Content-Type', 'application/json')
restreq.add_header("Authorization", "Basic %s" % base64string)

# Send the request and grab JSON response
response = urlopen(restreq, data)

# Load into a JSON object and return that to the calling function
return json.loads(response.read())


# Build the text for the JIRA ticket.
jira_summary = 'This is the issue summary'
jira_description = 'This is the issue description'

# Build the JSON to post to JIRA
json_data = '''
{
"fields":{
"project":{
"key":"ABC"
},
"summary": "%s",
"components":[
{"name":"Component1"}
],
"issuetype":{
"name":"Story"
},
"description": "%s"
}
} ''' % (jira_summary, jira_description)

json_response = jira_rest_call(json_data)
parent_key = json_response['key']

print "Created parent issue ", parent_key


Christopher LeJeune
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
June 10, 2019

Sorry it has taken so long to get back to this. I can't get this script working. Let me give a little more detail and see if it helps. Right now we use giitlab for our test/deploy. When the app is deployed it is a docker image. During that pipeline process (currently) a script is run that auto-creates the ticket. That script is a curl command. This is our current script for Redmine that works. I need something similar for Jira.

 

#!/usr/bin/env bash
GIT_COMMIT=`git rev-parse HEAD`

REDMINE_DATA="{\"issue\":{\"project_id\":1,\"tracker_id\":4,\"status_id\":1,\"priority_id\":2,\"subject\":\"${CI_PROJECT_NAME} Deploy to Prod ${CI_COMMIT_TAG} (migrations: yes, seeds: no)\",\"description\":\"[![build status](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/badges/${CI_COMMIT_TAG}/build.svg)](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/commits/${CI_COMMIT_TAG})[![tag](https://img.shields.io/badge/release-v${CI_COMMIT_TAG}-blue.svg)](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/tree/${CI_COMMIT_TAG})[![tag](https://img.shields.io/badge/SHA-${GIT_COMMIT}-blue.svg)](https://gitlab.verisys.com/verisys/${CI_PROJECT_NAME}/tree/${CI_COMMIT_TAG})\",\"done_ratio\":0,\"spent_hours\":0.0,\"total_spent_hours\":0.0,\"custom_fields\":[{\"id\":18,\"name\":\"GitHub Code Reviewed\",\"value\":\"1\"},{\"id\":9,\"name\":\"QA Verified\",\"value\":\"1\"},{\"id\":10,\"name\":\"PO Approved\",\"value\":\"0\"},{\"id\":11,\"name\":\"Business Signoff\",\"value\":\"0\"},{\"id\":20,\"name\":\"Ops Approved\",\"value\":\"0\"},{\"id\":21,\"name\":\"Manager Approved\",\"value\":\"0\"},{\"id\":13,\"name\":\"Commits For Approval\",\"value\":\"${GIT_COMMIT}\"},{\"id\":17,\"name\":\"Deployment Completion Date\",\"value\":\"\"},{\"id\":16,\"name\":\"Verification Date\",\"value\":\"\"},{\"id\":19,\"name\":\"Pivotal Tracker Task ID\",\"value\":\"None\"}]}}"

REDMINE_API_KEY_HEADER="X-REDMINE-API-KEY: ${REDMINE_API_KEY}"
echo curl -k -v -H "Content-Type: application/json" --header "REDMINE_API_KEY_HEADER" -X POST "${REDMINE_URL}" -d "$REDMINE_DATA"
curl -k -v -H "Content-Type: application/json" --header "${REDMINE_API_KEY_HEADER}" -X POST "${REDMINE_URL}" -d "$REDMINE_DATA"
Artem Grotskyi January 29, 2020

Hi @Pete Singleton ,

Thank you so much for the script!

Like Pete Singleton likes this
mahendra akhil July 16, 2020

Hi is there any way of integration of control m with jira using python

GOUTHAM KUMAR YELLRAPU November 4, 2020

from urllib.request import urlopen
from jira import jira
#import jira
import sys
import json
#import base64
import os
import urllib
import urllib3
import urllib3.request
#from gluon._compat import urlopen
#from gluon._compat import urllib3
import base64
import warnings
warnings.filterwarnings('ignore')

 

def jira_rest_call(data):

# Set the root JIRA URL, and encode the username and password
url = 'https://jirasandbox.rampgroup.com/rest/api/2/issue'
base64string = base64.encodestring('%s:%s' % ('xxxxxxx', 'xxxxx')).replace('\n','')

# Build the request
restreq = Request(url)
restreq.add_header('Content-Type', 'application/json')
restreq.add_header("Authorization", "Basic %s" % base64string)

# Send the request and grab JSON response
response = urlopen(restreq, data)

# Load into a JSON object and return that to the calling function
return json.loads(response.read())


# Build the text for the JIRA ticket.
jira_summary = 'This is the issue summary'
jira_description = 'This is the issue description'

# Build the JSON to post to JIRA
json_data = '''
{
"fields":{
"project":{
"key":"MY22 Info HMI SW (MIHS)"
},
"summary": "%s",
"components":[
{"name":"Component1"}
],
"issuetype":{
"name":"Story"
},
"description": "%s"
}
} ''' % (jira_summary, jira_description)

json_response = jira_rest_call(json_data)
parent_key = json_response['key']

print ("Created parent issue ", parent_key)

 

this code is getting errors @Christopher LeJeune @Amit Kundu @mahendra akhil @Artem Grotskyi @Matt Doar  @Pete Singleton

please help me

Artem Grotskyi November 4, 2020

Hi @GOUTHAM KUMAR YELLRAPU ,

I was using this script to create a ticket in Jira.
Replace JIRA_NAME and USER_NAME and also generate an API token



from
urllib2 import Request, urlopen, URLError
import sys
import json
import base64
import os
import datetime

# Jira settings
JIRA_URL = "https://JIRA_NAME.atlassian.net"

JIRA_USERNAME = "USER_NAME"
JIRA_PASSWORD = "" # For Jira Cloud use a token generated here: https://id.atlassian.com/manage/api-tokens

JIRA_PROJECT_KEY = "TEST"
JIRA_ISSUE_TYPE = "Story"


def jira_rest_call(data):

# Set the root JIRA URL, and encode the username and password
url = JIRA_URL + '/rest/api/2/issue'
base64string = base64.encodestring('%s:%s' % (JIRA_USERNAME, JIRA_PASSWORD)).replace('\n','')

# Build the request
restreq = Request(url)
restreq.add_header('Content-Type', 'application/json')
restreq.add_header("Authorization", "Basic %s" % base64string)

# Send the request and grab JSON response
response = urlopen(restreq, data)

# Load into a JSON object and return that to the calling function
return json.loads(response.read())


def generate_summary():
return "Summary - " + '{date:%Y-%m-%d %H:%M}'.format(date=datetime.datetime.now())


def generate_description(data):
return data


def generate_issue_data(summary, description):
# Build the JSON to post to JIRA
json_data = '''
{
"fields":{
"project":{
"key":"%s"
},
"summary": "%s",
"issuetype":{
"name":"%s"
},
"description": "%s"
}
} ''' % (JIRA_PROJECT_KEY, summary, JIRA_ISSUE_TYPE, description)
return json_data


json_response = jira_rest_call(generate_issue_data(generate_summary(), generate_description("TEST DESCRIPTION")))
issue_key = json_response['key']
print "Created issue ", issue_key

.
 

GOUTHAM KUMAR YELLRAPU December 8, 2020

Hello @Artem Grotskyi   Still I am getting error please can you share your Email Id with me.

0 votes
Amit Kundu
I'm New Here
I'm New Here
Those new to the Atlassian Community have posted less than three times. Give them a warm welcome!
October 21, 2020

I am using the above mentioned script to create JIRA through python. But facing the below issue and am not able to navigate through this. 

 

Traceback (most recent call last):

  File "CreateJIRA.py", line 46, in <module>

    json_response = jira_rest_call(json_data)

  File "CreateJIRA.py", line 19, in jira_rest_call

    response = urlopen(restreq, data)

  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen

    return _opener.open(url, data, timeout)

  File "/usr/lib/python2.7/urllib2.py", line 406, in open

    response = meth(req, response)

  File "/usr/lib/python2.7/urllib2.py", line 519, in http_response

    'http', request, response, code, msg, hdrs)

  File "/usr/lib/python2.7/urllib2.py", line 444, in error

    return self._call_chain(*args)

  File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain

    result = func(*args)

  File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default

    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)

urllib2.HTTPError: HTTP Error 400:

 

Any help will be appreciated.

0 votes
GOUTHAM KUMAR YELLRAPU October 17, 2020

@Pete Singleton  can  you help me please

0 votes
GOUTHAM KUMAR YELLRAPU October 16, 2020

Hi I am getting error when I was use above code, please help me anyone @Pete Singleton @mahendra akhil 

this is my email id gkumar.y97@gmail.com

0 votes
Matt Doar
Community Champion
May 28, 2019

Lots of examples for the jira python library at https://jira.readthedocs.io/en/master/

Suggest an answer

Log in or Sign up to answer