| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2023, Ondrej Zvara ([email protected]) |
| 4 |
# Based on code: |
| 5 |
# Copyright (c) 2021, Lennert Mertens ([email protected]) |
| 6 |
# Copyright (c) 2021, Werner Dijkerman ([email protected]) |
| 7 |
# Copyright (c) 2015, Werner Dijkerman ([email protected]) |
| 8 |
# Copyright (c) 2019, Guillaume Martinez ([email protected]) |
| 9 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 10 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
DOCUMENTATION = r""" |
| 14 |
module: gitlab_issue |
| 15 |
short_description: Create, update, or delete GitLab issues |
| 16 |
version_added: '8.1.0' |
| 17 |
description: |
| 18 |
- Creates an issue if it does not exist. |
| 19 |
- When an issue does exist, it is updated if the provided parameters are different. |
| 20 |
- When an issue does exist and O(state=absent), the issue is deleted. |
| 21 |
- When multiple issues are detected, the task fails. |
| 22 |
- Existing issues are matched based on O(title) and O(state_filter) filters. |
| 23 |
author: |
| 24 |
- zvaraondrej (@zvaraondrej) |
| 25 |
requirements: |
| 26 |
- python-gitlab >= 2.3.0 |
| 27 |
extends_documentation_fragment: |
| 28 |
- community.general._auth_basic |
| 29 |
- community.general._gitlab |
| 30 |
- community.general._attributes |
| 31 |
|
| 32 |
attributes: |
| 33 |
check_mode: |
| 34 |
support: full |
| 35 |
diff_mode: |
| 36 |
support: none |
| 37 |
|
| 38 |
options: |
| 39 |
assignee_ids: |
| 40 |
description: |
| 41 |
- A list of assignee usernames omitting V(@) character. |
| 42 |
- Set to an empty array to unassign all assignees. |
| 43 |
type: list |
| 44 |
elements: str |
| 45 |
description: |
| 46 |
description: |
| 47 |
- A description of the issue. |
| 48 |
- Gets overridden by a content of file specified at O(description_path), if found. |
| 49 |
type: str |
| 50 |
description_path: |
| 51 |
description: |
| 52 |
- A path of file containing issue's description. |
| 53 |
- Accepts MarkDown formatted files. |
| 54 |
type: path |
| 55 |
issue_type: |
| 56 |
description: |
| 57 |
- Type of the issue. |
| 58 |
default: issue |
| 59 |
type: str |
| 60 |
choices: ["issue", "incident", "test_case"] |
| 61 |
labels: |
| 62 |
description: |
| 63 |
- A list of label names. |
| 64 |
- Set to an empty array to remove all labels. |
| 65 |
type: list |
| 66 |
elements: str |
| 67 |
milestone_search: |
| 68 |
description: |
| 69 |
- The name of the milestone. |
| 70 |
- Set to empty string to unassign milestone. |
| 71 |
type: str |
| 72 |
milestone_group_id: |
| 73 |
description: |
| 74 |
- The path or numeric ID of the group hosting desired milestone. |
| 75 |
type: str |
| 76 |
project: |
| 77 |
description: |
| 78 |
- The path or name of the project. |
| 79 |
required: true |
| 80 |
type: str |
| 81 |
state: |
| 82 |
description: |
| 83 |
- Create or delete issue. |
| 84 |
default: present |
| 85 |
type: str |
| 86 |
choices: ["present", "absent"] |
| 87 |
state_filter: |
| 88 |
description: |
| 89 |
- Filter specifying state of issues while searching. |
| 90 |
type: str |
| 91 |
choices: ["opened", "closed"] |
| 92 |
default: opened |
| 93 |
title: |
| 94 |
description: |
| 95 |
- A title for the issue. The title is used as a unique identifier to ensure idempotency. |
| 96 |
type: str |
| 97 |
required: true |
| 98 |
""" |
| 99 |
|
| 100 |
|
| 101 |
EXAMPLES = r""" |
| 102 |
- name: Create Issue |
| 103 |
community.general.gitlab_issue: |
| 104 |
api_url: https://gitlab.com |
| 105 |
api_token: secret_access_token |
| 106 |
project: "group1/project1" |
| 107 |
title: "Ansible demo Issue" |
| 108 |
description: "Demo Issue description" |
| 109 |
labels: |
| 110 |
- Ansible |
| 111 |
- Demo |
| 112 |
assignee_ids: |
| 113 |
- testassignee |
| 114 |
state_filter: "opened" |
| 115 |
state: present |
| 116 |
|
| 117 |
- name: Delete Issue |
| 118 |
community.general.gitlab_issue: |
| 119 |
api_url: https://gitlab.com |
| 120 |
api_token: secret_access_token |
| 121 |
project: "group1/project1" |
| 122 |
title: "Ansible demo Issue" |
| 123 |
state_filter: "opened" |
| 124 |
state: absent |
| 125 |
""" |
| 126 |
|
| 127 |
RETURN = r""" |
| 128 |
msg: |
| 129 |
description: Success or failure message. |
| 130 |
returned: always |
| 131 |
type: str |
| 132 |
sample: "Success" |
| 133 |
|
| 134 |
issue: |
| 135 |
description: API object. |
| 136 |
returned: success |
| 137 |
type: dict |
| 138 |
""" |
| 139 |
|
| 140 |
from ansible.module_utils.api import basic_auth_argument_spec |
| 141 |
from ansible.module_utils.basic import AnsibleModule |
| 142 |
from ansible.module_utils.common.text.converters import to_text |
| 143 |
|
| 144 |
from ansible_collections.community.general.plugins.module_utils._gitlab import ( |
| 145 |
auth_argument_spec, |
| 146 |
find_group, |
| 147 |
find_project, |
| 148 |
gitlab, |
| 149 |
gitlab_authentication, |
| 150 |
) |
| 151 |
|
| 152 |
|
| 153 |
class GitlabIssue: |
| 154 |
def __init__(self, module, project, gitlab_instance): |
| 155 |
self._gitlab = gitlab_instance |
| 156 |
self._module = module |
| 157 |
self.project = project |
| 158 |
|
| 159 |
""" |
| 160 |
@param milestone_id Title of the milestone |
| 161 |
""" |
| 162 |
|
| 163 |
def get_milestone(self, milestone_id, group): |
| 164 |
milestones = [] |
| 165 |
try: |
| 166 |
milestones = group.milestones.list(search=milestone_id) |
| 167 |
except gitlab.exceptions.GitlabGetError as e: |
| 168 |
self._module.fail_json(msg=f"Failed to list the Milestones: {e}") |
| 169 |
|
| 170 |
if len(milestones) > 1: |
| 171 |
self._module.fail_json(msg="Multiple Milestones matched search criteria.") |
| 172 |
if len(milestones) < 1: |
| 173 |
self._module.fail_json(msg="No Milestones matched search criteria.") |
| 174 |
if len(milestones) == 1: |
| 175 |
try: |
| 176 |
return group.milestones.get(id=milestones[0].id) |
| 177 |
except gitlab.exceptions.GitlabGetError as e: |
| 178 |
self._module.fail_json(msg=f"Failed to get the Milestones: {e}") |
| 179 |
|
| 180 |
""" |
| 181 |
@param title Title of the Issue |
| 182 |
@param state_filter Issue's state to filter on |
| 183 |
""" |
| 184 |
|
| 185 |
def get_issue(self, title, state_filter): |
| 186 |
issues = [] |
| 187 |
try: |
| 188 |
issues = self.project.issues.list(query_parameters={"search": title, "in": "title", "state": state_filter}) |
| 189 |
except gitlab.exceptions.GitlabGetError as e: |
| 190 |
self._module.fail_json(msg=f"Failed to list the Issues: {e}") |
| 191 |
|
| 192 |
if len(issues) > 1: |
| 193 |
self._module.fail_json(msg="Multiple Issues matched search criteria.") |
| 194 |
if len(issues) == 1: |
| 195 |
try: |
| 196 |
return self.project.issues.get(id=issues[0].iid) |
| 197 |
except gitlab.exceptions.GitlabGetError as e: |
| 198 |
self._module.fail_json(msg=f"Failed to get the Issue: {e}") |
| 199 |
|
| 200 |
""" |
| 201 |
@param username Name of the user |
| 202 |
""" |
| 203 |
|
| 204 |
def get_user(self, username): |
| 205 |
users = [] |
| 206 |
try: |
| 207 |
users = [user for user in self.project.users.list(username=username, all=True) if user.username == username] |
| 208 |
except gitlab.exceptions.GitlabGetError as e: |
| 209 |
self._module.fail_json(msg=f"Failed to list the users: {e}") |
| 210 |
|
| 211 |
if len(users) > 1: |
| 212 |
self._module.fail_json(msg="Multiple Users matched search criteria.") |
| 213 |
elif len(users) < 1: |
| 214 |
self._module.fail_json(msg="No User matched search criteria.") |
| 215 |
else: |
| 216 |
return users[0] |
| 217 |
|
| 218 |
""" |
| 219 |
@param users List of usernames |
| 220 |
""" |
| 221 |
|
| 222 |
def get_user_ids(self, users): |
| 223 |
return [self.get_user(user).id for user in users] |
| 224 |
|
| 225 |
""" |
| 226 |
@param options Options of the Issue |
| 227 |
""" |
| 228 |
|
| 229 |
def create_issue(self, options): |
| 230 |
if self._module.check_mode: |
| 231 |
self._module.exit_json(changed=True, msg=f"Successfully created Issue '{options['title']}'.") |
| 232 |
|
| 233 |
try: |
| 234 |
return self.project.issues.create(options) |
| 235 |
except gitlab.exceptions.GitlabCreateError as e: |
| 236 |
self._module.fail_json(msg=f"Failed to create Issue: {e}") |
| 237 |
|
| 238 |
""" |
| 239 |
@param issue Issue object to delete |
| 240 |
""" |
| 241 |
|
| 242 |
def delete_issue(self, issue): |
| 243 |
if self._module.check_mode: |
| 244 |
self._module.exit_json(changed=True, msg=f"Successfully deleted Issue '{issue['title']}'.") |
| 245 |
|
| 246 |
try: |
| 247 |
return issue.delete() |
| 248 |
except gitlab.exceptions.GitlabDeleteError as e: |
| 249 |
self._module.fail_json(msg=f"Failed to delete Issue: '{e}'.") |
| 250 |
|
| 251 |
""" |
| 252 |
@param issue Issue object to update |
| 253 |
@param options Options of the Issue |
| 254 |
""" |
| 255 |
|
| 256 |
def update_issue(self, issue, options): |
| 257 |
if self._module.check_mode: |
| 258 |
self._module.exit_json(changed=True, msg=f"Successfully updated Issue '{issue['title']}'.") |
| 259 |
|
| 260 |
try: |
| 261 |
return self.project.issues.update(issue.iid, options) |
| 262 |
except gitlab.exceptions.GitlabUpdateError as e: |
| 263 |
self._module.fail_json(msg=f"Failed to update Issue {e}.") |
| 264 |
|
| 265 |
""" |
| 266 |
@param issue Issue object to evaluate |
| 267 |
@param options New options to update Issue with |
| 268 |
""" |
| 269 |
|
| 270 |
def issue_has_changed(self, issue, options): |
| 271 |
for key, value in options.items(): |
| 272 |
if value is not None: |
| 273 |
if key == "milestone_id": |
| 274 |
old_milestone = issue.milestone["id"] if issue.milestone else "" |
| 275 |
if value != old_milestone: |
| 276 |
return True |
| 277 |
elif key == "assignee_ids": |
| 278 |
if value != sorted([user["id"] for user in issue.assignees]): |
| 279 |
return True |
| 280 |
|
| 281 |
elif key == "labels": |
| 282 |
if value != sorted(getattr(issue, key)): |
| 283 |
return True |
| 284 |
|
| 285 |
elif getattr(issue, key) != value: |
| 286 |
return True |
| 287 |
|
| 288 |
return False |
| 289 |
|
| 290 |
|
| 291 |
def main(): |
| 292 |
argument_spec = basic_auth_argument_spec() |
| 293 |
argument_spec.update(auth_argument_spec()) |
| 294 |
argument_spec.update( |
| 295 |
assignee_ids=dict(type="list", elements="str"), |
| 296 |
description=dict(type="str"), |
| 297 |
description_path=dict(type="path"), |
| 298 |
issue_type=dict(type="str", default="issue", choices=["issue", "incident", "test_case"]), |
| 299 |
labels=dict(type="list", elements="str"), |
| 300 |
milestone_search=dict(type="str"), |
| 301 |
milestone_group_id=dict(type="str"), |
| 302 |
project=dict(type="str", required=True), |
| 303 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 304 |
state_filter=dict(type="str", default="opened", choices=["opened", "closed"]), |
| 305 |
title=dict(type="str", required=True), |
| 306 |
) |
| 307 |
|
| 308 |
module = AnsibleModule( |
| 309 |
argument_spec=argument_spec, |
| 310 |
mutually_exclusive=[ |
| 311 |
["api_username", "api_token"], |
| 312 |
["api_username", "api_oauth_token"], |
| 313 |
["api_username", "api_job_token"], |
| 314 |
["api_token", "api_oauth_token"], |
| 315 |
["api_token", "api_job_token"], |
| 316 |
["description", "description_path"], |
| 317 |
], |
| 318 |
required_together=[ |
| 319 |
["api_username", "api_password"], |
| 320 |
["milestone_search", "milestone_group_id"], |
| 321 |
], |
| 322 |
required_one_of=[["api_username", "api_token", "api_oauth_token", "api_job_token"]], |
| 323 |
supports_check_mode=True, |
| 324 |
) |
| 325 |
|
| 326 |
assignee_ids = module.params["assignee_ids"] |
| 327 |
description = module.params["description"] |
| 328 |
description_path = module.params["description_path"] |
| 329 |
issue_type = module.params["issue_type"] |
| 330 |
labels = module.params["labels"] |
| 331 |
milestone_id = module.params["milestone_search"] |
| 332 |
milestone_group_id = module.params["milestone_group_id"] |
| 333 |
project = module.params["project"] |
| 334 |
state = module.params["state"] |
| 335 |
state_filter = module.params["state_filter"] |
| 336 |
title = module.params["title"] |
| 337 |
|
| 338 |
# check prerequisites and connect to gitlab server |
| 339 |
gitlab_instance = gitlab_authentication(module, min_version="2.3.0") |
| 340 |
|
| 341 |
this_project = find_project(gitlab_instance, project) |
| 342 |
if this_project is None: |
| 343 |
module.fail_json(msg=f"Failed to get the project: {project}") |
| 344 |
|
| 345 |
this_gitlab = GitlabIssue(module=module, project=this_project, gitlab_instance=gitlab_instance) |
| 346 |
|
| 347 |
if milestone_id and milestone_group_id: |
| 348 |
this_group = find_group(gitlab_instance, milestone_group_id) |
| 349 |
if this_group is None: |
| 350 |
module.fail_json(msg=f"Failed to get the group: {milestone_group_id}") |
| 351 |
|
| 352 |
milestone_id = this_gitlab.get_milestone(milestone_id, this_group).id |
| 353 |
|
| 354 |
this_issue = this_gitlab.get_issue(title, state_filter) |
| 355 |
|
| 356 |
if state == "present": |
| 357 |
if description_path: |
| 358 |
try: |
| 359 |
with open(description_path, "rb") as f: |
| 360 |
description = to_text(f.read(), errors="surrogate_or_strict") |
| 361 |
except OSError as e: |
| 362 |
module.fail_json(msg=f"Cannot open {description_path}: {e}") |
| 363 |
|
| 364 |
# sorting necessary in order to properly detect changes, as we don't want to get false positive |
| 365 |
# results due to differences in ids ordering; |
| 366 |
assignee_ids = sorted(this_gitlab.get_user_ids(assignee_ids)) if assignee_ids else assignee_ids |
| 367 |
labels = sorted(labels) if labels else labels |
| 368 |
|
| 369 |
options = { |
| 370 |
"title": title, |
| 371 |
"description": description, |
| 372 |
"labels": labels, |
| 373 |
"issue_type": issue_type, |
| 374 |
"milestone_id": milestone_id, |
| 375 |
"assignee_ids": assignee_ids, |
| 376 |
} |
| 377 |
|
| 378 |
if not this_issue: |
| 379 |
issue = this_gitlab.create_issue(options) |
| 380 |
module.exit_json(changed=True, msg=f"Created Issue '{title}'.", issue=issue.asdict()) |
| 381 |
else: |
| 382 |
if this_gitlab.issue_has_changed(this_issue, options): |
| 383 |
issue = this_gitlab.update_issue(this_issue, options) |
| 384 |
module.exit_json(changed=True, msg=f"Updated Issue '{title}'.", issue=issue) |
| 385 |
else: |
| 386 |
module.exit_json(changed=False, msg=f"Issue '{title}' already exists", issue=this_issue.asdict()) |
| 387 |
elif state == "absent": |
| 388 |
if not this_issue: |
| 389 |
module.exit_json(changed=False, msg=f"Issue '{title}' does not exist or has already been deleted.") |
| 390 |
else: |
| 391 |
issue = this_gitlab.delete_issue(this_issue) |
| 392 |
module.exit_json(changed=True, msg=f"Issue '{title}' deleted.", issue=issue) |
| 393 |
|
| 394 |
|
| 395 |
if __name__ == "__main__": |
| 396 |
main() |