class Importer(object): def __init__(self): username = config.JIRA_USERNAME password = config.JIRA_PASSWORD server = config.JIRA_SERVER project = config.JIRA_PROJECT self.jira = JIRA(basic_auth=(username, password), options={'server': server}) self.project = project def import_users(self, verbose=False): for jira_user in self._fetch_users(): user = create_user(jira_user) if verbose: print 'created user: %s' % user.login def import_issues(self, verbose=False): for jira_issue in self._fetch_issues(): issue = create_issue(jira_issue) if verbose: print 'created issue: %s' % issue.key def _fetch_users(self): return self.jira.search_assignable_users_for_projects('', self.project) def _fetch_issues(self): return self.jira.search_issues( 'project=%s and (status=OPEN or status=CLOSED)' % self.project, maxResults=MAX_ISSUE_RESULTS)
def is_bug_open(cls, issue_id): """Checks if the JIRA issue is open. An issue is open if its status is not in the closed_statuses list, or if none of its labels are in the closed_labels list. """ log = logging.getLogger('RunnerLog') config = JiraTrackerConfig() issue = None try: # exceptions from requests can bubble up here jira = JIRA(options={'server': config.server}) # returns an Issue object; JIRAError on invalid id issue = jira.issue(issue_id) except JIRAError as error: log.info('Error getting issue from JIRA. ' 'JIRAError: {0}'.format(error)) except RequestException as error: log.info('Unable to connect to JIRA server {0}. ' 'RequestException: {1}'.format(config.server, error)) if cls._status_is_open(issue, config): return True elif cls._labels_are_open(issue, config): return True return False
def getJiraData(depNbr, envName): _jira = JIRA(options={'server':'https://jira/jira', 'verify':False} ,basic_auth=('svc.edw.queryservice','changeme')) try: _issue = _jira.issue('EDW-' + str(depNbr), expand='changelog', fields='customfield_10406,customfield_11814,customfield_11843,customfield_11839') except JIRAError as e: if e.status_code == 503: _jiraResults = lambda: None return None elif e.status_code == 404: _issue = _jira.issue('FSIT-' + str(depNbr), expand='changelog', fields='customfield_10406,customfield_11814,customfield_11843,customfield_11839') else: raise e _statusAll = ['Development', 'Code Review', '2nd Code Review', 'QA', 'Deployment'] _statusValid = ['Development', 'Code Review', '2nd Code Review', 'QA', 'Deployment'] if envName.lower() == 'dev' \ else ['QA', 'Deployment'] if envName.lower() in ['test'] \ else ['Deployment'] _jiraResults = getSignoff(_issue.changelog.histories, _statusValid, _statusAll) _jiraResults.statusValid = _statusValid _jiraResults.developerIds = {} if _issue.fields.customfield_11814 is not None: _jiraResults.developerIds.update({'Developer':_issue.fields.customfield_11814}) # if _issue.fields.customfield_11843 is not None: # _jiraResults.developerIds.update({'Code Review':_issue.fields.customfield_11843}) # if _issue.fields.customfield_11839 is not None: # _jiraResults.developerIds.update({'2nd Code Review':_issue.fields.customfield_11839}) _jiraResults.hotfixDate=dt.strptime(_issue.fields.customfield_10406, "%Y-%m-%d") if _issue.fields.customfield_10406 else None return _jiraResults
def search_jira_projects(request): key_cert_data = None with open('C:\dev\jira.pem', 'r') as key_cert_file: key_cert_data = key_cert_file.read() logger.debug('key_cert_data' + key_cert_data) oauth_dict = { 'access_token': 'srkLiVajV2EtYhHhgi2x8DJjpoqSyXaN', 'access_token_secret': 'qkjFBvRxAwAZb4ygpTObr1IhJfPmy0h1', 'consumer_key': 'simplicity', 'key_cert': key_cert_data } options = { 'server': 'https://itcsas.atlassian.net', } jira = JIRA(options=options, oauth=oauth_dict) # Get all projects viewable by anonymous users. projects_main = jira.projects() projects = [] for project in projects_main: print project.name projects.append(jira.project(project.id)) roles = jira.project_components(project.id) users = jira.search_assignable_users_for_projects('ajardila',project.key) logger.debug("Cantidad: " + str(users)) return render_to_response('jira_projects_list.html', {'projects': projects})
def run(self): printout("Running Bicho with delay of %s seconds" % (str(self.delay))) issues_per_query = 100 bugsdb = get_database(DBJiraBackend()) bugsdb.insert_supported_traker("jira", "4.1.2") trk = Tracker(self.url.split("-")[0], "jira", "4.1.2") dbtrk = bugsdb.insert_tracker(trk) serverUrl = self.url.split("/browse/")[0] query = "/si/jira.issueviews:issue-xml/" project = self.url.split("/browse/")[1] options_jira = { 'server': self.serverUrl } jira = JIRA(options_jira) if (project.split("-").__len__() > 1): bug_key = project project = project.split("-")[0] bugs_number = self.bugsNumber(jira) try: issue = jira.issue(bug_key,expand='changelog') self.analyze_bug_list(issue, self.serverUrl+'/browse/', bugsdb, dbtrk.id) except Exception, e: #printerr(e) print(e)
class SRJira: def __init__(self, server, userName, password): server = 'https://snapdeal.atlassian.net' userName = '******' password = '******' options = { 'server': server } self.jira = JIRA(options) self.jira = JIRA(basic_auth=(userName, password)) def verifyIssueOwner(self, issueId, emailId): jiraIssue = self.jira.issue(issueId) if jiraIssue.fields.assignee.emailAddress == emailId: print 'Issue ', issueId , ' belongs to correct owner ', emailId else: print 'Issue ', issueId , ' correct owner is ', jiraIssue.fields.assignee.emailAddress, 'please check!' sys.exit(1) def verifyIssueState(self, issueId, issueState): jiraIssue = self.jira.issue(issueId) if jiraIssue.fields.status.name == issueState: print 'Issue ', issueId , ' is in correct state ', issueState else: print 'Issue ', issueId , ' state is ', jiraIssue.fields.status.name, 'please check!' sys.exit(1) def updateIssue(self, issueId, commitMessage): jiraIssue = self.jira.issue(issueId) comment = 'A commit with %s is done using this JIRA' % commitId print comment self.jira.add_comment(jiraIssue, comment)
def get_jira_defects(self,server,auth,jsl,max_results=1000): jira=JIRA(server,auth) fields='issuetype,summary,assignee,reporter,status,priority,resolution,created,updated,components' issues=jira.search_issues(jsl,maxResults=max_results,fields=fields) list=[] for item in issues: hash={} hash['key']=item.key fids=item.fields for fid_name in fields.split(','): if fid_name == 'components': hash[fid_name]=fids.components[0].name else: attr=getattr(fids, fid_name) if str(type(attr))=="<type 'unicode'>": hash[fid_name]=attr elif attr!=None: hash[fid_name]=getattr(attr,'name') else: hash[fid_name]='None' list.append(hash) return list
def sync(types, verbose=False): "Refresh selected collections from JIRA." jira_project = config["jira.project"] jira_username = config["jira.username"] jira_password = config["jira.password"] jira_server = config["jira.server"] jira = JIRA(basic_auth=(jira_username, jira_password), options={"server": jira_server}) if "users" in types: User.drop_collection() # FIXME: can this come from config? for jira_user in jira.search_assignable_users_for_projects("", jira_project): try: user = create_user(jira_user) except: print "Error creating user: %s" % jira_user.name raise if verbose: print "created user: %s" % jira_user.name if "issues" in types: Issue.drop_collection() issues = jira.search_issues( "project=%s and (status=OPEN or status=CLOSED)" % jira_project, maxResults=MAX_ISSUE_RESULTS ) for jira_issue in issues: try: issue = create_issue(jira_issue) except: print "Error creating %s" % jira_issue.key raise if verbose: print "created issue: %s" % jira_issue.key
def main(): username = ENV['JIRA_USERNAME'] password = ENV['JIRA_PASSWORD'] host = ENV['JIRA_HOST'] jira = JIRA({'server': host}, basic_auth=(username, password)) query = 'assignee=currentUser() and status="In Progress"' in_progress = jira.search_issues(query) if len(in_progress) > 1: while True: for i, issue in enumerate(in_progress): print '{0}: {1}, {2}'.format(i + 1, issue.key, issue.fields.summary) n = raw_input('Please choose one of the above, [1-{0}]: '.format( len(in_progress))) try: n = int(n) active = in_progress[n - 1] except: print 'Not a valid choice' else: break else: active = in_progress[0] print 'Activating {0} for commit messages.'.format(active.key) with open(os.path.expanduser('~/.jiraissue'), 'w') as f: f.write("export JIRA_ISSUE='{0}'".format(active.key)) os.system('source ~/.jiraissue')
def is_bug_open(cls, issue_id): """Checks if the JIRA issue is open.""" log = logging.getLogger('RunnerLog') config = JiraTrackerConfig() issue = None try: # exceptions from requests can bubble up here jira = JIRA(options={'server': config.server}) # returns an Issue ojbect; JIRAError on invalid id issue = jira.issue(issue_id) except JIRAError as error: log.info('Error getting issue from JIRA. ' 'JIRAError: {0}'.format(error)) except RequestException as error: log.info('Unable to connect to JIRA server {0}. ' 'RequestException: {1}'.format(config.server, error)) status_name = None if issue: status_name = issue.fields.status.name closed_statuses = [x.lower() for x in config.closed_statuses] if status_name is None or status_name.lower() not in closed_statuses: return True return False
def getData(): options = {"server": "https://jira.server.com"} jira = JIRA(options=options, basic_auth=("user", "pass")) issues = jira.search_issues('status was Rejected DURING (startOfWeek(-1), startOfWeek()) AND "Team Lead" = myuser') rates = {} reasons = {} for issue in issues: issue = jira.issue(issue.key) name = str(issue.fields.customfield_10901.displayName) reason = str(issue.fields.customfield_14700) # Add name to rates set if name not in rates: rates[name] = 0 # Add reason name to reasons set if reason not in reasons: reasons[reason] = 0 rates[name] = rates[name] + 1 reasons[reason] = reasons[reason] + 1 mailInfo(rates, reasons) return
class Builds(object): def __init__(self, configfile='bamboo.cfg'): self.jira_user = '******' self.jira_password = '******' self.server_name = 'http://bamboo.rutube.ru:8085' parse_config(self, configfile) self.jira = JIRA({'server': self.server_name, 'rest_api_version': '1.0'}, basic_auth=(self.jira_user, self.jira_password)) @translate_resource_args def add_comment(self, build, body): data = { 'author': self.jira_user, 'content': body } url = self.jira._get_url('result/' + build + '/comment') r = self.jira._session.post(url, headers={'content-type':'application/json'}, data=json.dumps(data)) raise_on_error(r) @translate_resource_args def run_plan(self, plan, **extra_variables): params = None if extra_variables: params = {} for k, v in extra_variables.items(): params['bamboo.variable.%s' % k] = v url = self.jira._get_url('queue/%s' % plan) print "POST %s" % url r = self.jira._session.post(url, headers={'content-type':'application/json'}, params=params, data=json.dumps({})) raise_on_error(r)
class JiraService(IssueService): # A map of jira priorities to taskwarrior priorities priorities = {"Trivial": "L", "Minor": "L", "Major": "M", "Critical": "H", "Blocker": "H"} def __init__(self, *args, **kw): super(JiraService, self).__init__(*args, **kw) self.username = self.config.get(self.target, "jira.username") self.url = self.config.get(self.target, "jira.base_uri") self.query = "assignee=" + self.username + " AND status != closed and status != resolved" self.jira = JIRA( options={"server": self.config.get(self.target, "jira.base_uri")}, basic_auth=(self.username, self.config.get(self.target, "jira.password")), ) @classmethod def validate_config(cls, config, target): for option in ["jira.username", "jira.password", "jira.base_uri"]: if not config.has_option(target, option): die("[%s] has no '%s'" % (target, option)) IssueService.validate_config(config, target) def get_owner(self, issue): return True def annotations(self, issue): annotations = [] comments = self.jira.comments(issue) if comments is []: pass else: for comment in comments: created = date.fromtimestamp(time.mktime(time.strptime(comment.created[0:10], "%Y-%m-%d"))) annotations.append(self.format_annotation(created, comment.author.name, comment.body)) return dict(annotations) def issues(self): cases = self.jira.search_issues(self.query, maxResults=-1) log.debug(" Found {0} total.", len(cases)) return [ dict( description=self.description( title=case.fields.summary, url=self.url + "/browse/" + case.key, number=case.key.rsplit("-", 1)[1], cls="issue", ), project=case.key.rsplit("-", 1)[0], priority=self.priorities.get(get_priority(case.fields.priority), self.default_priority), **self.annotations(case.key) ) for case in cases ]
def main(): jira = JIRA() JIRA(options={'server': 'http://localhost:8100'}) projects = jira.projects() print projects for project in projects: print project.key
def log_failure(post, subject): """ Logs failures in redirecting [email protected] emails. This does not mean literal failure, but the email in question is not a [email protected] email and should be forwarded. Inputs: :post: copy of request.POST QueryDict """ if settings.DEBUG or hasattr(mail, 'outbox'): jira = [] else: try: jira = JIRA(options=settings.options, basic_auth=settings.my_agent_auth) except JIRAError: jira = [] # Pop from and headers from the post dict; from is used in a few places # and headers, text, and html need a small bit of special handling from_ = post.pop('from', '') if type(from_) == list: from_ = from_[0] headers = post.pop('headers', '') text = post.pop('text', '') html = post.pop('html', '') body = add_part('', 'from', from_, '') # These are likely to be the most important, so we can put them first for part in ['to', 'cc', 'subject', 'spam_score', 'spam_report']: body = add_part(body, part, post.pop(part, ''), ', ') # Add email body (text and html versions) body = add_part(body, 'text', text, '\n') body = add_part(body, 'html', html, '\n') for item in post.items(): if not item[0].startswith('attachment'): body = add_part(body, item[0], item[1], ', ') body = add_part(body, 'headers', headers, '\n') if jira: project = jira.project('MJA') issue = { 'project': {'key': project.key}, 'summary': subject, 'description': body, 'issuetype': {'name': 'Task'} } jira.create_issue(fields=issue) else: email = EmailMessage( subject=subject, body=body, from_email=from_, to=[settings.EMAIL_TO_ADMIN]) email.send()
def get_ea_open_issues(): search_query = """ project = 'Cloud DNS' AND priority = Blocker AND status not in (Closed, "Ready for Release") """ jira = JIRA(options=options) return jira.search_issues(search_query, maxResults=30000)
def upload(self, filename, project, excelSheet='Sheet1', column='Descrition'): jira = JIRA(jiraServer, basic_auth={jiraUser,jiraPassword}) df = pd.read_excel(fileName, sheetName=excelSheet) df = df[pd.notnull(df[column])] for i in df.index: jira.create_issue(project={'key': project}, summary=df[column][i], issuetype={'name' : 'Story'})
def getProjects(self): options = {'server': self.server} jira = JIRA(options,basic_auth=(self.username, self.password)) # a username/password tuple # Get the mutable application properties for this server (requires jira-system-administrators permission) props = jira.application_properties() projects = jira.projects() return projects
class JiraTicketProvider(TicketProvider): def __init__(self): for k in ['JIRA_AUTH_TOKEN', 'JIRA_AUTH_SECRET', 'JIRA_AUTH_PRIVATEKEY', 'JIRA_AUTH_ID', 'JIRA_URL']: if not hasattr(config, k): raise TicketProviderErrorResponse("No value for config.%s, no !ticket for you :(" % k) options = { 'server': config.JIRA_URL, } oauth = { 'access_token': config.JIRA_AUTH_TOKEN, 'access_token_secret': config.JIRA_AUTH_SECRET, 'consumer_key': config.JIRA_AUTH_ID, 'key_cert': config.JIRA_AUTH_PRIVATEKEY } self.url = "%s/" % config.JIRA_URL if not config.JIRA_URL.endswith('/') else config.JIRA_URL self.jira = JIRA(options=options, oauth=oauth) def route_command(self, subcommand, callback, args): if subcommand == "jql": return self.ticket_jql(callback, args) else: return super(JiraTicketProvider, self).route_command(subcommand, callback, args) def _format_issue(self, issue): return '%s: %s (%sbrowse/%s)' % (issue.key, issue.fields.summary, self.url, issue.key) def ticket_create(self, callback, args): return "create: not implemented yet" def ticket_search(self, callback, args): jql = "" for a in args: if jql: jql += " and " jql += '(summary ~ "%s" or description ~ "%s")' % (a, a) output = [] issues = self.jira.search_issues(jql, maxResults=5) if len(issues) == 0: output.append("No issues found matching '{term}'".format(term=' '.join(args))) else: for issue in issues: output.append(self._format_issue(issue)) return '\n'.join(output) def ticket_show(self, callback, args): issue_id = args[0] if re.match("[A-Za-z0-9]{0,4}-[0-9]+", issue_id): issue = self.jira.issue(issue_id, fields='summary') return self._format_issue(issue) else: return "%s does not match [A-Za-z0-9]{0,4}-[0-9]+ (not a valid JIRA issue id?)" % issue_id def ticket_jql(self, callback, args): return "jql: not implemented yet"
def get_jira(jira_config): options = { 'server': 'https://issues.apache.org/jira' } jira = JIRA(options=options,basic_auth=(jira_config['user'], jira_config['password'])) # (Force) verify the auth was really done jira_session=jira.session() if (jira_session is None): raise Exception("Failed to login to the JIRA instance") return jira
def __init__(self, server, userName, password): server = 'https://snapdeal.atlassian.net' userName = '******' password = '******' options = { 'server': server } self.jira = JIRA(options) self.jira = JIRA(basic_auth=(userName, password))
def update_jira(issue_name, pull_url, user, action, auth): """ Update a Jira issue to attach a pull request. """ jira = JIRA(options=JIRA_OPTIONS, basic_auth=auth) issue = jira.issue(issue_name) if action == 'opened' or action == 'reopened': if user in TRANSLATE_NAMES: user = TRANSLATE_NAMES['user'] status = JIRA_URL + issue_name + '\n' if not issue.fields.status.name in ACTIVE_STATUS: status += 'Jira not updated (state was not active or new)' elif issue.fields.customfield_10010 != None: status += 'Jira not updated (pull request already registered)' elif issue.fields.assignee is not None and \ issue.fields.assignee.name.lower() != user.lower(): status += 'Jira not updated (user does not match)' else: if issue.fields.assignee is None: jira.assign_issue(issue, user) issue.update(fields={'customfield_10010': pull_url}) if issue.fields.status.name != 'Active': jira.transition_issue(issue, '71') # Assign and schedule jira.transition_issue(issue, '81') # Attach Pull Request status += 'Jira updated' else: status = '' # Don't know if it was closed for accept or reject... return status
def connect_to_jira(self, JIRAUsername=None, JIRAPassword=None, options=None): """ Connect to a JIRA server. Arguments: | JIRAUsername (string) | (Optional) A JIRA Username you wish to authenticate with, will authorise with anonymous account if left empty | | JIRAPassword (string) | (Optional) If a username was specified and a password is not the user will be prompted for password at runtime | | options (dictionary) | (Optional) A dictionary of options that the JIRA connection will be initialied with | This must be called first to be able to do most JIRA actions such as creating a new issue and assigning users. When connecting to JIRA you may need to authenticate a user. This can be done by passing in Username and Password as parameters. However, should you wish to not have a sensitive password saved in a file, an option is available to not pass in a Password and a prompt will appear asking for the JIRA password at runtime. 'connect to jira' can be called on its own and will default options to: '{'rest_api_version': '2', 'verify': True, 'server': 'http://*****:*****@ssword | {'server': http://devjira01'} | """ if JIRAUsername is not None and (JIRAPassword is "" or JIRAPassword is None): JIRAPassword = getpass.getpass("\nJIRA Password: "******"\nAuthentication to JIRA unsuccessful. Ensure the user used has sufficient access and that Username and Password were correct\n\n" ) sys.exit(1) else: try: self.jira = JIRA(options=JIRAOptions, basic_auth=(str(JIRAUsername), str(JIRAPassword))) except: sys.__stdout__.write( "\nAuthentication to JIRA unsuccessful. Ensure the user used has sufficient access and that Username and Password were correct\n\n" ) sys.exit(1)
def __init__(self, jira_file): try: with open(jira_file) as jf: data = jf.read() data = yaml.safe_load(data) self.account = data['account'] self.password = data['password'] self.project = data['project'] self.server = data['server'] self.issue_type = data['issue_type'] self.url = data['url'] self.ip_proxy = data.get('ip_proxy') self.port_proxy = data.get('port_proxy') self.disable_transitions = data.get('disable_transitions', False) self.assignee = data.get('assignee', None) self.only_update_on_change = data.get('only_update_on_change', False) except KeyError as e: raise Exception( 'JIRA sync configuration missing required field: {}'.format(e)) except IOError as e: raise Exception( 'Error opening JIRA sync configuration file: {}'.format(e)) except yaml.scanner.ScannerError as e: raise Exception( 'JIRA sync configuration file contains malformed YAML: {}'. format(e)) try: options = {} options['verify'] = app.config.get('JIRA_SSL_VERIFY', True) proxies = None if (self.ip_proxy and self.port_proxy): proxy_connect = '{}:{}'.format(self.ip_proxy, self.port_proxy) proxies = {'http': proxy_connect, 'https': proxy_connect} elif (self.ip_proxy and self.port_proxy is None): app.logger.warn( "Proxy host set, but not proxy port. Skipping JIRA proxy settings." ) elif (self.ip_proxy is None and self.port_proxy): app.logger.warn( "Proxy port set, but not proxy host. Skipping JIRA proxy settings." ) self.client = JIRA(self.server, basic_auth=(self.account, self.password), options=options, proxies=proxies) # pylint: disable=E1123 except Exception as e: raise Exception("Error connecting to JIRA: {}".format( str(e)[:1024]))
def jira_issues(server_url, project_name): """ Get JIRA issue keys for a project on a server. Returns a list of IssueFields such as: [IssueFields(key='OSPR-456', labels=['Dedx'], issuetype=u'Sub-task'), IssueFields(key='OSPR-458', labels=[], issuetype=u'Pull Request Review')] """ jira = JIRA({'server': server_url}) issues = jira.search_issues('project = {}'.format(project_name), maxResults=None) return [extract_fields(iss) for iss in issues]
def get_tickets(equipment, closed): ''' Populate tickets for equipment ''' jira = JIRA(**options) _projects = settings.JIRA_TICKETING['projects'] _projects_defaults = settings.JIRA_TICKETING['projects_defaults'] # construct entire search string so we don't hammer the server repeatedly search_string = settings.JIRA_TICKETING['search_string'].replace('{}', '"%s"' % equipment.serial) if _projects: projects = [project.key for project in jira.projects() if project.key in _projects.keys()] _first = True search_string += ' AND (' for project in projects: if _first: search_string += ' ( ' _first = False else: search_string += ' ) OR ( ' search_string += 'project = "%s"' % project if not closed: try: _closed_string = _projects[project]['closed_string'] or _projects_defaults['closed_string'] except KeyError: _closed_string = _projects_defaults['closed_string'] search_string += ' AND status != "%s"' % _closed_string search_string += ' ) )' elif not closed: search_string += ' AND status != "%s"' % _projects_defaults['closed_string'] issues = list(jira.search_issues(search_string)) for issue in issues: name = issue.key try: _closed_string = _projects[issue.fields.project.key]['closed_string'] or _projects_defaults['closed_string'] except KeyError: _closed_string = _projects_defaults['closed_string'] if issue.fields.status.name == _closed_string.capitalize(): status = 'closed' else: status = 'open' # when Django 1.7 becomes the minimum required version, use update_or_create() instead here # (and then the trailing update of t.state and the t.save() will not be needed) t, created = Ticket.objects.get_or_create( name=name, defaults={ 'state': status, 'url': issue.permalink(), }, ) # if existing ticket retrieved by get_or_create(), url is static but state often won't be - update it manually t.state = status t.save() equipment.ticket_set.add(t) return equipment
def prepare(self): self.jira = JIRA( options={'server': self.config.get(self.short_name, 'server_url')}, basic_auth=(self.config.get(self.short_name, 'username'), self.config.get(self.short_name, 'password'))) # test try: self.jira.projects() except: logger.exception( 'Can not connect to JIRA, please check hamster-bridge.cfg')
def jira_issues(server_url, project_name): """ Get JIRA issue keys for a project on a server. Returns a list of IssueFields such as: [IssueFields(key='OSPR-456', labels=['Dedx'], issuetype=u'Sub-task'), IssueFields(key='OSPR-458', labels=[], issuetype=u'Pull Request Review')] """ jira = JIRA({'server': server_url}) issues = jira.search_issues(f'project = {project_name}', maxResults=None) return [extract_fields(iss) for iss in issues]
def connect(self): if self.c is None: self.c = JIRA(options={'server': self.conf.site.url}, basic_auth=(self.credentials.jira.username, self.credentials.jira.password)) logger.debug('created jira connection') else: logger.debug('jira connection exists') logger.debug('configured user: '******'actual user: ' + self.c.current_user())
def init_jira(self): if not self.__server: self.__server = raw_input("Enter JIRA server url: \n") if not self.__username or not self.__password: self.__username = raw_input("Enter JIRA username: "******"server": self.__server} self._auth = (self.__username, self.__password) self._jira = JIRA(self._options, basic_auth=self._auth) if not self._board_id: pprint.pprint(self._jira.boards()) self._board_id = raw_input("Enter Board Id: ")
def buscarIssueBHP(NomeProjeto): jira = JIRA(options) listaProjetos = listarNomeProjetosJira() listaSiglas = listarSiglaProjetosJira() for i in range(len(listaProjetos)): if NomeProjeto in listaProjetos[i]: itemProjeto = 'project=' + str(listaSiglas[i]) issue = jira.search_issues( '%s AND issuetype = Bug AND status = Closed ORDER BY created DESC' % itemProjeto ) #Falta ajustar a JQL de acordo com as necessidades return str(issue[0])
def listarNomeProjetosJira(): projectsName = [] jira = JIRA(options) projects = jira.projects() for i in range(len(projects)): # Laço para percorrer todos os projetos jra = jira.project( str(projects[i]) ) # retorna ao nome do projeto onde a sigla (str(projects[i]) foi passada como parâmetro projectsName.append( jra.name) # Adiciona em uma lista todos os nomes dos projetos return projectsName
def UpdateJiraTicket(jiraName, summary, description, priorityNum): jira = JIRA(server, basic_auth=(username, password)) issue = jira.issue(jiraName) issue.update( fields={ 'summary': summary, 'description': description, 'priority': { 'id': priorityNum } }) return
def __init__(self): self._logger = logging.getLogger('Jira') self._jira = JIRA( server=JIRA_CONFIG['url'], basic_auth=[JIRA_CONFIG['user'], JIRA_CONFIG['password']]) self._fields = JIRA_CONFIG.get('fields') self._project = JIRA_CONFIG.get('project') self._server = self._jira.client_info() self._logger.info("Using {} project on <{}>".format( self._project, self._server))
def get_robot(request): if request.method == 'GET': # issue = request.GET.getlist('value[]') print "Get Data : ", request.GET.get('value[]') ts_name = request.GET.get('tsName') print "Test Suit Name Is :", ts_name value = request.GET.get('value[]') issue = value.split(",") print len(issue) #print "robot file path :",r_path #print type(str(r_path)) if len(issue) > 0: url = settings.JIRA_URL username = settings.JIRA_USERNAME pwd = settings.JIRA_PWD print "%%%%%%%%%%%%%%%%%%%%%%" print url print username print pwd print "$$$$$$$$$$$$$$$$$$$" try: conn = JIRA(url, basic_auth=(username, pwd)) except Exception as err: print "*****************" print err print "*****************" raise Exception(err) issue_list_conns = [conn.issue(x) for x in issue] f = open( os.path.join(settings.BASE_DIR, "media", ''.join( map(str, issue_list_conns))) + ".robot", 'w') [ f.write(attach.get()) for x in issue_list_conns for attach in x.fields.attachment ] project = Project.objects.all()[0] ts_rq = TestRequest(user=request.user, project=project, test_suit_id=ts_name, test_file=f.name) ts_rq.save() f.close() # return HttpResponseRedirect(reverse('status_sort', args=('W',))) status = {'status': 1, 'message': "Successfully Inserted"} return HttpResponse(json.dumps(status)) return render(request, 'jira_testplan.html', {})
def log_to_jira( worklog ): config_path = os.path.expanduser( '~/.worklog/config.json' ) try: with open( config_path ) as json_data: auth_file = json.load( json_data ) try: options = { 'server': '{}'.format( auth_file['server'] ) } except KeyError: server = imput( '\nJira Server: ' ) options = { 'server': server } try: username = auth_file['username'] except KeyError: username = input( '\nJira Username: '******'password'] except KeyError: password = getpass() except OSError as e: if e.errno == errno.ENOENT: username = input( '\nJira Username: '******'{}-{}-{}T{}:{}:00.000-0400'.format( task.start.year, task.start.month, task.start.day, task.start.hour, task.start.minute ) ticket = jira.issue( task.ticket ) sys.stdout.write( '\nLogging {} to ticket {}\n'.format( time, ticket ) ) jira.add_worklog( issue = ticket, timeSpent = str( time ), started = datetime.strptime( started, '%Y-%m-%dT%H:%M:%S.000%z' ) )
def JIRA_Main(Object, Ticket_Summary, Ticket_Description): JIRA_Details = Load_Output(Object, "jira") if JIRA_Details: try: JIRA_Options={'server': JIRA_Details[1]} JIRA_Session=JIRA(options=JIRA_Options,basic_auth=(JIRA_Details[2], JIRA_Details[3])) JIRA_Session.create_issue(project={'key': JIRA_Details[0]}, summary=Ticket_Summary, description=Ticket_Description, issuetype={'name': JIRA_Details[4]}) logging.info(f"{Date()} - Common Library - New JIRA ticket created.") except Exception as e: logging.warning(f"{Date()} - Common Library - {str(e)}.")
def jiraauthfn(self, user, password, realm, environ=None): print 'u, p, r: %s, %s, %s' % (user, '*'*len(password), realm) try: j = JIRA(options = { 'server': self.jiraurl}, basic_auth=(user, password)) print 'login succeeded' if realm and realm != 'Hg Root': p = j.project(realm) print 'project found' except: print 'authentication failed' return False return True
def buscarIssueRDP(NomeProjeto): jira = JIRA(options) listaProjetos = listarNomeProjetosJira() listaSiglas = listarSiglaProjetosJira() for i in range(len(listaProjetos)): if NomeProjeto in listaProjetos[i]: itemProjeto = 'project=' + str(listaSiglas[i]) issue = jira.search_issues( '%s AND issuetype = Bug AND status = Closed ORDER BY created DESC' % itemProjeto ) #Falta ajustar a JQL de acordo com as necessidades #print("Field:", field_name, "Value:", issue.raw['fields'][field_name]) --Será necessário para usar na migração return str(issue[0])
def login(self, username, password): try: self.jira = JIRA(options={ 'server': self.base_url, 'check_update': False }, basic_auth=(username, password), get_server_info=False, validate=False) except JIRAError: raise JiraAuthenticationError('failure to authenticate') except RequestException: raise JiraInitializationError('failure to communicate with jira')
def connect_to_jira(): jira_options = {'server': 'http://<jira server>'} #try: jiraStr = '' jira = JIRA (options=jira_options, basic_auth=('<id>','<password>')) issues = jira.search_issues('issuetype=Change\ Notification') issue = issues[0] mydict = {'issue_id' : issue, 'summary' : issue.fields.summary, 'duration': issue.fields.customfield_18862, 'start_date': issue.fields.customfield_18865, 'end_date': issue.fields.customfield_18866, 'description': issue.fields.description, 'notification_type': issue.fields.customfield_18860, 'impacted_services': issue.fields.customfield_18867, 'team_responsible': issue.fields.customfield_11169 } #for key,value in mydict.items(): # print key, "=>", value subject = mydict['notification_type'], ":", mydict['summary'] message = """ Description: %(description)s Impacted Services: %(impacted_services)s Duration: %(duration)s Start Date/Time: %(start_date)s End Data/Time: %(end_date)s Team(s) Involved: %(team_responsible)s JIRA ID: %(issue_id)s """ % {'issue_id' : mydict['issue_id'], 'summary' : mydict['summary'], 'duration': mydict['duration'], 'start_date': issue.fields.customfield_18865, 'end_date': issue.fields.customfield_18866, 'description': issue.fields.description, 'notification_type': issue.fields.customfield_18860, 'impacted_services': issue.fields.customfield_18867, 'team_responsible': issue.fields.customfield_11169 } sendNotification(subject, message) #except Exception as e: # jira = None return jiraStr
def __init__(self, connection_name='unknown', url='unknown', user_name='unknown', password='******') -> None: self.possible_projects = [] # type: List[str] self.connection_name = connection_name self._url = url.rstrip('/') self._user = user_name self._pass = password self._wrapped_jira_connection = None # Internal representation is simply name of project. We have a 1:many mapping of JiraConnection # to JiraProjects, and cannot have multiple projects with the same name on a single JIRA underlying object. self._cached_jira_projects = {} # type: Dict[str, JiraProject] if connection_name == 'unknown': raise ConfigError( 'Got JiraConnection constructor call with no connection_name. Cannot use this.' ) # Create the JIRA connection, bailing if we have an error with auth try: if utils.unit_test: self._wrapped_jira_connection = TestWrappedJiraConnectionStub() else: self._wrapped_jira_connection = JIRA(server=self._url, basic_auth=(self._user, self._pass)) except JIRAError as je: if '401' in str(je.response): print( 'Received HTTP 401 response. Likely a mistyped local argus password. Try again.' ) elif '404' in str(je.response): print('Recieved HTTP 404 response with url: {}'.format(je.url)) else: print('Received HTTP error response. url: {} response: {}'. format(je.url, je.response)) print('Exiting due to failed Jira Connection attempt.') exit() if utils.unit_test: print( 'DEBUG MODE. JiraConnection stubbed to locally generated names. Will not save config changes nor query.' ) else: print('JIRA connection active for {}.'.format( self.connection_name)) self.save_config()
def __init__(self, **kwargs): self.description = None self.issue_aus = None self.issue_us = None self.issue_uk = None self.issue_es = None self.issue_de = None self.issue_fr = None self.issue_apac = None self.issue_mea = None self.create_aus = None self.create_us = None self.create_apac = None self.create_de = None self.create_mea = None self.create_fr = None self.create_es = None self.create_uk = None self.options = { 'server': 'https://neomediaworld.atlassian.net', 'verify': False } self.client = None if len(kwargs) != 2: raise JiraException( 'In order to use this class you need to specify a user and a password as keyword arguments!' ) else: if 'username' in kwargs.keys(): self.username = kwargs['username'] else: raise JiraException( 'You need to specify a username as keyword argument!') if 'password' in kwargs.keys(): self.password = kwargs['password'] else: raise JiraException( 'You need to specify a password as keyword argument!') try: self.client = JIRA(self.options, basic_auth=(self.username, self.password)) except Exception: raise JiraException( 'Could not connect to the API, invalid username or password!' )
def removeHost(): """ This function used for removing host with host's name :return: string """ # logging settings logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.ERROR, filename=u'host_logs.log') # get jira's issue name from the link issueName = request.args['key'] # connect to the zabbix z = ZabbixAPI(SERVER_ZABBIX) z.login(user=LOGIN_ZABBIX, password=PASSWORD_ZABBIX) # connect to the jira jira_options = {'server': SERVER_JIRA} jira = JIRA(options=jira_options, basic_auth=(LOGIN_JIRA, PASSWORD_JIRA)) issue = jira.issue(str(issueName)) hostname = issue.fields.customfield_10001 + " - " + issueName if request.method == "POST": try: host = z.host.get(filter={"host": hostname}) except ZabbixAPIException: ze = ZabbixAPIException('No permissions to referred object or it does not exist!') print(ze) # permission error logs err_str = 'No permissions to referred object or it does not exist! ' + hostname logging.error(err_str) else: try: host_id = host[0]["hostid"] # z.host.delete(host_id) # delete host # deleting logs err_str = 'Host ' + hostname + ' successful removed' logging.info(err_str) except IndexError: out_of_range = IndexError("There is no host with this name") print(out_of_range) err_no_host_str = 'There is no host for delete' + hostname logging.error(err_no_host_str) else: print(' Do not used POST method') # connection error logs err_str = 'Do not used true method. Must be used method POST' logging.error(err_str) return 'host removed'
def main(): argv=parserArgument() global path path=argv.configpath jira_parameter=get_jira_parameter(argv.parameter) jira = JIRA({'server':"http://jira.micron.com/jira/"},basic_auth=(argv.user, argv.password)) try: new_issue=jira.create_issue(fields=jira_parameter) print "Jira Ticket is created successfully" print "the ticket id is: "+new_issue.key except Exception as e: print e
def main(): args = parse_arguments() rsa_key = read_file(args.rsa_path) jira = JIRA(options={'server': args.jira_server}, oauth={ 'access_token': args.token, 'access_token_secret': args.token_secret, 'consumer_key': args.consumer_key, 'key_cert': rsa_key }) for project in jira.projects(): print(project.key)
def create_ticket(first, last, email, topics, subject, question): f = open('.access', 'r') A = f.readlines() f.close() my_string_u = base64.b64decode(A[0].strip()).decode().strip() my_string_p = base64.b64decode(A[1].strip()).decode().strip() """ This function creates the ticket coming form the help form """ jira = JIRA( server="https://opensource.ncsa.illinois.edu/jira/", basic_auth=(my_string_u, my_string_p)) body = """ *ACTION ITEMS* - Please ASSIGN this ticket if it is unassigned. - PLEASE SEND AN EMAIL TO *%s* to reply to this ticket - COPY the answer in the comments section and ideally further communication. - PLEASE close this ticket when resolved *Name*: %s %s *Email*: %s *Topics*: %s *Question*: %s """ % (email, first, last, email, topics, question) issue = { 'project' : {'key': 'DESRELEASE'}, 'issuetype': {'name': 'Task'}, 'summary': 'Q: %s' % subject, 'description' : body, #'reporter' : {'name': 'desdm-wufoo'}, } temp = jira.create_issue(fields=issue) try: ticket = temp.key valid = True except: ticket = '' valid = False return valid, ticket
def connectJIRA(self, URL, user, password): log.debug('[research] : connecting to %s' % (URL)) basicauth = (user, password) try: self.jira = JIRA(options={'server': URL}, basic_auth=basicauth) self.connected = True log.debug('[research] : connected to %s' % (URL)) except JIRAError as jx: log.error('[research] jira.error : %s' % (jx)) except Exception as ex: log.debug('[research] exception : %s' % (ex)) finally: log.debug('[research] connection info (%s)' % (URL))
def login(self, jira_id, pwd, isSaveAccount): self.jira_id = jira_id self.pwd = pwd try: self.jira = JIRA(server=self.url, basic_auth=(jira_id, pwd)) except: return "failed" else: ## save session of login info to local file if isSaveAccount: self.saveSession() users = self.jira.search_users(jira_id) if len(users) == 1: ## found user return users[0] return None
def jiraGetIssueInfo(issueKey, config): jiraServer = config.get('jira', 'serverUrl') jiraOptions = { 'server': jiraServer } jiraUser = config.get('jira', 'user') jiraPassword = config.get('jira', 'password') # jira = JIRA(jiraOptions) jira = JIRA(options=jiraOptions, basic_auth=(jiraUser, jiraPassword)) issue = jira.issue(issueKey) jira.create_issue() return issue
def _init_jira_client(self): """Return Jira client. Returns: JIRA: jira-instance """ try: self.jira = JIRA(options={'server': self.host}, basic_auth=(self.username, self.password)) self.class_logger.info("Init jira client") return self.jira except Exception as err: self.class_logger.error("Exception: %s" % (err, )) self.class_logger.error("Cannot create jira instants") return None
def does_jira_exist(self, key_id): # we check for if a jira already exsists for this access key - we don't want to spam the users jira_options={'server': config["jira_server_address"]} jira_instance=JIRA(options=jira_options,basic_auth=(config["atlassian_api_email"],self.ATLASSIAN_API_TOKEN)) # using the jira sdk for python jql_query = 'status not in (Closed, Cancelled, Resolved, "In Progress") and description~"{}" and labels=AWS-User-Key-Rotation'.format(key_id[-5:]) issues_in_OPS = jira_instance.search_issues(jql_str=jql_query, maxResults=5) # query looks for any tickets that have this access key ID in it and are open # if we find a ticket regarding this expiring key id, then we change the global jira ticket url, otherwise we return false if issues_in_OPS == []: return False else: self.jira_ticket_url = "{}/browse/{}".format(config["jira_server_address"], issues_in_OPS[0]) return True
def lookup_jira(self, message, matches): issue_id = matches[0] jira = JIRA(options={'server': HOST}, basic_auth=(USERNAME, PASSWORD)) try: issue = jira.issue(issue_id) url = '{base}/browse/{id}'.format(base=HOST, id=issue_id) desc = '' env = '' if issue.fields.description: desc = issue.fields.description if issue.fields.environment: env = '\n{0}'.format(issue.fields.environment) return '{id}: {status}, assigned to {assignee} ({tags})\n{title}: {url}\n{desc}{env}'.format(id=issue_id.upper(), status=issue.fields.status.name, title=issue.fields.summary, desc=desc,url=url, tags=', '.join(issue.fields.labels), assignee=issue.fields.assignee.displayName, env=env) except Exception as e: pass
def updateTrackedTicketStatus(request): #connect to Jira try: connectionOptions = {'server':'http://jira.motionsoft.com:8080'} j = JIRA(connectionOptions, basic_auth = (jira_username, jira_password)) except: msg = 'could not connect to jira' return HttpResponse(msg, content_type = 'application/json') t = Ticket.objects.all() i = 0 jiraIssues = {} while i < len(t): ticket = t[i] if ticket.jira_issue: key, value = ticket.netsuite_case_number, ticket.jira_issue jiraIssues[key] = value i += 1 jiraSearch = {} i = 0 error = 'error' for key in jiraIssues: issue = str(jiraIssues[key]) if issue[:4] == 'MOSO': try: jiraIssue = j.issue(issue) status = jiraIssue.fields.status.name jiraSearch[key] = [issue, status] i += 1 except(JIRAError): thisError = 'error', i jiraSearch[thisError] = 'ya dun bunged up',i,'times' i += 1 for key in jiraSearch: try: thisUpdate = Ticket.objects.get(netsuite_case_number = key) thisUpdate.jira_issue_status = jiraSearch[key][1] thisUpdate.save() except: print 'could not find ticket to update with key: ',key t = Ticket.objects.all() js = json.dumps(jiraSearch,'json') t = serializers.serialize('json',list(t)) js = js + t return HttpResponse(js, content_type='application/json')
def jira_createTC(api_token,url,email,latest_data): jira = JIRA(options={'server': url}, basic_auth=(email, api_token)) for ind in latest_data.index: issue = jira.issue(latest_data['test_case_id'][ind]) summary = str(issue) + "_" + str(date.today()) print("Creating sub-task ", summary, "for Issue...", issue) issueDict = { 'project': {'key': 'DQT'}, 'summary': summary, 'issuetype': {'name': 'Sub-task'}, 'parent': {'key': issue.key}, } child = jira.create_issue(fields=issueDict) print("Created sub-task: " + child.key) jira_updateTC(api_token,url,email,child.key,latest_data['execution_result'][ind])
def __init__(self): if not hasattr(self, '_jira'): self._jira = JIRA( basic_auth=(JIRA_NAME, JIRA_PW), options={'server': JIRA_SERVER} ) self._issue = None
def setUp(self): super(IntegrationTestBase, self).setUp() self.jira_configured = True jira_env_settings = { 'username': '******', 'url': 'INTEGRATION_TESTING_URL', 'project': 'INTEGRATION_TESTING_PROJECT', 'password': '******', } self.jira_env = {} for key, env_var in jira_env_settings.items(): try: self.jira_env[key] = os.environ[env_var] except KeyError: raise SkipTest( "Integration tests require the following environment " "variables to be set: %s" % ( ', '.join( [v for k, v in jira_env_settings.items()] ) ) ) self.jira = JIRA( {'server': self.jira_env['url']}, basic_auth=( self.jira_env['username'], self.jira_env['password'], ) ) self.created_issues = [] self.path = tempfile.mkdtemp()
class JiraAPi: """ Simple class to update the status of a jira issue """ def __init__(self, username, password, server): options = {'server': server} self.jira = JIRA(options, basic_auth=(username, password)) def get_issue(self, issue_key): """ Returns issue object Useful fields: Who raised: issue.fields.reporter.displayName Priority: issue.fields.priority.name Status: issue.fields.status.name Title: issue.fields.summary Last Updated: issue.fields.updated """ return self.jira.issue(issue_key) def check_release_status(self, issue_key): """ Returns true if status is Approved """ issue = self.get_issue(issue_key) if issue.fields.status.name == 'Approved': return True return False