from pprint import pprint from atlassian import Jira JQL = 'project = DEMO AND status NOT IN (Closed, Resolved) ORDER BY issuekey' jira = Jira( url='http://localhost:8080', username='******', password='******') data = jira.jql(JQL) pprint(data)
# coding=utf-8 from atlassian import Jira jira = Jira(url="http://localhost:8080", username="******", password="******") def get_all_users(group, include_inactive=True): """ Get all users for group. If there more, than 50 users in group: go through the pages and append other users to the list :param group: :param include_inactive: :return: """ start = 0 users = jira.get_all_users_from_group( group, include_inactive_users=include_inactive, start=start) processed_data = { "group_name": group, "total": users["total"], "users": [{ "name": user["name"], "active": user["active"] } for user in users["values"]], } while "nextPage" in users: start += 50 users = jira.get_all_users_from_group( group, include_inactive_users=include_inactive, start=start)
print(answer) return answer requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.InsecureRequestWarning) options = {'server': 'https://jarvis2.atlassian.net', 'verify': False} client = Wit('5PA2VEZ7QB7BPVDMXNSY2W3VYPSLT3H6') jir = JIRA(options, basic_auth=('*****@*****.**', '48GCD07xfciUeR2n2qLj2C03')) atlassian = Jira(url='https://jarvis2.atlassian.net', username='******', password='******') def voice(text_data): import os import uuid audio_name = str(uuid.uuid1()) #espeak -v female3 -g 01ms -a 10 -p 45 -s 130 #espeak -ven+f4 -s150 s = "espeak -v female3 -g 01ms -a 10 -p 45 -s 130 '{}' --stdout > '{}'.mp3".format( text_data, audio_name) os.system(s)
#!/usr/bin/env python3 from atlassian import Jira jira_url = os.environ.get('JIRA_URL') jira_username = os.environ.get('JIRA_USERNAME') jira_password = os.environ.get('JIRA_PASSWORD') jira = Jira( url=jira_url, username=jira_username, # the password is the "basic auth token" available from # https://id.atlassian.com/manage-profile/security/api-tokens password=jira_password) JQL = 'assignee = \'{}\' AND resolution = Unresolved ORDER BY updated DESC'.format( jira_username) data = jira.jql(JQL) print(data)
# coding: utf8 from atlassian import Jira jira = Jira(url='http://localhost:8080', username='******', password='******') results = jira.tempo_account_get_customers() print("Count of Customers " + str(len(results))) for result in results: print(result.get('key'), ' ', result.get('name'))
def post(self, request, *args, **kwargs): """ 账号申请状态修改, 同意则创建对应的账号 1.内网SVN账号 2.内网GIT账号 3.内网JIRA账号 4.内网网盘账号 5.内网日志平台 6.生产日志平台 :param request: :return: """ data = json.loads(request.body.decode('utf-8'))['params'] if request.user.is_superuser: queryset = InnerAccount.objects.filter(id=data.get('id')).first() email = queryset.account_name username = UserInfo.objects.filter(email=email).values('username').first() password = RandCode.random_password() name = UserInfo.objects.filter(email=email).values('name').first() mobile = UserInfo.objects.filter(email=email).values('mobile').first() title = '帐号开通提醒' msg = '您申请的帐号已经开通, 用户名:%s, 请妥善保管(%s)密码!' % (str(email), str(password)) msg_en = 'Your account has been opened. User name: %s Please keep your password! (%s)' % ( str(email), str(password) ) if queryset.status == 2: # 待审核的状态 logger.info("当前申请的账号类型:%d" % int(queryset.account_type)) if queryset.account_type == AccountEnum.INNER_SVN_ACCOUNT.value: bro = SeleniumInit.create_windows(url=config('SVN_URL') + '/svnadmin/login.php') time.sleep(2) bro.find_element_by_id('loginname').send_keys(config('SVN_USER')) bro.find_element_by_id('loginpass').send_keys(config('SVN_PASS')) bro.find_element_by_class_name('addbtn').click() time.sleep(0.5) bro.get(url=config('SVN_URL') + '/svnadmin/usercreate.php') logger.info("开始创建svn用户:%s, 密码:%s" % (email, password)) bro.find_element_by_id('username').send_keys(email) bro.find_element_by_id('password').send_keys(password) bro.find_element_by_id('password2').send_keys(password) bro.find_element_by_xpath('//*[@id="textarea"]/div/form/div[4]/input').click() result_msg = bro.find_element_by_xpath('//*[@id="textarea"]/div[1]/div[2]/ul').text logger.info("开始加入Users用户组,加入的用户是:%s" % email) bro.get(url=config('SVN_URL') + '/svnadmin/usergroupassign.php') bro.find_element_by_xpath('//*[@id="textarea"]/form/table/tbody/tr/td[1]/div/input').send_keys(email) bro.find_element_by_xpath('//*[@id="selectallusers"]').click() bro.find_element_by_xpath('//*[@id="textarea"]/form/table/tbody/tr/td[3]/div/input').send_keys('user') bro.find_element_by_xpath('//*[@id="selectallgroups"]').click() bro.find_element_by_class_name('anbtn').click() result_group_msg = bro.find_element_by_xpath('//*[@id="textarea"]/div/div[2]/ul/li').text if 'successfully' in result_msg and 'is now a member of group user' in result_group_msg: queryset.status = 0 queryset.save() # TODO 邮件提醒, 任务状态暂未处理 url = 'http://svn.srv.pigs.com/svn/svn-repo' logger.info(msg + '开始发送异步通知') result = send_deploy_email.delay(email, name['name'], title, msg, msg_en, url, subject=title) logger.info('异步任务返回ID: %s, 状态: %s' % (str(result.id), str(result.state))) return JsonResponse(data={"msg": "SVN用户创建成功", "errcode": 0}) else: logger.error('SVN用户创建失败, status:400') return JsonResponse(data={"msg": "SVN用户创建失败!", "errcode": 1000}) elif queryset.account_type == AccountEnum.INNER_GIT_ACCOUNT.value: post_data = { "source_id": 0, "username": username['username'], # Gogs 账号只能以用户名创建 "email": email, "login_name": email, "password": password, } GOGS_TOKEN = config('GOGS_TOKEN') GOGS_HEADERS = { "Authorization": "token {0}".format(GOGS_TOKEN) } git_rsp = requests.post(url=str(config('GOGS_API')) + '/api/v1/admin/users', data=post_data, headers=GOGS_HEADERS) logger.info("创建Gogs用户返回状态码:%d" % git_rsp.status_code) git_rsp_content = git_rsp.content.decode('utf-8') logger.info("创建Gogs用户返回信息:%s" % str(git_rsp_content)) if git_rsp.status_code == 422: logger.error('Gogs http code: 422') return JsonResponse(data={ 'errcode': 422, 'msg': json.loads(git_rsp_content)['message'] }) elif git_rsp.status_code == 201: queryset.status = 0 queryset.save() logger.info('Gogs用户创建成功:%s, %s' % (email, password)) url = 'http://git.srv.pigs.com/' logger.info('发送钉钉异步通知') result = send_deploy_email.delay(email, name['name'], title, msg, msg_en, url, subject=title) logger.info('异步任务返回ID: %s, 状态: %s' % (str(result.id), str(result.state))) return JsonResponse(data={ 'errcode': 0, 'msg': "User created successfully" }) else: logger.error('Gogs创建失败, 返回状态码:%s' % str(git_rsp.status_code)) return JsonResponse(data={'msg': '服务异常!', "errcode": 500}, status=500) elif queryset.account_type == AccountEnum.INNER_JIRA_ACCOUNT.value: jira = Jira(url=config('JIRA_URL'), username=config('SVN_USER'), password=config('SVN_PASS')) logger.info("开始创建Jira平台账号:%s, 密码:%s" % (email, password)) try: jira_result = jira.user_create(email, email, name['name'], password=password) logger.info("创建Jira账号返回信息:%s" % str(jira_result)) logger.info("用户:%s, 加入的默认权限组:技术部" % email) # TODO 加入Group group_result = jira.add_user_to_group(email, "技术部") logger.info("返回信息,%s" % str(group_result)) queryset.status = 0 queryset.save() url = 'http://jira.srv.pigs.com/' logger.info('Jira用户创建成功, 发送异步通知') result = send_deploy_email.delay(email, name['name'], title, msg, msg_en, url, subject=title) logger.info('异步任务返回ID: %s, 状态: %s' % (str(result.id), str(result.state))) return JsonResponse(data={"msg": "Jira用户创建成功!", "errcode": 0}) except BaseException as e: logger.error("创建用户异常: %s" % str(traceback.format_exc())) return JsonResponse(data={"msg": "创建Jira用户失败", "errcode": 400}) elif queryset.account_type == AccountEnum.INNER_PAN_DISK_ACCOUNT.value: bro = SeleniumInit.create_windows(url=config('PAN_URL')) time.sleep(2) bro.find_element_by_id('id_email').send_keys(email) bro.find_element_by_id('id_password1').send_keys(password) bro.find_element_by_id('id_password2').send_keys(password) bro.find_element_by_class_name('submit').click() time.sleep(5) if '注册成功' in bro.find_element_by_xpath('//*[@id="main"]/div[1]/p').text: queryset.status = 0 queryset.save() url = 'http://pan.srv.pigs.com/accounts/login/?next=/' logger.info('网盘用户注册成功,请等待管理员激活!') result = send_deploy_email.delay(email, name['name'], title, msg, msg_en, url, subject=title) logger.info('异步任务返回ID: %s, 状态: %s' % (str(result.id), str(result.state))) return JsonResponse(data={"msg": "网盘用户注册成功,请等待管理员激活!", "errcode": 0}) else: logger.error('网盘用户创建失败: %s' % str(bro.find_element_by_xpath('//*[@id="main"]/div[1]/p').text)) return JsonResponse(data={"msg": "网盘用户创建失败!", "errcode": 1000}) elif queryset.account_type == AccountEnum.INNER_LOGS_ACCOUNT.value: headers = { "Content-Type": "application/json" } api_url = config('INNER_ELASTIC') + '/_shield/user/{}?pretty'.format(email) data = { "password": password, "roles": ["_test"], "full_name": name['name'], "email": email, } auth = HTTPBasicAuth(config('INNER_ELASTIC_USER'), config('INNER_ELASTIC_PASS')) logger.info("开始创建内网日志平台账号:%s" % data) kibana_result = requests.post(url=api_url, data=json.dumps(data), headers=headers, auth=auth) logger.info("创建内网日志平台账号返回信息:%s" % str(kibana_result.text)) if kibana_result.status_code == 200: queryset.status = 0 queryset.save() url = 'http://logs.develop.test.pigs.com/login' logger.info('内网日志平台用户创建成功, 开始发送异步通知') result = send_deploy_email.delay(email, name['name'], title, msg, msg_en, url, subject=title) logger.info('异步任务返回ID: %s, 状态: %s' % (str(result.id), str(result.state))) return JsonResponse(data={ "msg": "内网日志平台用户创建成功!", "errcode": 0 }) else: logger.error('创建内网日志平台用户失败: %s' % str(name)) return JsonResponse(data={"msg": "创建内网日志平台用户失败", "errcode": 1000}) elif queryset.account_type == AccountEnum.PROD_LOGS_ACCOUNT.value: headers = { "Content-Type": "application/json" } api_url = config('PROD_ELASTIC') + '/_shield/user/{}?pretty'.format(email) logger.info(api_url) data = { "password": password, "roles": ["dev_group"], "full_name": name['name'], "email": email, } auth = HTTPBasicAuth(config('PROD_ELASTIC_USER'), config('PROD_ELASTIC_PASS')) logger.info("开始创建生产环境日志平台账号:%s" % str(data)) kibana_result = requests.post(url=api_url, data=json.dumps(data), headers=headers, auth=auth) logger.info("创建生产环境日志平台账号返回信息:%s" % str(kibana_result.text)) if kibana_result.status_code == 200: queryset.status = 0 queryset.save() url = 'http://logs.prod.pigs.com/login' logger.info('生产环境日志平台用户创建成功, 发送异步通知') result = send_deploy_email.delay(email, name['name'], title, msg, msg_en, url, subject=title) logger.info('异步任务返回ID: %s, 状态: %s' % (str(result.id), str(result.state))) return JsonResponse(data={ "msg": "生产环境日志平台用户创建成功!", "errcode": 0 }) else: logger.error('创建生产环境日志平台用户失败, status: 400') return JsonResponse(data={"msg": "创建生产环境日志平台用户失败", "errcode": 400}) elif queryset.account_type == AccountEnum.PROD_DB_ACCOUNT.value: from utils.aliyun import AliYunInit aliyun = AliYunInit() _create_ram_user = aliyun.create_ram_user( user_name=username['username'], display_name=name['name'], mobile_phone=mobile['mobile'], email=email ) if not _create_ram_user: return JsonResponse(data={ "msg": "RAM用户创建失败!", "errcode": 1000 }) _update_login_profile = aliyun.update_login_profile(user_name=username['username'], password=password) if not _update_login_profile: return JsonResponse(data={ "msg": "更新RAM用户权限失败!", "errcode": 1000 }) _add_ram_user_to_group = aliyun.add_ram_user_to_group(user_name=username['username']) if not _add_ram_user_to_group: return JsonResponse(data={ "msg": "更新RAM用户权限失败!", "errcode": 1000 }) # _create_rds_account = aliyun.create_rds_account( # account_name=username['username'], # account_password=password, # account_desc=name['first_name'] # ) # if not _create_rds_account: # return JsonResponse(data={ # "msg": "创建RDS用户失败!", # "status": 400 # }) # # _grant_rds_account_privilege = aliyun.grant_rds_account_privilege(account_name=username['username']) # if not _grant_rds_account_privilege: # return JsonResponse(data={ # "msg": "更新RDS用户权限失败!", # "status": 400 # }) queryset.status = 0 queryset.save() url = 'https://signin.aliyun.com/login.htm' logger.info("用户名:%s, 密码:%s, 邮箱:%s" % (username['username'], password, email)) logger.info('RAM/RDS用户创建成功!, 发送异步通知') msg = '您申请的帐号已经开通, 用户名:%s, 请妥善保管(%s)密码!' % ( str(username['username'] + '@[替换成阿里云账号ID].onaliyun.com'), str(password)) msg_en = 'Your account has been opened. User name: %s Please keep your password! (%s)' % ( str(username['username'] + '@[替换成阿里云账号ID].onaliyun.com'), str(password) ) result = send_deploy_email.delay(email, name['name'], title, msg, msg_en, url, subject=title) logger.info('异步任务返回ID: %s, 状态: %s' % (str(result.id), str(result.state))) return JsonResponse(data={ "msg": "RAM/RDS用户创建成功!", "errcode": 0 }) else: return JsonResponse(data={'msg': '操作不合法!只有待审核的状态才可以创建', 'errcode': 1000}) else: return JsonResponse(data={'errcode': 403, 'msg': '你无权操作!'})
from pprint import pprint from atlassian import Jira jira = Jira( url='http://localhost:8080', username='******', password='******') data = jira.rename_sprint( sprint_id=10, name='Here is the name of my new sprint', start_date='2014-10-13 11:44', end_date='2014-10-20 09:34') pprint(data)
from pprint import pprint from atlassian import Jira jira = Jira( url="http://localhost:8000/", username="******", password="******") status = jira.reindex().json() pprint(status)
from atlassian import Jira import logging logging.basicConfig(level=logging.ERROR) jira = Jira(url='http://localhost:8080', username='******', password='******') """That example show how to copy group members into role members""" def convert_group_into_users_in_role(project_key, role_id, group_name): users = jira.get_all_users_from_group(group=group_name, limit=1000).get("values") for user in users: jira.add_user_into_project_role(project_key=project_key, role_id=role_id, user_name=user.get("name")) print( f"{user.get('name')} added into role_id {role_id} in {project_key}" ) group_name_to_find = "old-developers" roles = jira.get_all_global_project_roles() projects = jira.get_all_projects(included_archived=True) for project in projects: for role in roles: members_of_role = jira.get_project_actors_for_role_project( project.get("key"), role.get("id")) if not members_of_role: continue for member in members_of_role:
# coding: utf8 from atlassian import Jira jira = Jira( url="https://jira.example.com/", username='******', password='******') jira.issue_create(fields={ 'project': {'key': 'TEST'}, 'issuetype': { "name": "Task" }, 'summary': 'test rest', 'description': 'rest rest', })
# coding=utf-8 from urllib.parse import quote from atlassian import Jira jira = Jira(url="http://localhost:8080", username="******", password="******") EMAIL_SUBJECT = quote("Jira access to project {project_key}") EMAIL_BODY = quote( """I am asking for access to the {project_key} project in Jira. To give me the appropriate permissions, assign me to a role on the page: http://localhost:8080/plugins/servlet/project-config/{project_key}/roles Role: Users - read-only access + commenting Developers - work on tasks, editing, etc. Admin - Change of configuration and the possibility of starting sprints""") MAILTO = '<a href="mailto:{lead_email}?subject={email_subject}&body={email_body}">{lead_name}</a>' print("|| Project Key || Project Name || Ask for Access ||") for project in jira.project_leaders(): print("| {project_key} | {project_name} | {lead_email_link} |".format( project_key=project["project_key"], project_name=project["project_name"], lead_email_link=MAILTO.format(lead_name=project["lead_name"], lead_email=project["lead_email"]), ))
def connect_to_jira_api(api_token, server, user): jira = Jira(url=server, username=user, password=api_token, cloud=True) return jira
from atlassian import Jira jira = Jira(url="http://localhost:8080", username="******", password="******") issue_types = jira.get_issue_types() print("Enter projects category:") category = input() for i in issue_types: issue_type = i["name"] jql_all = 'issuetype = "{0}"'.format(issue_type) number = jira.jql(jql_all)["total"] jql_of_category = 'issuetype = "{0}" AND category = {1}'.format( issue_type, category) number_of_deprecated = jira.jql(jql_of_category)["total"] if number > 0: percent_of_deprecated = number_of_deprecated / number * 100 else: percent_of_deprecated = 0 percentage = round(percent_of_deprecated, 1) print("{0}, {1}, {2}% of {3}".format(issue_type, number, percentage, category))
def jira(porta): jira = Jira( url=jiraurl + ':' + porta, username='******', password= os.getenv("JIRA_SENHA_" + porta)) return jira
from pprint import pprint from atlassian import Jira jira = Jira(url='http://localhost:8080', username='******', password='******') data = jira.rename_sprint(sprint_id=10, name='Here is the name of my new sprint', start_date='2014-10-13 11:44', end_date='2014-10-20 09:34') pprint(data)
return None def get_project_notification_scheme_object( new_scheme="Archived Notification Scheme"): schemes = jira.get_all_notification_schemes() for scheme in schemes: if scheme.get("name") == new_scheme: return scheme return None if __name__ == "__main__": jira = Jira( url=environ.get("JIRA_URL"), username=environ.get("ATLASSIAN_USER"), password=environ.get("ATLASSIAN_PASSWORD"), ) # Setting the logging level. INFO|ERROR|DEBUG are the most common. logging.basicConfig(level=logging.INFO) # Initialize argparse module with some program name and additional information parser = argparse.ArgumentParser( prog="Jira Archive Projects", description="Simple execution of th project key") parser.add_argument("--project", dest="project", default="TEST", help="Jira project key") parser.add_argument("--category", dest="category", default="DEPRECATED",
#!/usr/bin/env python3 from pprint import pprint from time import sleep from atlassian import Jira jira = Jira(url="http://localhost:8080/", username="******", password="******") jira.reindex() while not jira.reindex_status()['success']: print('Still reindexing...') sleep(1) print('Done.')
from atlassian import Jira # This example shoes how to copy custom field value from on issue to another # define custom field id, in notation customfield_id custom_field_id = 'customfield_102589' source_issue_key = "TST-1" destination_issue_key = "TST-2" jira = Jira( url='http://localhost:8080', username='******', password='******') # get value and save customfield_value = jira.issue_field_value(source_issue_key, custom_field_id) # prepare data like this https://developer.atlassian.com/server/jira/platform/jira-rest-api-example-edit-issues-6291632 custom_field_preparation = {custom_field_id: customfield_value} # update custom field on destination issue jira.update_issue_field(destination_issue_key, custom_field_preparation)
from atlassian import Stash import config import logging import time PROJECT_KEY = 'PROJ' REPOS = ['repo1', 'repo2'] ACCEPTED_ISSUE_STATUSES = ["Closed", "Verified"] EXCLUDE_REPO_RULES = config.exclude_parameters LAST_COMMIT_CONDITION_IN_DAYS = 75 ATLASSIAN_USER = config.JIRA_LOGIN ATLASSIAN_PASSWORD = config.JIRA_PASSWORD logging.basicConfig(level=logging.ERROR) jira = Jira(url=config.JIRA_URL, username=ATLASSIAN_USER, password=ATLASSIAN_PASSWORD) stash = Stash(url=config.STASH_URL, username=ATLASSIAN_USER, password=ATLASSIAN_PASSWORD) flag = True time_now = int(time.time()) * 1000 delta_for_time_ms = LAST_COMMIT_CONDITION_IN_DAYS * 24 * 60 * 60 * 1000 commit_info_key = "com.atlassian.bitbucket.server.bitbucket-branch:latest-commit-metadata" out_going_pull_request = "com.atlassian.bitbucket.server.bitbucket-ref-metadata:outgoing-pull-request-metadata" branch_related_issues = "com.atlassian.bitbucket.server.bitbucket-jira:branch-list-jira-issues" def is_can_removed_branch(branch_candidate):
import urllib from atlassian import Jira jira = Jira( url='http://localhost:8080', username='******', password='******') EMAIL_SUBJECT= urllib.parse.quote('Jira access to project {project_key}') EMAIL_BODY = urllib.parse.quote('''Proszę o dostęp do projektu {project_key} w Jirze. Aby nadać mi odpowiednie uprawnienia przypisz mnie do roli na stronie: http://localhost:8080/plugins/servlet/project-config/{project_key}/roles Role: Users - dostęp tylko do odczytu + komentowanie Developers - praca na zadaniach, edycja itp. Admin - Zmiana konfiguracji oraz możliwość startowania sprintów''') MAILTO = '<a href="mailto:{lead_email}?subject={email_subject}&body={email_body}">{lead_name}</a>' print('|| Project Key || Project Name || Ask for Access ||') for project in jira.project_leaders(): print('| {project_key} | {project_name} | {lead_name} <{lead_email}> |'.format( project_key=project['project_key'], project_name=project['project_name'], email_subject=EMAIL_SUBJECT, email_body=EMAIL_BODY,
# coding=utf-8 from atlassian import Jira from pprint import pprint """ How to get server info with health check""" jira = Jira(url="https://jira.example.com/", username='******', password='******') pprint(jira.get_server_info(True))
# coding=utf-8 from atlassian import Jira jira = Jira(url="https://jira.example.com/", username="******", password="******") jira.issue_create( fields={ "project": { "key": "TEST" }, "issuetype": { "name": "Task" }, "summary": "test rest", "description": "rest rest", })
import simplejson as json import sqlite3 import requests #from datetime import timedelta #project Key 입력 project_list = ['TPD'] # ID, PW 정보 username = '******' password = '******' userData = {'os_username': username, 'os_password': password} # jira auth jira = Jira(url='https://tcs.telechips.com:8443', username='******', password='******') #현재 날짜 생성 date = datetime.datetime.now() nowdate = date.strftime('%Y-%m-%d') # Bigpicture에서 프로젝트에 기록된 Worklog data를 추출 resource = requests.get( 'https://tcs.telechips.com:8443/rest/com.deniz.jira.worklog/1.0/timesheet/project?targetKey=' + project_list[0], userData) resource = json.loads(resource.text) # 리소스, Member_list = '' Timespent = 0
class DeploymentTicket: def __init__(self): __ATLASSSIAN_BASE_URI = os.getenv('ATLASSSIAN_BASE_URI', False) __ATLASSIAN_USER = os.getenv('ATLASSIAN_USER', False) __ATLASSIAN_API_KEY = os.getenv('ATLASSIAN_API_KEY', False) if any([__ATLASSSIAN_BASE_URI is False, __ATLASSIAN_USER is False, __ATLASSIAN_API_KEY is False]): raise Exception('One or more environment variables are not set') self.jira = Jira( url=__ATLASSSIAN_BASE_URI, username=__ATLASSIAN_USER, password=__ATLASSIAN_API_KEY) def getTickets(self): JQL = GET_TICKETS_TO_DEPLOY data = self.jira.jql(JQL) if 'total' not in data: sys.exit(data) if data['total'] > 0: print(self.getHeader(data)) print(self.getBody(data['issues'])) print(self.getFooter()) else: print("No issues ready to deploy at this moment") def getAssigne(self, value, defaultValue): if value is None: return defaultValue else: return value['key'] def getHeader(self, data): total = data['total'] tickets = '' for record in data['issues']: tickets += '{},'.format(record['key']) header = 'Total Ticket Count: *{}* [Filter|{}/issues/?jql=Key%20in%20({})] \n\n'.format( total, self.jira.url, tickets) header += 'h2. Migrations \n' header += 'Please review the PRs for each ticket to see if there are any migrations and put in this section \n\n' header += 'h2. Tickets By Engineer: \n' return header def getBody(self, issues): body = '' assignee = '' for record in issues: currentAssignee = self.getAssigne( record['fields']['assignee'], 'Undefined') if assignee != currentAssignee: body += '[~{}] \n'.format(currentAssignee) assignee = currentAssignee body += '# {} {} \n'.format(record['key'], record['fields']['summary'].encode('utf-8', errors='ignore')) return body def getFooter(self): footer = 'commit: \n' footer += 'pipeline: \n' footer += 'Description was autogenerated by [this tool|https://github.com/Andresjz/ticketdeploy]' return footer
# coding=utf-8 from atlassian import Jira # This example shoes how to copy custom field value from on issue to another # define custom field id, in notation customfield_id custom_field_id = 'customfield_102589' source_issue_key = "TST-1" destination_issue_key = "TST-2" jira = Jira( url='http://localhost:8080', username='******', password='******') # get value and save customfield_value = jira.issue_field_value(source_issue_key, custom_field_id) # prepare data like this https://developer.atlassian.com/server/jira/platform/jira-rest-api-example-edit-issues-6291632 custom_field_preparation = {custom_field_id: customfield_value} # update custom field on destination issue jira.update_issue_field(destination_issue_key, custom_field_preparation)
# coding=utf-8 from atlassian import Jira """ How to edit comment""" jira = Jira(url="https://jira.example.com/", username="******", password="******") jira.issue_edit_comment("TST-11098", 10700, "edited test rest api request")
# coding=utf-8 from atlassian import Jira JQL = "project = DEMO AND status NOT IN (Closed, Resolved) ORDER BY issuekey" jira = Jira(url="http://localhost:8080", username="******", password="******") data = jira.jql(JQL) print(data)
def test_init_jira(self): jira = Jira( url=JIRA_URL, username=ATLASSIAN_USER, password=ATLASSIAN_PASSWORD )
import logging from atlassian import Jira """ That example shows how to find the same screen fields based on fields number or hash of orders. used python 3 string forms f'{variable}' """ logging.basicConfig(level=logging.ERROR) jira = Jira(url="jira.example.com", username="******", password="******", timeout=10) def extract_count(json): try: # Also convert to int since update_time will be string. When comparing # strings, "10" is smaller than "2". return int(json["available_fields_count"]) except KeyError: return 0 all_screens = jira.get_all_screens() screens = list() count_fields_per_screen = list() hashes = list() for screen in all_screens: screen_id = screen.get("id") available_screen_fields = jira.get_all_available_screen_fields(screen_id=screen_id) field_ids = [x.get("id") for x in available_screen_fields]
#현재 날짜 생성 date = datetime.datetime.now() nowdate = date.strftime('%Y-%m-%d') #print(nowdate) # ID, PW 정보 con = sqlite3.connect('C:/Users/telechips/database/tcs.db') user = pd.read_sql("SELECT * FROM id_pw", con) user_info = user.values.tolist() con.close() userData = {'os_username': user_info[0][0], 'os_password': user_info[0][1]} # jira auth jira = Jira( url='https://tcs.telechips.com:8443', username = user_info[0][0], password = user_info[0][1]) #TCS에 등록된 모든 프로젝트의 ID를 key, 프로젝트 이름을 value로 정리 project_data = jira.projects(included_archived=None) #print(project_data[0]) data_project = {} for i in range(0, len(project_data)): r1 = {} r1.setdefault('name', project_data[i]['name']) r1.setdefault('key', project_data[i]['key']) r1.setdefault('projectcategory', project_data[i]['projectCategory']['name']) data_project.setdefault(project_data[i]['id'], r1) #print(data_project)
# coding=utf-8 import logging from atlassian import Jira from pprint import pprint """ How to get server info with health check""" jira = Jira( url="https://jira.example.com/", username='******', password='******') log = logging.getLogger("com.gonchik.python.scripts.example") logging.basicConfig(level=logging.ERROR) projects = jira.get_all_projects() for project in projects: project_key = project.get("key") try: value = jira.get_project_issue_security_scheme(project_key).get("name") or "None" except Exception as e: log.error(e) value = "None" print(project_key + " has issue security scheme " + value)
#from datetime import timedelta #project Key 입력 project_list = ['SDC'] # ID, PW 정보 con = sqlite3.connect('C:/Users/telechips/database/tcs.db') user = pd.read_sql("SELECT * FROM id_pw", con) user_info = user.values.tolist() con.close() userData = {'os_username': user_info[0][0], 'os_password': user_info[0][1]} # jira auth jira = Jira( url='https://tcs.telechips.com:8443', username = user_info[0][0], password = user_info[0][1]) #현재 날짜 생성 date = datetime.datetime.now() nowdate = date.strftime('%Y-%m-%d') # Bigpicture에서 프로젝트에 기록된 Worklog data를 추출 resource = requests.get('https://tcs.telechips.com:8443/rest/com.deniz.jira.worklog/1.0/timesheet/project?targetKey=' + project_list[0], userData) resource = json.loads(resource.text) # 리소스, Member_list = '' Timespent = 0 if len(resource['worklogAuthors']) == 0:
# coding: utf8 from time import sleep from atlassian import Jira jira = Jira( url="http://localhost:8080/", username="******", password="******") jira.reindex() while not jira.reindex_status()['success']: print('Still reindexing...') sleep(1) print('Done.')
# coding: utf8 from atlassian import Jira """ How to add comment""" jira = Jira( url="https://jira.example.com/", username='******', password='******') jira.issue_add_comment('TST-11098', 'test rest api request')
# coding=utf-8 import logging from atlassian import Confluence from atlassian import Jira logging.basicConfig(level=logging.DEBUG, format='[%(asctime).19s] [%(levelname)s] %(message)s') logging.getLogger('requests').setLevel(logging.WARNING) log = logging.getLogger('jira-projects-administrators') jira = Jira(url='http://localhost:8080', username='******', password='******') confluence = Confluence(url='http://localhost:8090', username='******', password='******') html = [ """<table> <tr> <th>Project Key</th> <th>Project Name</th> <th>Leader</th> <th>Email</th> </tr>""" ] for data in jira.project_leaders(): log.info( '{project_key} leader is {lead_name} <{lead_email}>'.format(**data)) row = """<tr> <td>{project_key}</td>
# coding: utf8 from atlassian import Jira jira = Jira( url='http://localhost:8080', username='******', password='******') results = jira.tempo_account_get_customers() print("Count of Customers " + str(len(results))) for result in results: print(result.get('key'), ' ', result.get('name'))
# 해당 버전의 전체 이슈 API allissue1 = 'https://tcs.telechips.com:8443/rest/api/2/version/' allissue2 = '/relatedIssueCounts' # 해당 버전의 미해결 이슈 API unresolvedissue1 = 'https://tcs.telechips.com:8443/rest/api/2/version/' unresolvedissue2 = '/unresolvedIssueCount' # ID, PW 정보 username = '******' password = '******' userData = {'os_username': username, 'os_password': password} # jira auth jira = Jira( url='https://tcs.telechips.com:8443', username='******', password='******') # Wiki auth confluence = Confluence( url='https://wiki.telechips.com:8443', username='******', password='******') #TCS에 등록된 모든 프로젝트의 ID를 key, 프로젝트 이름을 value로 정리 project_data = jira.projects(included_archived=None) r1 = {} for i in range(0, len(project_data)): r1.setdefault(project_data[i]['id'], project_data[i]['name']) data_project = r1
from atlassian import Jira jira = Jira( url='http://localhost:8080', username='******', password='******') accounts = jira.tempo_account_get_accounts_by_jira_project(project_id="10140") for account in accounts: print(account) jira.tempo_account_associate_with_jira_project(account['id'], project_id='10210')
from pprint import pprint from atlassian import Jira JQL = 'project = DEMO AND status NOT IN (Closed, Resolved) ORDER BY issuekey' jira = Jira(url='http://localhost:8080', username='******', password='******') data = jira.jql(JQL) pprint(data)
from atlassian import Jira jira = Jira( url="http://localhost:8080/", username="******", password="******") jira.reindex()
def get_instance(self) -> Jira: config = self.get_config() return Jira(url=config["url"], username=config["username"], password=config["token"])
# coding: utf8 import logging from atlassian import Confluence from atlassian import Jira logging.basicConfig(level=logging.DEBUG, format='[%(asctime).19s] [%(levelname)s] %(message)s') logging.getLogger('requests').setLevel(logging.WARNING) log = logging.getLogger('jira-projects-administrators') jira = Jira( url='http://localhost:8080', username='******', password='******') confluence = Confluence( url='http://localhost:8090', username='******', password='******') html = ["""<table> <tr> <th>Project Key</th> <th>Project Name</th> <th>Leader</th> <th>Email</th> </tr>"""] for data in jira.project_leaders(): log.info('{project_key} leader is {lead_name} <{lead_email}>'.format(**data)) row = """<tr>
# coding: utf8 from atlassian import Jira jira = Jira( url='https://jira.example.com/', username='******', password='******' ) data = { 'permissionScheme': 10001 } result = jira.update_project('RD', data) print(result)