community.general/lib/ansible/modules/web_infrastructure/jira.py

438 lines
11 KiB
Python
Raw Normal View History

2014-09-26 01:01:01 +00:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Steve Smith <ssmith@atlassian.com>
# Atlassian open-source approval reference OSR-76.
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
2016-12-06 10:35:25 +00:00
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
2014-09-26 01:01:01 +00:00
DOCUMENTATION = """
module: jira
version_added: "1.6"
short_description: create and modify issues in a JIRA instance
description:
- Create and modify issues in a JIRA instance.
options:
uri:
required: true
description:
- Base URI for the JIRA instance
operation:
required: true
aliases: [ command ]
choices: [ create, comment, edit, fetch, transition ]
description:
- The operation to perform.
username:
required: true
description:
- The username to log-in with.
password:
required: true
description:
- The password to log-in with.
project:
aliases: [ prj ]
required: false
description:
- The project for this operation. Required for issue creation.
summary:
required: false
description:
- The issue summary, where appropriate.
description:
required: false
description:
- The issue description, where appropriate.
issuetype:
required: false
description:
- The issue type, for issue creation.
issue:
required: false
description:
- An existing issue key to operate on.
comment:
required: false
description:
- The comment text to add.
status:
required: false
description:
- The desired status; only relevant for the transition operation.
assignee:
required: false
description:
- Sets the assignee on create or transition operations. Note not all transitions will allow this.
2016-04-28 15:00:11 +00:00
linktype:
required: false
version_added: 2.3
description:
- Set type of link, when action 'link' selected
inwardissue:
required: false
version_added: 2.3
description:
- set issue from which link will be created
outwardissue:
required: false
version_added: 2.3
description:
- set issue to which link will be created
2014-09-26 01:01:01 +00:00
fields:
required: false
description:
- This is a free-form data structure that can contain arbitrary data. This is passed directly to the JIRA REST API (possibly after merging with other required data, as when passed to create). See examples for more information, and the JIRA REST API for the structure required for various fields.
notes:
- "Currently this only works with basic-auth."
author: "Steve Smith (@tarka)"
2014-09-26 01:01:01 +00:00
"""
EXAMPLES = """
# Create a new issue and add a comment to it:
- name: Create an issue
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
project: ANS
operation: create
summary: Example Issue
description: Created using Ansible
issuetype: Task
2014-09-26 01:01:01 +00:00
register: issue
- name: Comment on issue
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
issue: '{{ issue.meta.key }}'
operation: comment
comment: A comment added by Ansible
2014-09-26 01:01:01 +00:00
# Assign an existing issue using edit
- name: Assign an issue using free-form fields
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
issue: '{{ issue.meta.key}}'
operation: edit
assignee: ssmith
2014-09-26 01:01:01 +00:00
# Create an issue with an existing assignee
- name: Create an assigned issue
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
project: ANS
operation: create
summary: Assigned issue
description: Created and assigned using Ansible
issuetype: Task
assignee: ssmith
# Edit an issue
2014-09-26 01:01:01 +00:00
- name: Set the labels on an issue using free-form fields
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
issue: '{{ issue.meta.key }}'
operation: edit
args:
fields:
labels:
- autocreated
- ansible
2014-09-26 01:01:01 +00:00
# Retrieve metadata for an issue and use it to create an account
- name: Get an issue
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
project: ANS
operation: fetch
issue: ANS-63
2014-09-26 01:01:01 +00:00
register: issue
- name: Create a unix account for the reporter
become: true
user:
name: '{{ issue.meta.fields.creator.name }}'
comment: '{{ issue.meta.fields.creator.displayName }}'
2014-09-26 01:01:01 +00:00
2016-04-28 15:00:11 +00:00
- name: Create link from HSP-1 to MKY-1
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
operation: link
linktype: Relate
inwardissue: HSP-1
outwardissue: MKY-1
2016-04-28 15:00:11 +00:00
2014-09-26 01:01:01 +00:00
# Transition an issue by target status
- name: Close the issue
jira:
uri: '{{ server }}'
username: '{{ user }}'
password: '{{ pass }}'
issue: '{{ issue.meta.key }}'
operation: transition
status: Done
2014-09-26 01:01:01 +00:00
"""
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
2014-09-26 01:01:01 +00:00
import base64
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
from ansible.module_utils.pycompat24 import get_exception
2014-09-26 01:01:01 +00:00
def request(url, user, passwd, data=None, method=None):
if data:
data = json.dumps(data)
# NOTE: fetch_url uses a password manager, which follows the
# standard request-then-challenge basic-auth semantics. However as
# JIRA allows some unauthorised operations it doesn't necessarily
# send the challenge, so the request occurs as the anonymous user,
# resulting in unexpected results. To work around this we manually
# inject the basic-auth header up-front to ensure that JIRA treats
# the requests as authorized for this user.
auth = base64.encodestring('%s:%s' % (user, passwd)).replace('\n', '')
2017-01-27 23:20:31 +00:00
response, info = fetch_url(module, url, data=data, method=method,
2014-09-26 01:01:01 +00:00
headers={'Content-Type':'application/json',
'Authorization':"Basic %s" % auth})
if info['status'] not in (200, 201, 204):
2014-09-26 01:01:01 +00:00
module.fail_json(msg=info['msg'])
body = response.read()
if body:
return json.loads(body)
else:
return {}
def post(url, user, passwd, data):
return request(url, user, passwd, data=data, method='POST')
def put(url, user, passwd, data):
return request(url, user, passwd, data=data, method='PUT')
def get(url, user, passwd):
return request(url, user, passwd)
def create(restbase, user, passwd, params):
createfields = {
'project': { 'key': params['project'] },
'summary': params['summary'],
'description': params['description'],
'issuetype': { 'name': params['issuetype'] }}
# Merge in any additional or overridden fields
if params['fields']:
createfields.update(params['fields'])
data = {'fields': createfields}
url = restbase + '/issue/'
2017-01-27 23:20:31 +00:00
ret = post(url, user, passwd, data)
2014-09-26 01:01:01 +00:00
return ret
def comment(restbase, user, passwd, params):
data = {
'body': params['comment']
}
url = restbase + '/issue/' + params['issue'] + '/comment'
ret = post(url, user, passwd, data)
return ret
def edit(restbase, user, passwd, params):
data = {
'fields': params['fields']
}
2017-01-27 23:20:31 +00:00
url = restbase + '/issue/' + params['issue']
2014-09-26 01:01:01 +00:00
2017-01-27 23:20:31 +00:00
ret = put(url, user, passwd, data)
2014-09-26 01:01:01 +00:00
return ret
def fetch(restbase, user, passwd, params):
url = restbase + '/issue/' + params['issue']
2017-01-27 23:20:31 +00:00
ret = get(url, user, passwd)
2014-09-26 01:01:01 +00:00
return ret
def transition(restbase, user, passwd, params):
# Find the transition id
turl = restbase + '/issue/' + params['issue'] + "/transitions"
tmeta = get(turl, user, passwd)
target = params['status']
tid = None
for t in tmeta['transitions']:
if t['name'] == target:
tid = t['id']
break
if not tid:
raise ValueError("Failed find valid transition for '%s'" % target)
# Perform it
url = restbase + '/issue/' + params['issue'] + "/transitions"
data = { 'transition': { "id" : tid },
'fields': params['fields']}
ret = post(url, user, passwd, data)
return ret
2016-04-28 15:00:11 +00:00
def link(restbase, user, passwd, params):
data = {
'type': { 'name': params['linktype'] },
'inwardIssue': { 'key': params['inwardissue'] },
'outwardIssue': { 'key': params['outwardissue'] },
}
url = restbase + '/issueLink/'
ret = post(url, user, passwd, data)
return ret
2014-09-26 01:01:01 +00:00
# Some parameters are required depending on the operation:
OP_REQUIRED = dict(create=['project', 'issuetype', 'summary', 'description'],
comment=['issue', 'comment'],
edit=[],
fetch=['issue'],
2016-04-28 15:00:11 +00:00
transition=['status'],
link=['linktype', 'inwardissue', 'outwardissue'])
2014-09-26 01:01:01 +00:00
def main():
global module
module = AnsibleModule(
argument_spec=dict(
uri=dict(required=True),
2016-04-28 15:00:11 +00:00
operation=dict(choices=['create', 'comment', 'edit', 'fetch', 'transition', 'link'],
2014-09-26 01:01:01 +00:00
aliases=['command'], required=True),
username=dict(required=True),
password=dict(required=True),
project=dict(),
summary=dict(),
description=dict(),
issuetype=dict(),
issue=dict(aliases=['ticket']),
comment=dict(),
status=dict(),
assignee=dict(),
2016-04-28 15:00:11 +00:00
fields=dict(default={}, type='dict'),
linktype=dict(),
inwardissue=dict(),
outwardissue=dict(),
2014-09-26 01:01:01 +00:00
),
supports_check_mode=False
)
op = module.params['operation']
# Check we have the necessary per-operation parameters
missing = []
for parm in OP_REQUIRED[op]:
if not module.params[parm]:
missing.append(parm)
if missing:
module.fail_json(msg="Operation %s require the following missing parameters: %s" % (op, ",".join(missing)))
# Handle rest of parameters
uri = module.params['uri']
user = module.params['username']
passwd = module.params['password']
if module.params['assignee']:
module.params['fields']['assignee'] = { 'name': module.params['assignee'] }
if not uri.endswith('/'):
uri = uri+'/'
restbase = uri + 'rest/api/2'
# Dispatch
try:
2014-09-26 01:01:01 +00:00
# Lookup the corresponding method for this operation. This is
# safe as the AnsibleModule should remove any unknown operations.
thismod = sys.modules[__name__]
method = getattr(thismod, op)
ret = method(restbase, user, passwd, module.params)
except Exception:
e = get_exception()
2014-09-26 01:01:01 +00:00
return module.fail_json(msg=e.message)
module.exit_json(changed=True, meta=ret)
if __name__ == '__main__':
main()