Snippets

Marco delete all jira comments from issue

Created by Marco
'''
This script removes all comments from a specified jira issue

Please provide Jira-Issue-Key/Id, Jira-URL, Username, PAssword in the variables below.
'''

import sys
import json
import requests
import urllib3

# Jira Issue Key or Id where comments are deleted from
JIRA_ISSUE_KEY = 'TST-123'

# URL to Jira
URL_JIRA = 'https://jira.contoso.com'

# Username with enough rights to delete comments
JIRA_USERNAME = 'admin'
# Password to Jira User
JIRA_PASSWORD = 'S9ev6ZpQ4sy2VFH2_bjKKQAYRUlDfW7ujNnrIq9Lbn5w'

''' ----- ----- Do not change anything below ----- ----- '''

# Ignore SSL problem (certificate) - self signed
urllib3.disable_warnings()

# get issue comments:
# https://developer.atlassian.com/cloud/jira/platform/rest/#api-api-2-issue-issueIdOrKey-comment-get
URL_GET_COMMENT = '{0}/rest/api/latest/issue/{1}/comment'.format(URL_JIRA, JIRA_ISSUE_KEY)

# delete issue comment:
# https://developer.atlassian.com/cloud/jira/platform/rest/#api-api-2-issue-issueIdOrKey-comment-id-delete
URL_DELETE_COMMENT = '{0}/rest/api/2/issue/{1}/comment/{2}'

def user_yesno():
    ''' Asks user for input yes or no, responds with boolean '''
    allowed_response_yes = {'yes', 'y'}
    allowed_response_no = {'no', 'n'}

    user_response = input().lower()
    if user_response in allowed_response_yes:
        return True
    elif user_response in allowed_response_no:
        return False
    else:
        sys.stdout.write("Please respond with 'yes' or 'no'")
        return False

# get jira comments
RESPONSE = requests.get(URL_GET_COMMENT, verify=False, auth=(JIRA_USERNAME, JIRA_PASSWORD))

# check if http response is OK (200)
if RESPONSE.status_code != 200:
    print('Exit-101: Could not connect to api [HTTP-Error: {0}]'.format(RESPONSE.status_code))
    sys.exit(101)

# parse response to json
JSON_RESPONSE = json.loads(RESPONSE.text)

# get user confirmation to delete all comments for issue
print('You want to delete {0} comments for issue {1}? (yes/no)' \
    .format(len(JSON_RESPONSE['comments']), JIRA_ISSUE_KEY))
if user_yesno():
    for jira_comment in JSON_RESPONSE['comments']:
        print('Deleting Jira comment {0}'.format(jira_comment['id']))

        # send delete request
        RESPONSE = requests.delete(
            URL_DELETE_COMMENT.format(URL_JIRA, JIRA_ISSUE_KEY, jira_comment['id']),
            verify=False, auth=(JIRA_USERNAME, JIRA_PASSWORD))

        # check if http response is No Content (204)
        if RESPONSE.status_code != 204:
            print('Exit-102: Could not connect to api [HTTP-Error: {0}; {1}]' \
            .format(RESPONSE.status_code, RESPONSE.text))
            sys.exit(102)

else:
    print('User abort script...')

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.