Debian Codegraph @

ansible_collections/community/general/plugins/modules/jira.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Steve Smith <[email protected]>
4 # Atlassian open-source approval reference OSR-76.
5 #
6 # Copyright (c) 2020, Per Abildgaard Toft <[email protected]> Search and update function
7 # Copyright (c) 2021, Brandon McNama <[email protected]> Issue attachment functionality
8 # Copyright (c) 2022, Hugo Prudente <[email protected]> Worklog functionality
9 #
10 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
11 # SPDX-License-Identifier: GPL-3.0-or-later
12
13 from __future__ import annotations
14
15 DOCUMENTATION = r"""
16 module: jira
17 short_description: Create and modify issues in a JIRA instance
18 description:
19 - Create and modify issues in a JIRA instance.
20 extends_documentation_fragment:
21 - community.general._attributes
22
23 attributes:
24 check_mode:
25 support: none
26 diff_mode:
27 support: none
28
29 options:
30 uri:
31 type: str
32 required: true
33 description:
34 - Base URI for the JIRA instance.
35 operation:
36 type: str
37 required: true
38 aliases: [command]
39 choices: [attach, comment, create, edit, fetch, link, search, transition, update, worklog]
40 description:
41 - The operation to perform.
42 - V(worklog) was added in community.general 6.5.0.
43 username:
44 type: str
45 description:
46 - The username to log-in with.
47 - Must be used with O(password). Mutually exclusive with O(token).
48 password:
49 type: str
50 description:
51 - The password to log-in with.
52 - Must be used with O(username). Mutually exclusive with O(token).
53 token:
54 type: str
55 description:
56 - The personal access token to log-in with.
57 - Mutually exclusive with O(username) and O(password).
58 version_added: 4.2.0
59 client_cert:
60 type: path
61 description:
62 - Client certificate if required.
63 - In addition to O(username) and O(password) or O(token). Not mutually exclusive.
64 version_added: 10.4.0
65 client_key:
66 type: path
67 description:
68 - Client certificate key if required.
69 - In addition to O(username) and O(password) or O(token). Not mutually exclusive.
70 version_added: 10.4.0
71
72 project:
73 type: str
74 description:
75 - The project for this operation. Required for issue creation.
76 summary:
77 type: str
78 description:
79 - The issue summary, where appropriate.
80 - Note that JIRA may not allow changing field values on specific transitions or states.
81 description:
82 type: str
83 description:
84 - The issue description, where appropriate.
85 - Note that JIRA may not allow changing field values on specific transitions or states.
86 issuetype:
87 type: str
88 description:
89 - The issue type, for issue creation.
90 issue:
91 type: str
92 description:
93 - An existing issue key to operate on.
94 aliases: ['ticket']
95
96 comment:
97 type: str
98 description:
99 - The comment text to add.
100 - Note that JIRA may not allow changing field values on specific transitions or states.
101 comment_visibility:
102 type: dict
103 description:
104 - Used to specify comment comment visibility.
105 - See
106 U(https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-issue-comments/#api-rest-api-2-issue-issueidorkey-comment-post)
107 for details.
108 suboptions:
109 type:
110 description:
111 - Use O(comment_visibility.type) to specify which of the JIRA visibility restriction types is used.
112 type: str
113 required: true
114 choices: [group, role]
115 value:
116 description:
117 - Specify value corresponding to the type of visibility restriction. For example name of the group or role.
118 type: str
119 required: true
120 version_added: '3.2.0'
121
122 status:
123 type: str
124 description:
125 - Only used when O(operation) is V(transition), and a bit of a misnomer, it actually refers to the transition name.
126 - This is mutually exclusive with O(status_id).
127 status_id:
128 type: str
129 description:
130 - Only used when O(operation) is V(transition), and refers to the transition ID.
131 - This is mutually exclusive with O(status).
132 version_added: 10.3.0
133 assignee:
134 type: str
135 description:
136 - Sets the assignee when O(operation) is V(create), V(transition), or V(edit).
137 - Jira Cloud requires account IDs for all user-type fields. When O(cloud=true), a string value containing C(@) is
138 resolved as an email to an account ID automatically. A string without C(@) is assumed to be an account ID.
139 See also O(account_id) for a dedicated assignee account ID parameter.
140 Added in community.general 12.6.0.
141 - Jira Server and Jira Data Center may still accept O(assignee) as a username.
142 - Note that JIRA may not allow changing field values on specific transitions or states.
143 account_id:
144 type: str
145 description:
146 - Sets the account identifier for the assignee when O(operation) is V(create), V(transition), or V(edit).
147 - Note that JIRA may not allow changing field values on specific transitions or states.
148 version_added: 2.5.0
149
150 linktype:
151 type: str
152 description:
153 - Set type of link, when action 'link' selected.
154 inwardissue:
155 type: str
156 description:
157 - Set issue from which link is created.
158 outwardissue:
159 type: str
160 description:
161 - Set issue to which link is created.
162 fields:
163 type: dict
164 description:
165 - This is a free-form data structure that can contain arbitrary data. This is passed directly to the JIRA REST API (possibly
166 after merging with other required data, as when passed to create). See examples for more information, and the JIRA
167 REST API for the structure required for various fields.
168 - When O(cloud=true), user-type fields (V(assignee), V(reporter), and any fields listed in O(custom_user_fields)) that
169 contain a string value with C(@) are automatically resolved from email to account ID. String values without C(@) are
170 assumed to be account IDs. Added in community.general 12.6.0.
171 - When passed to comment, the data structure is merged at the first level since community.general 4.6.0. Useful to add
172 JIRA properties for example.
173 - Note that JIRA may not allow changing field values on specific transitions or states.
174 default: {}
175 jql:
176 description:
177 - Query JIRA in JQL Syntax, for example V("CMDB Hostname" = test.example.com).
178 type: str
179 version_added: '0.2.0'
180
181 maxresults:
182 description:
183 - Limit the result of O(operation=search). If no value is specified, the default JIRA limit is used.
184 - Used when O(operation=search) only, ignored otherwise.
185 type: int
186 version_added: '0.2.0'
187
188 timeout:
189 type: float
190 description:
191 - Set timeout, in seconds, on requests to JIRA API.
192 default: 10
193
194 validate_certs:
195 description:
196 - Require valid SSL certificates (set to V(false) if you would like to use self-signed certificates).
197 default: true
198 type: bool
199
200 cloud:
201 description:
202 - Enable when using Jira Cloud.
203 - When set to V(true), the module uses Jira Cloud compatible behavior.
204 - When set to V(false) (the default), the module uses Jira Server / Data Center compatible behavior.
205 - In the future, this option might affect additional operations for Jira Cloud compatibility.
206 type: bool
207 default: false
208 version_added: '12.6.0'
209
210 custom_user_fields:
211 description:
212 - A list of field names (for example V(customfield_10050)) that hold user values.
213 - When O(cloud=true) and a listed field is present in O(fields) as a string containing C(@), the module resolves the
214 email to a Jira Cloud account ID automatically.
215 - The built-in user fields O(assignee) and V(reporter) are always resolved when present; list here any further
216 user-typed fields (from other Jira products or extensions) that should receive the same resolution.
217 type: list
218 elements: str
219 default: []
220 version_added: '12.6.0'
221
222 attachment:
223 type: dict
224 version_added: 2.5.0
225 description:
226 - Information about the attachment being uploaded.
227 suboptions:
228 filename:
229 required: true
230 type: path
231 description:
232 - The path to the file to upload (from the remote node) or, if O(attachment.content) is specified, the filename
233 to use for the attachment.
234 content:
235 type: str
236 description:
237 - The Base64 encoded contents of the file to attach. If not specified, the contents of O(attachment.filename) is
238 used instead.
239 mimetype:
240 type: str
241 description:
242 - The MIME type to supply for the upload. If not specified, best-effort detection is performed.
243 notes:
244 - Currently this only works with basic-auth, or tokens.
245 - To use with JIRA Cloud, pass the login e-mail as the O(username) and the API token as O(password).
246 - Jira Cloud has removed the legacy C(/rest/api/2/search) endpoint. Set O(cloud=true) when using
247 O(operation=search) against Jira Cloud so that the module uses the replacement C(/rest/api/2/search/jql) endpoint instead.
248 author:
249 - "Steve Smith (@tarka)"
250 - "Per Abildgaard Toft (@pertoft)"
251 - "Brandon McNama (@DWSR)"
252 """
253
254 EXAMPLES = r"""
255 # Create a new issue and add a comment to it:
256 - name: Create an issue
257 community.general.jira:
258 uri: '{{ server }}'
259 username: '{{ user }}'
260 password: '{{ pass }}'
261 project: ANS
262 operation: create
263 summary: Example Issue
264 description: Created using Ansible
265 issuetype: Task
266 args:
267 fields:
268 customfield_13225: "test"
269 customfield_12931: {"value": "Test"}
270 register: issue
271
272 - name: Comment on issue
273 community.general.jira:
274 uri: '{{ server }}'
275 username: '{{ user }}'
276 password: '{{ pass }}'
277 issue: '{{ issue.meta.key }}'
278 operation: comment
279 comment: A comment added by Ansible
280
281 - name: Comment on issue with restricted visibility
282 community.general.jira:
283 uri: '{{ server }}'
284 username: '{{ user }}'
285 password: '{{ pass }}'
286 issue: '{{ issue.meta.key }}'
287 operation: comment
288 comment: A comment added by Ansible
289 comment_visibility:
290 type: role
291 value: Developers
292
293 - name: Comment on issue with property to mark it internal
294 community.general.jira:
295 uri: '{{ server }}'
296 username: '{{ user }}'
297 password: '{{ pass }}'
298 issue: '{{ issue.meta.key }}'
299 operation: comment
300 comment: A comment added by Ansible
301 fields:
302 properties:
303 - key: 'sd.public.comment'
304 value:
305 internal: true
306
307 # Add an workog to an existing issue
308 - name: Worklog on issue
309 community.general.jira:
310 uri: '{{ server }}'
311 username: '{{ user }}'
312 password: '{{ pass }}'
313 issue: '{{ issue.meta.key }}'
314 operation: worklog
315 comment: A worklog added by Ansible
316 fields:
317 timeSpentSeconds: 12000
318
319 - name: Workflow on issue with comment restricted visibility
320 community.general.jira:
321 uri: '{{ server }}'
322 username: '{{ user }}'
323 password: '{{ pass }}'
324 issue: '{{ issue.meta.key }}'
325 operation: worklog
326 comment: A worklog added by Ansible
327 comment_visibility:
328 type: role
329 value: Developers
330 fields:
331 timeSpentSeconds: 12000
332
333 - name: Workflow on issue with comment property to mark it internal
334 community.general.jira:
335 uri: '{{ server }}'
336 username: '{{ user }}'
337 password: '{{ pass }}'
338 issue: '{{ issue.meta.key }}'
339 operation: worklog
340 comment: A worklog added by Ansible
341 fields:
342 properties:
343 - key: 'sd.public.comment'
344 value:
345 internal: true
346 timeSpentSeconds: 12000
347
348 # Assign an existing issue using edit
349 - name: Assign an issue using free-form fields
350 community.general.jira:
351 uri: '{{ server }}'
352 username: '{{ user }}'
353 password: '{{ pass }}'
354 issue: '{{ issue.meta.key}}'
355 operation: edit
356 assignee: ssmith
357
358 # Create an issue with an existing assignee
359 - name: Create an assigned issue
360 community.general.jira:
361 uri: '{{ server }}'
362 username: '{{ user }}'
363 password: '{{ pass }}'
364 project: ANS
365 operation: create
366 summary: Assigned issue
367 description: Created and assigned using Ansible
368 issuetype: Task
369 assignee: ssmith
370
371 # Assign an issue on Jira Cloud using an email address
372 # (the module resolves the email to an account ID automatically)
373 - name: Assign an issue on Jira Cloud using email
374 community.general.jira:
375 uri: '{{ server }}'
376 username: '{{ user }}'
377 password: '{{ pass }}'
378 issue: '{{ issue.meta.key }}'
379 operation: edit
380 cloud: true
381 assignee: [email protected]
382
383 # Create an issue on Jira Cloud with reporter and a custom user field
384 # resolved from email addresses to account IDs
385 - name: Create an issue on Jira Cloud with user field resolution
386 community.general.jira:
387 uri: '{{ server }}'
388 username: '{{ user }}'
389 password: '{{ pass }}'
390 project: ANS
391 operation: create
392 summary: Example Issue
393 description: Created using Ansible
394 issuetype: Task
395 cloud: true
396 assignee: [email protected]
397 custom_user_fields:
398 - customfield_10050
399 args:
400 fields:
401 reporter: [email protected]
402 customfield_10050: [email protected]
403
404 # Edit an issue
405 - name: Set the labels on an issue using free-form fields
406 community.general.jira:
407 uri: '{{ server }}'
408 username: '{{ user }}'
409 password: '{{ pass }}'
410 issue: '{{ issue.meta.key }}'
411 operation: edit
412 args:
413 fields:
414 labels:
415 - autocreated
416 - ansible
417
418 # Updating a field using operations: add, set & remove
419 - name: Change the value of a Select dropdown
420 community.general.jira:
421 uri: '{{ server }}'
422 username: '{{ user }}'
423 password: '{{ pass }}'
424 issue: '{{ issue.meta.key }}'
425 operation: update
426 args:
427 fields:
428 customfield_12931: ['set': {'value': 'Virtual'}]
429 customfield_13820: ['set': {'value': 'Manually'}]
430 register: cmdb_issue
431 delegate_to: localhost
432
433
434 # Retrieve metadata for an issue and use it to create an account
435 - name: Get an issue
436 community.general.jira:
437 uri: '{{ server }}'
438 username: '{{ user }}'
439 password: '{{ pass }}'
440 project: ANS
441 operation: fetch
442 issue: ANS-63
443 register: issue
444
445 # Search for an issue on Jira Data Center / Server
446 # You can limit the search for specific fields by adding optional args. Note! It must be a dict, hence, lastViewed: null
447 - name: Search for an issue
448 community.general.jira:
449 uri: '{{ server }}'
450 username: '{{ user }}'
451 password: '{{ pass }}'
452 project: ANS
453 operation: search
454 maxresults: 10
455 jql: project=cmdb AND cf[13225]="test"
456 args:
457 fields:
458 lastViewed:
459 register: issue
460
461 # Search for an issue on Jira Cloud (uses the /search/jql endpoint)
462 - name: Search for an issue on Jira Cloud
463 community.general.jira:
464 uri: '{{ server }}'
465 username: '{{ user }}'
466 password: '{{ pass }}'
467 project: ANS
468 operation: search
469 cloud: true
470 maxresults: 10
471 jql: project=cmdb AND cf[13225]="test"
472 args:
473 fields:
474 lastViewed:
475 register: issue
476
477 - name: Create a unix account for the reporter
478 become: true
479 user:
480 name: '{{ issue.meta.fields.creator.name }}'
481 comment: '{{ issue.meta.fields.creator.displayName }}'
482
483 # You can get list of valid linktypes at /rest/api/2/issueLinkType
484 # url of your jira installation.
485 - name: Create link from HSP-1 to MKY-1
486 community.general.jira:
487 uri: '{{ server }}'
488 username: '{{ user }}'
489 password: '{{ pass }}'
490 operation: link
491 linktype: Relates
492 inwardissue: HSP-1
493 outwardissue: MKY-1
494
495 # Transition an issue
496 - name: Resolve the issue
497 community.general.jira:
498 uri: '{{ server }}'
499 username: '{{ user }}'
500 password: '{{ pass }}'
501 issue: '{{ issue.meta.key }}'
502 operation: transition
503 status: Resolve Issue
504 account_id: 112233445566778899aabbcc
505 fields:
506 resolution:
507 name: Done
508 description: I am done! This is the last description I will ever give you.
509
510 # Attach a file to an issue
511 - name: Attach a file
512 community.general.jira:
513 uri: '{{ server }}'
514 username: '{{ user }}'
515 password: '{{ pass }}'
516 issue: HSP-1
517 operation: attach
518 attachment:
519 filename: topsecretreport.xlsx
520
521 # Use username, password and client certificate authentification
522 - name: Create an issue
523 community.general.jira:
524 uri: '{{ server }}'
525 username: '{{ user }}'
526 password: '{{ pass }}'
527 client_cert: '{{ path/to/client-cert }}'
528 client_key: '{{ path/to/client-key }}'
529
530 # Use token and client certificate authentification
531 - name: Create an issue
532 community.general.jira:
533 uri: '{{ server }}'
534 token: '{{ token }}'
535 client_cert: '{{ path/to/client-cert }}'
536 client_key: '{{ path/to/client-key }}'
537 """
538
539 import base64
540 import binascii
541 import json
542 import mimetypes
543 import os
544 import random
545 import string
546 import traceback
547 from urllib.parse import quote
548 from urllib.request import pathname2url
549
550 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
551 from ansible.module_utils.urls import fetch_url
552
553 from ansible_collections.community.general.plugins.module_utils._module_helper import StateModuleHelper, cause_changes
554
555
556 class JIRA(StateModuleHelper):
557 USER_FIELDS = ["assignee", "reporter"]
558
559 module = dict(
560 argument_spec=dict(
561 attachment=dict(
562 type="dict",
563 options=dict(
564 content=dict(type="str"), filename=dict(type="path", required=True), mimetype=dict(type="str")
565 ),
566 ),
567 uri=dict(type="str", required=True),
568 operation=dict(
569 type="str",
570 choices=[
571 "attach",
572 "create",
573 "comment",
574 "edit",
575 "update",
576 "fetch",
577 "transition",
578 "link",
579 "search",
580 "worklog",
581 ],
582 aliases=["command"],
583 required=True,
584 ),
585 username=dict(type="str"),
586 password=dict(type="str", no_log=True),
587 token=dict(type="str", no_log=True),
588 client_cert=dict(type="path"),
589 client_key=dict(type="path"),
590 project=dict(
591 type="str",
592 ),
593 summary=dict(
594 type="str",
595 ),
596 description=dict(
597 type="str",
598 ),
599 issuetype=dict(
600 type="str",
601 ),
602 issue=dict(type="str", aliases=["ticket"]),
603 comment=dict(
604 type="str",
605 ),
606 comment_visibility=dict(
607 type="dict",
608 options=dict(
609 type=dict(type="str", choices=["group", "role"], required=True),
610 value=dict(type="str", required=True),
611 ),
612 ),
613 status=dict(
614 type="str",
615 ),
616 status_id=dict(
617 type="str",
618 ),
619 assignee=dict(
620 type="str",
621 ),
622 fields=dict(default={}, type="dict"),
623 linktype=dict(
624 type="str",
625 ),
626 inwardissue=dict(
627 type="str",
628 ),
629 outwardissue=dict(
630 type="str",
631 ),
632 jql=dict(
633 type="str",
634 ),
635 cloud=dict(type="bool", default=False),
636 custom_user_fields=dict(type="list", elements="str", default=[]),
637 maxresults=dict(type="int"),
638 timeout=dict(type="float", default=10),
639 validate_certs=dict(default=True, type="bool"),
640 account_id=dict(type="str"),
641 ),
642 mutually_exclusive=[
643 ["username", "token"],
644 ["password", "token"],
645 ["assignee", "account_id"],
646 ["status", "status_id"],
647 ],
648 required_together=[["username", "password"], ["client_cert", "client_key"]],
649 required_one_of=[
650 ["username", "token"],
651 ],
652 required_if=(
653 ("operation", "attach", ["issue", "attachment"]),
654 ("operation", "create", ["project", "issuetype", "summary"]),
655 ("operation", "comment", ["issue", "comment"]),
656 ("operation", "workflow", ["issue", "comment"]),
657 ("operation", "fetch", ["issue"]),
658 ("operation", "transition", ["issue"]),
659 ("operation", "transition", ["status", "status_id"], True),
660 ("operation", "link", ["linktype", "inwardissue", "outwardissue"]),
661 ("operation", "search", ["jql"]),
662 ),
663 supports_check_mode=False,
664 )
665 state_param = "operation"
666
667 def __init_module__(self):
668 self.vars.uri = self.vars.uri.strip("/")
669 self.vars.set("restbase", f"{self.vars.uri}/rest/api/2")
670 if self.vars.fields is None:
671 self.vars.fields = {}
672 if self.vars.assignee:
673 if self.vars.cloud:
674 self.vars.fields["assignee"] = self.vars.assignee
675 else:
676 self.vars.fields["assignee"] = {"name": self.vars.assignee}
677 if self.vars.account_id:
678 self.vars.fields["assignee"] = {"accountId": self.vars.account_id}
679 self.resolve_user_fields()
680
681 def resolve_user_fields(self):
682 if not self.vars.cloud or not self.vars.fields:
683 return
684 user_fields = self.USER_FIELDS + self.vars.custom_user_fields
685 for field_name in user_fields:
686 value = self.vars.fields.get(field_name)
687 if not isinstance(value, str):
688 continue
689 if "@" in value:
690 account_id = self.resolve_account_id(value, field_name)
691 self.vars.fields[field_name] = {"accountId": account_id}
692 else:
693 self.vars.fields[field_name] = {"accountId": value}
694
695 def resolve_account_id(self, email, field_name="assignee"):
696 url = f"{self.vars.restbase}/user/search?query={quote(email, safe='')}"
697 result = self.get(url)
698 if not isinstance(result, list) or len(result) != 1:
699 count = len(result) if isinstance(result, list) else 0
700 self.module.fail_json(
701 msg=(
702 f'Failed to resolve field "{field_name}" email "{email}" to a unique '
703 f'Jira Cloud account ID: found "{count}" result(s). '
704 "Specify the account ID directly."
705 )
706 )
707 user = result[0]
708 user_email = user.get("emailAddress")
709 if (user_email or "").lower() != email.lower():
710 self.module.fail_json(
711 msg=(
712 f'Failed to resolve field "{field_name}" email "{email}": '
713 f'the email address on the matched account "{user_email}" does not match. '
714 "Specify the account ID directly."
715 )
716 )
717 return user["accountId"]
718
719 @cause_changes(when="success")
720 def operation_create(self):
721 createfields = {
722 "project": {"key": self.vars.project},
723 "summary": self.vars.summary,
724 "issuetype": {"name": self.vars.issuetype},
725 }
726
727 if self.vars.description:
728 createfields["description"] = self.vars.description
729
730 # Merge in any additional or overridden fields
731 if self.vars.fields:
732 createfields.update(self.vars.fields)
733
734 data = {"fields": createfields}
735 url = f"{self.vars.restbase}/issue/"
736 self.vars.meta = self.post(url, data)
737
738 @cause_changes(when="success")
739 def operation_comment(self):
740 data = {"body": self.vars.comment}
741 # if comment_visibility is specified restrict visibility
742 if self.vars.comment_visibility is not None:
743 data["visibility"] = self.vars.comment_visibility
744
745 # Use 'fields' to merge in any additional data
746 if self.vars.fields:
747 data.update(self.vars.fields)
748
749 url = f"{self.vars.restbase}/issue/{self.vars.issue}/comment"
750 self.vars.meta = self.post(url, data)
751
752 @cause_changes(when="success")
753 def operation_worklog(self):
754 data = {"comment": self.vars.comment}
755 # if comment_visibility is specified restrict visibility
756 if self.vars.comment_visibility is not None:
757 data["visibility"] = self.vars.comment_visibility
758
759 # Use 'fields' to merge in any additional data
760 if self.vars.fields:
761 data.update(self.vars.fields)
762
763 url = f"{self.vars.restbase}/issue/{self.vars.issue}/worklog"
764 self.vars.meta = self.post(url, data)
765
766 @cause_changes(when="success")
767 def operation_edit(self):
768 data = {"fields": self.vars.fields}
769 url = f"{self.vars.restbase}/issue/{self.vars.issue}"
770 self.vars.meta = self.put(url, data)
771
772 @cause_changes(when="success")
773 def operation_update(self):
774 data = {
775 "update": self.vars.fields,
776 }
777 url = f"{self.vars.restbase}/issue/{self.vars.issue}"
778 self.vars.meta = self.put(url, data)
779
780 def operation_fetch(self):
781 url = f"{self.vars.restbase}/issue/{self.vars.issue}"
782 self.vars.meta = self.get(url)
783
784 def operation_search(self):
785 if self.vars.cloud:
786 url = f"{self.vars.restbase}/search/jql?jql={pathname2url(self.vars.jql)}"
787 else:
788 url = f"{self.vars.restbase}/search?jql={pathname2url(self.vars.jql)}"
789
790 if self.vars.fields:
791 fields = self.vars.fields.keys()
792 url = f"{url}&fields={'&fields='.join([pathname2url(f) for f in fields])}"
793 elif self.vars.cloud:
794 url = f"{url}&fields=*navigable"
795
796 if self.vars.maxresults:
797 url = f"{url}&maxResults={self.vars.maxresults}"
798
799 self.vars.meta = self.get(url)
800
801 @cause_changes(when="success")
802 def operation_transition(self):
803 # Find the transition id
804 turl = f"{self.vars.restbase}/issue/{self.vars.issue}/transitions"
805 tmeta = self.get(turl)
806
807 tid = None
808 target = None
809
810 if self.vars.status is not None:
811 target = self.vars.status.strip()
812 elif self.vars.status_id is not None:
813 tid = self.vars.status_id.strip()
814
815 for t in tmeta["transitions"]:
816 if target is not None:
817 if t["name"] == target:
818 tid = t["id"]
819 break
820 else:
821 if tid == t["id"]:
822 break
823 else:
824 if target is not None:
825 raise ValueError(f"Failed find valid transition for '{target}'")
826 else:
827 raise ValueError(f"Failed find valid transition for ID '{tid}'")
828
829 fields = dict(self.vars.fields)
830 if self.vars.summary is not None:
831 fields.update({"summary": self.vars.summary})
832 if self.vars.description is not None:
833 fields.update({"description": self.vars.description})
834
835 # Perform it
836 data = {"transition": {"id": tid}, "fields": fields}
837 if self.vars.comment is not None:
838 data.update(
839 {
840 "update": {
841 "comment": [{"add": {"body": self.vars.comment}}],
842 }
843 }
844 )
845 url = f"{self.vars.restbase}/issue/{self.vars.issue}/transitions"
846 self.vars.meta = self.post(url, data)
847
848 @cause_changes(when="success")
849 def operation_link(self):
850 data = {
851 "type": {"name": self.vars.linktype},
852 "inwardIssue": {"key": self.vars.inwardissue},
853 "outwardIssue": {"key": self.vars.outwardissue},
854 }
855 url = f"{self.vars.restbase}/issueLink/"
856 self.vars.meta = self.post(url, data)
857
858 @cause_changes(when="success")
859 def operation_attach(self):
860 v = self.vars
861 filename = v.attachment.get("filename")
862 content = v.attachment.get("content")
863
864 if not any((filename, content)):
865 raise ValueError("at least one of filename or content must be provided")
866 mime = v.attachment.get("mimetype")
867
868 if not os.path.isfile(filename):
869 raise ValueError(f"The provided filename does not exist: {filename}")
870
871 content_type, data = self._prepare_attachment(filename, content, mime)
872
873 url = f"{v.restbase}/issue/{v.issue}/attachments"
874 return True, self.post(
875 url, data, content_type=content_type, additional_headers={"X-Atlassian-Token": "no-check"}
876 )
877
878 # Ideally we'd just use prepare_multipart from ansible.module_utils.urls, but
879 # unfortunately it does not support specifying the encoding and also defaults to
880 # base64. Jira doesn't support base64 encoded attachments (and is therefore not
881 # spec compliant. Go figure). I originally wrote this function as an almost
882 # exact copypasta of prepare_multipart, but ran into some encoding issues when
883 # using the noop encoder. Hand rolling the entire message body seemed to work
884 # out much better.
885 #
886 # https://community.atlassian.com/t5/Jira-questions/Jira-dosen-t-decode-base64-attachment-request-REST-API/qaq-p/916427
887 #
888 # content is expected to be a base64 encoded string since Ansible doesn't
889 # support passing raw bytes objects.
890 @staticmethod
891 def _prepare_attachment(filename, content=None, mime_type=None):
892 def escape_quotes(s):
893 return s.replace('"', '\\"')
894
895 boundary = "".join(random.choice(string.digits + string.ascii_letters) for dummy in range(30))
896 name = os.path.basename(filename)
897
898 if not mime_type:
899 try:
900 mime_type = mimetypes.guess_type(filename or "", strict=False)[0] or "application/octet-stream"
901 except Exception:
902 mime_type = "application/octet-stream"
903 main_type, sep, sub_type = mime_type.partition("/")
904
905 if not content and filename:
906 with open(to_bytes(filename, errors="surrogate_or_strict"), "rb") as f:
907 content = f.read()
908 else:
909 try:
910 content = base64.b64decode(content)
911 except binascii.Error as e:
912 raise Exception(f"Unable to base64 decode file content: {e}") from e
913
914 lines = [
915 f"--{boundary}",
916 f'Content-Disposition: form-data; name="file"; filename={escape_quotes(name)}',
917 f"Content-Type: {main_type}/{sub_type}",
918 "",
919 to_text(content),
920 f"--{boundary}--",
921 "",
922 ]
923
924 return (f"multipart/form-data; boundary={boundary}", "\r\n".join(lines))
925
926 def request(self, url, data=None, method=None, content_type="application/json", additional_headers=None):
927 if data and content_type == "application/json":
928 data = json.dumps(data)
929
930 headers = {}
931 if isinstance(additional_headers, dict):
932 headers = additional_headers.copy()
933
934 # NOTE: fetch_url uses a password manager, which follows the
935 # standard request-then-challenge basic-auth semantics. However as
936 # JIRA allows some unauthorised operations it doesn't necessarily
937 # send the challenge, so the request occurs as the anonymous user,
938 # resulting in unexpected results. To work around this we manually
939 # inject the auth header up-front to ensure that JIRA treats
940 # the requests as authorized for this user.
941
942 if self.vars.token is not None:
943 headers.update(
944 {
945 "Content-Type": content_type,
946 "Authorization": f"Bearer {self.vars.token}",
947 }
948 )
949 else:
950 auth = to_text(
951 base64.b64encode(to_bytes(f"{self.vars.username}:{self.vars.password}", errors="surrogate_or_strict"))
952 )
953 headers.update(
954 {
955 "Content-Type": content_type,
956 "Authorization": f"Basic {auth}",
957 }
958 )
959
960 response, info = fetch_url(
961 self.module, url, data=data, method=method, timeout=self.vars.timeout, headers=headers
962 )
963
964 if info["status"] not in (200, 201, 204):
965 error = None
966 try:
967 error = json.loads(info["body"])
968 except Exception:
969 msg = f'The request "{method} {url}" returned the unexpected status code {info["status"]} {info["msg"]}\n{info.get("body")}'
970 self.module.fail_json(msg=msg, exception=traceback.format_exc())
971 if error:
972 msg = []
973 for key in ("errorMessages", "errors"):
974 if error.get(key):
975 msg.append(str(error[key]))
976 if msg:
977 self.module.fail_json(msg=", ".join(msg))
978 self.module.fail_json(msg=f"{error}")
979 # Fallback print body, if it can't be decoded
980 self.module.fail_json(msg=to_native(info["body"]))
981
982 body = response.read()
983
984 if body:
985 return json.loads(to_text(body, errors="surrogate_or_strict"))
986 return {}
987
988 def post(self, url, data, content_type="application/json", additional_headers=None):
989 return self.request(
990 url, data=data, method="POST", content_type=content_type, additional_headers=additional_headers
991 )
992
993 def put(self, url, data):
994 return self.request(url, data=data, method="PUT")
995
996 def get(self, url):
997 return self.request(url)
998
999
1000 def main():
1001 jira = JIRA()
1002 jira.run()
1003
1004
1005 if __name__ == "__main__":
1006 main()