| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2016, Jiri Tyr <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: jenkins_plugin |
| 11 |
author: Jiri Tyr (@jtyr) |
| 12 |
short_description: Add or remove Jenkins plugin |
| 13 |
description: |
| 14 |
- Ansible module which helps to manage Jenkins plugins. |
| 15 |
attributes: |
| 16 |
check_mode: |
| 17 |
support: full |
| 18 |
diff_mode: |
| 19 |
support: none |
| 20 |
|
| 21 |
options: |
| 22 |
group: |
| 23 |
type: str |
| 24 |
description: |
| 25 |
- GID or name of the Jenkins group on the OS. |
| 26 |
default: jenkins |
| 27 |
jenkins_home: |
| 28 |
type: path |
| 29 |
description: |
| 30 |
- Home directory of the Jenkins user. |
| 31 |
default: /var/lib/jenkins |
| 32 |
mode: |
| 33 |
type: raw |
| 34 |
description: |
| 35 |
- File mode applied on versioned plugins. |
| 36 |
default: '0644' |
| 37 |
name: |
| 38 |
type: str |
| 39 |
description: |
| 40 |
- Plugin name. |
| 41 |
required: true |
| 42 |
owner: |
| 43 |
type: str |
| 44 |
description: |
| 45 |
- UID or name of the Jenkins user on the OS. |
| 46 |
default: jenkins |
| 47 |
state: |
| 48 |
type: str |
| 49 |
description: |
| 50 |
- Desired plugin state. |
| 51 |
- If set to V(latest), the check for new version is performed every time. This is suitable to keep the plugin up-to-date. |
| 52 |
choices: [absent, present, pinned, unpinned, enabled, disabled, latest] |
| 53 |
default: present |
| 54 |
timeout: |
| 55 |
type: int |
| 56 |
description: |
| 57 |
- Server connection timeout in secs. |
| 58 |
default: 30 |
| 59 |
updates_expiration: |
| 60 |
type: int |
| 61 |
description: |
| 62 |
- Number of seconds after which a new copy of the C(update-center.json) file is downloaded. This is used to avoid the |
| 63 |
need to download the plugin to calculate its checksum when O(state=latest) is specified. |
| 64 |
- Set it to V(0) if no cache file should be used. In that case, the plugin file is always downloaded to calculate its |
| 65 |
checksum when O(state=latest) is specified. |
| 66 |
default: 86400 |
| 67 |
updates_url: |
| 68 |
type: list |
| 69 |
elements: str |
| 70 |
description: |
| 71 |
- A list of base URL(s) to retrieve C(update-center.json), and direct plugin files from. |
| 72 |
- This can be a list since community.general 3.3.0. |
| 73 |
default: ['https://updates.jenkins.io', 'http://mirrors.jenkins.io'] |
| 74 |
updates_url_username: |
| 75 |
description: |
| 76 |
- If using a custom O(updates_url), set this as the username of the user with access to the URL. |
| 77 |
- If the custom O(updates_url) does not require authentication, this can be left empty. |
| 78 |
type: str |
| 79 |
version_added: 11.2.0 |
| 80 |
updates_url_password: |
| 81 |
description: |
| 82 |
- If using a custom O(updates_url), set this as the password of the user with access to the URL. |
| 83 |
- If the custom O(updates_url) does not require authentication, this can be left empty. |
| 84 |
type: str |
| 85 |
version_added: 11.2.0 |
| 86 |
update_json_url_segment: |
| 87 |
type: list |
| 88 |
elements: str |
| 89 |
description: |
| 90 |
- A list of URL segment(s) to retrieve the update center JSON file from. |
| 91 |
default: ['update-center.json', 'updates/update-center.json'] |
| 92 |
version_added: 3.3.0 |
| 93 |
plugin_versions_url_segment: |
| 94 |
type: list |
| 95 |
elements: str |
| 96 |
description: |
| 97 |
- A list of URL segment(s) to retrieve the plugin versions JSON file from. |
| 98 |
default: ['plugin-versions.json', 'current/plugin-versions.json'] |
| 99 |
version_added: 11.2.0 |
| 100 |
latest_plugins_url_segments: |
| 101 |
type: list |
| 102 |
elements: str |
| 103 |
description: |
| 104 |
- Path inside the O(updates_url) to get latest plugins from. |
| 105 |
default: ['latest'] |
| 106 |
version_added: 3.3.0 |
| 107 |
versioned_plugins_url_segments: |
| 108 |
type: list |
| 109 |
elements: str |
| 110 |
description: |
| 111 |
- Path inside the O(updates_url) to get specific version of plugins from. |
| 112 |
default: ['download/plugins', 'plugins'] |
| 113 |
version_added: 3.3.0 |
| 114 |
url: |
| 115 |
type: str |
| 116 |
description: |
| 117 |
- URL of the Jenkins server. |
| 118 |
default: http://localhost:8080 |
| 119 |
version: |
| 120 |
type: str |
| 121 |
description: |
| 122 |
- Plugin version number. |
| 123 |
- If this option is specified, all plugin dependencies must be installed manually. |
| 124 |
- It might take longer to verify that the correct version is installed. This is especially true if a specific version |
| 125 |
number is specified. |
| 126 |
- Quote the version to prevent the value to be interpreted as float. For example if V(1.20) would be unquoted, it would |
| 127 |
become V(1.2). |
| 128 |
with_dependencies: |
| 129 |
description: |
| 130 |
- Defines whether to install plugin dependencies. |
| 131 |
- In earlier versions, this option had no effect when a specific O(version) was set. |
| 132 |
Since community.general 11.2.0, dependencies are also installed for versioned plugins. |
| 133 |
type: bool |
| 134 |
default: true |
| 135 |
|
| 136 |
notes: |
| 137 |
- Plugin installation should be run under root or the same user which owns the plugin files on the disk. Only if the plugin |
| 138 |
is not installed yet and no version is specified, the API installation is performed which requires only the Web UI credentials. |
| 139 |
- It is necessary to notify the handler or call the M(ansible.builtin.service) module to restart the Jenkins service after |
| 140 |
a new plugin was installed. |
| 141 |
- Pinning works only if the plugin is installed and Jenkins service was successfully restarted after the plugin installation. |
| 142 |
- It is not possible to run the module remotely by changing the O(url) parameter to point to the Jenkins server. The module |
| 143 |
must be used on the host where Jenkins runs as it needs direct access to the plugin files. |
| 144 |
- If using a custom O(updates_url), ensure that the URL provides a C(plugin-versions.json) file. |
| 145 |
This file must include metadata for all available plugin versions to support version compatibility resolution. |
| 146 |
The file should be in the same format as the one provided by Jenkins update center (https://updates.jenkins.io/current/plugin-versions.json). |
| 147 |
extends_documentation_fragment: |
| 148 |
- ansible.builtin.url |
| 149 |
- ansible.builtin.files |
| 150 |
- community.general._attributes |
| 151 |
""" |
| 152 |
|
| 153 |
EXAMPLES = r""" |
| 154 |
- name: Install plugin |
| 155 |
community.general.jenkins_plugin: |
| 156 |
name: build-pipeline-plugin |
| 157 |
|
| 158 |
- name: Install plugin without its dependencies |
| 159 |
community.general.jenkins_plugin: |
| 160 |
name: build-pipeline-plugin |
| 161 |
with_dependencies: false |
| 162 |
|
| 163 |
- name: Make sure the plugin is always up-to-date |
| 164 |
community.general.jenkins_plugin: |
| 165 |
name: token-macro |
| 166 |
state: latest |
| 167 |
|
| 168 |
- name: Install specific version of the plugin |
| 169 |
community.general.jenkins_plugin: |
| 170 |
name: token-macro |
| 171 |
version: "1.15" |
| 172 |
|
| 173 |
- name: Pin the plugin |
| 174 |
community.general.jenkins_plugin: |
| 175 |
name: token-macro |
| 176 |
state: pinned |
| 177 |
|
| 178 |
- name: Unpin the plugin |
| 179 |
community.general.jenkins_plugin: |
| 180 |
name: token-macro |
| 181 |
state: unpinned |
| 182 |
|
| 183 |
- name: Enable the plugin |
| 184 |
community.general.jenkins_plugin: |
| 185 |
name: token-macro |
| 186 |
state: enabled |
| 187 |
|
| 188 |
- name: Disable the plugin |
| 189 |
community.general.jenkins_plugin: |
| 190 |
name: token-macro |
| 191 |
state: disabled |
| 192 |
|
| 193 |
- name: Uninstall plugin |
| 194 |
community.general.jenkins_plugin: |
| 195 |
name: build-pipeline-plugin |
| 196 |
state: absent |
| 197 |
|
| 198 |
# |
| 199 |
# Example of how to authenticate |
| 200 |
# |
| 201 |
- name: Install plugin |
| 202 |
community.general.jenkins_plugin: |
| 203 |
name: build-pipeline-plugin |
| 204 |
url_username: admin |
| 205 |
url_password: p4ssw0rd |
| 206 |
url: http://localhost:8888 |
| 207 |
|
| 208 |
# |
| 209 |
# Example of how to authenticate with serverless deployment |
| 210 |
# |
| 211 |
- name: Update plugins on ECS Fargate Jenkins instance |
| 212 |
community.general.jenkins_plugin: |
| 213 |
# plugin name and version |
| 214 |
name: ws-cleanup |
| 215 |
version: '0.45' |
| 216 |
# Jenkins home path mounted on ec2-helper VM (example) |
| 217 |
jenkins_home: "/mnt/{{ jenkins_instance }}" |
| 218 |
# matching the UID/GID to one in official Jenkins image |
| 219 |
owner: 1000 |
| 220 |
group: 1000 |
| 221 |
# Jenkins instance URL and admin credentials |
| 222 |
url: "https://{{ jenkins_instance }}.com/" |
| 223 |
url_username: admin |
| 224 |
url_password: p4ssw0rd |
| 225 |
# make module work from EC2 which has local access |
| 226 |
# to EFS mount as well as Jenkins URL |
| 227 |
delegate_to: ec2-helper |
| 228 |
vars: |
| 229 |
jenkins_instance: foobar |
| 230 |
|
| 231 |
# |
| 232 |
# Example of a Play which handles Jenkins restarts during the state changes |
| 233 |
# |
| 234 |
- name: Jenkins Master play |
| 235 |
hosts: jenkins-master |
| 236 |
vars: |
| 237 |
my_jenkins_plugins: |
| 238 |
token-macro: |
| 239 |
enabled: true |
| 240 |
build-pipeline-plugin: |
| 241 |
version: "1.4.9" |
| 242 |
pinned: false |
| 243 |
enabled: true |
| 244 |
tasks: |
| 245 |
- name: Install plugins without a specific version |
| 246 |
community.general.jenkins_plugin: |
| 247 |
name: "{{ item.key }}" |
| 248 |
register: my_jenkins_plugin_unversioned |
| 249 |
when: > |
| 250 |
'version' not in item.value |
| 251 |
with_dict: "{{ my_jenkins_plugins }}" |
| 252 |
|
| 253 |
- name: Install plugins with a specific version |
| 254 |
community.general.jenkins_plugin: |
| 255 |
name: "{{ item.key }}" |
| 256 |
version: "{{ item.value['version'] }}" |
| 257 |
register: my_jenkins_plugin_versioned |
| 258 |
when: > |
| 259 |
'version' in item.value |
| 260 |
with_dict: "{{ my_jenkins_plugins }}" |
| 261 |
|
| 262 |
- name: Initiate the fact |
| 263 |
ansible.builtin.set_fact: |
| 264 |
jenkins_restart_required: false |
| 265 |
|
| 266 |
- name: Check if restart is required by any of the versioned plugins |
| 267 |
ansible.builtin.set_fact: |
| 268 |
jenkins_restart_required: true |
| 269 |
when: item.changed |
| 270 |
with_items: "{{ my_jenkins_plugin_versioned.results }}" |
| 271 |
|
| 272 |
- name: Check if restart is required by any of the unversioned plugins |
| 273 |
ansible.builtin.set_fact: |
| 274 |
jenkins_restart_required: true |
| 275 |
when: item.changed |
| 276 |
with_items: "{{ my_jenkins_plugin_unversioned.results }}" |
| 277 |
|
| 278 |
- name: Restart Jenkins if required |
| 279 |
ansible.builtin.service: |
| 280 |
name: jenkins |
| 281 |
state: restarted |
| 282 |
when: jenkins_restart_required |
| 283 |
|
| 284 |
- name: Wait for Jenkins to start up |
| 285 |
ansible.builtin.uri: |
| 286 |
url: http://localhost:8080 |
| 287 |
status_code: 200 |
| 288 |
timeout: 5 |
| 289 |
register: jenkins_service_status |
| 290 |
# Keep trying for 5 mins in 5 sec intervals |
| 291 |
retries: 60 |
| 292 |
delay: 5 |
| 293 |
until: > |
| 294 |
'status' in jenkins_service_status and |
| 295 |
jenkins_service_status['status'] == 200 |
| 296 |
when: jenkins_restart_required |
| 297 |
|
| 298 |
- name: Reset the fact |
| 299 |
ansible.builtin.set_fact: |
| 300 |
jenkins_restart_required: false |
| 301 |
when: jenkins_restart_required |
| 302 |
|
| 303 |
- name: Plugin pinning |
| 304 |
community.general.jenkins_plugin: |
| 305 |
name: "{{ item.key }}" |
| 306 |
state: "{{ 'pinned' if item.value['pinned'] else 'unpinned'}}" |
| 307 |
when: > |
| 308 |
'pinned' in item.value |
| 309 |
with_dict: "{{ my_jenkins_plugins }}" |
| 310 |
|
| 311 |
- name: Plugin enabling |
| 312 |
community.general.jenkins_plugin: |
| 313 |
name: "{{ item.key }}" |
| 314 |
state: "{{ 'enabled' if item.value['enabled'] else 'disabled'}}" |
| 315 |
when: > |
| 316 |
'enabled' in item.value |
| 317 |
with_dict: "{{ my_jenkins_plugins }}" |
| 318 |
""" |
| 319 |
|
| 320 |
RETURN = r""" |
| 321 |
plugin: |
| 322 |
description: Plugin name. |
| 323 |
returned: success |
| 324 |
type: str |
| 325 |
sample: build-pipeline-plugin |
| 326 |
state: |
| 327 |
description: State of the target, after execution. |
| 328 |
returned: success |
| 329 |
type: str |
| 330 |
sample: "present" |
| 331 |
""" |
| 332 |
|
| 333 |
import hashlib |
| 334 |
import json |
| 335 |
import os |
| 336 |
import tempfile |
| 337 |
import time |
| 338 |
from collections import OrderedDict |
| 339 |
from http import cookiejar |
| 340 |
from urllib.parse import urlencode |
| 341 |
|
| 342 |
from ansible.module_utils.basic import AnsibleModule, to_bytes |
| 343 |
from ansible.module_utils.urls import basic_auth_header, fetch_url, url_argument_spec |
| 344 |
|
| 345 |
from ansible_collections.community.general.plugins.module_utils._jenkins import download_updates_file |
| 346 |
|
| 347 |
|
| 348 |
class FailedInstallingWithPluginManager(Exception): |
| 349 |
pass |
| 350 |
|
| 351 |
|
| 352 |
class JenkinsPlugin: |
| 353 |
def __init__(self, module): |
| 354 |
# To be able to call fail_json |
| 355 |
self.module = module |
| 356 |
|
| 357 |
# Shortcuts for the params |
| 358 |
self.params = self.module.params |
| 359 |
self.url = self.params["url"] |
| 360 |
self.timeout = self.params["timeout"] |
| 361 |
|
| 362 |
# Authentication for non-Jenkins calls |
| 363 |
self.updates_url_credentials = {} |
| 364 |
if self.params.get("updates_url_username") and self.params.get("updates_url_password"): |
| 365 |
self.updates_url_credentials["Authorization"] = basic_auth_header( |
| 366 |
self.params["updates_url_username"], self.params["updates_url_password"] |
| 367 |
) |
| 368 |
|
| 369 |
# Crumb |
| 370 |
self.crumb = {} |
| 371 |
|
| 372 |
# Authentication for Jenkins calls |
| 373 |
if self.params.get("url_username") and self.params.get("url_password"): |
| 374 |
self.crumb["Authorization"] = basic_auth_header(self.params["url_username"], self.params["url_password"]) |
| 375 |
|
| 376 |
# Cookie jar for crumb session |
| 377 |
self.cookies = None |
| 378 |
|
| 379 |
if self._csrf_enabled(): |
| 380 |
self.cookies = cookiejar.LWPCookieJar() |
| 381 |
self._get_crumb() |
| 382 |
|
| 383 |
# Get list of installed plugins |
| 384 |
self._get_installed_plugins() |
| 385 |
|
| 386 |
def _csrf_enabled(self): |
| 387 |
csrf_data = self._get_json_data(f"{self.url}/api/json", "CSRF") |
| 388 |
|
| 389 |
if "useCrumbs" not in csrf_data: |
| 390 |
self.module.fail_json(msg="Required fields not found in the Crumbs response.", details=csrf_data) |
| 391 |
|
| 392 |
return csrf_data["useCrumbs"] |
| 393 |
|
| 394 |
def _get_json_data(self, url, what, **kwargs): |
| 395 |
# Get the JSON data |
| 396 |
r = self._get_url_data(url, what, **kwargs) |
| 397 |
|
| 398 |
# Parse the JSON data |
| 399 |
try: |
| 400 |
json_data = json.loads(r.read()) |
| 401 |
except Exception as e: |
| 402 |
self.module.fail_json(msg=f"Cannot parse {what} JSON data.", details=f"{e}") |
| 403 |
|
| 404 |
return json_data |
| 405 |
|
| 406 |
def _get_urls_data(self, urls, what=None, msg_status=None, msg_exception=None, **kwargs): |
| 407 |
# Compose default messages |
| 408 |
if msg_status is None: |
| 409 |
msg_status = f"Cannot get {what}" |
| 410 |
|
| 411 |
if msg_exception is None: |
| 412 |
msg_exception = f"Retrieval of {what} failed." |
| 413 |
|
| 414 |
errors = {} |
| 415 |
for url in urls: |
| 416 |
err_msg = None |
| 417 |
try: |
| 418 |
self.module.debug(f"fetching url: {url}") |
| 419 |
|
| 420 |
is_jenkins_call = url.startswith(self.url) |
| 421 |
self.module.params["force_basic_auth"] = is_jenkins_call |
| 422 |
|
| 423 |
response, info = fetch_url( |
| 424 |
self.module, |
| 425 |
url, |
| 426 |
timeout=self.timeout, |
| 427 |
cookies=self.cookies, |
| 428 |
headers=self.crumb if is_jenkins_call else self.updates_url_credentials or self.crumb, |
| 429 |
**kwargs, |
| 430 |
) |
| 431 |
if info["status"] == 200: |
| 432 |
return response |
| 433 |
else: |
| 434 |
err_msg = f"{msg_status}. fetching url {url} failed. response code: {info['status']}" |
| 435 |
if info["status"] > 400: # extend error message |
| 436 |
err_msg = f"{err_msg}. response body: {info['body']}" |
| 437 |
except Exception as e: |
| 438 |
err_msg = f"{msg_status}. fetching url {url} failed. error msg: {e}" |
| 439 |
finally: |
| 440 |
if err_msg is not None: |
| 441 |
self.module.debug(err_msg) |
| 442 |
errors[url] = err_msg |
| 443 |
|
| 444 |
# failed on all urls |
| 445 |
self.module.fail_json(msg=msg_exception, details=errors) |
| 446 |
|
| 447 |
def _get_url_data(self, url, what=None, msg_status=None, msg_exception=None, dont_fail=False, **kwargs): |
| 448 |
# Compose default messages |
| 449 |
if msg_status is None: |
| 450 |
msg_status = f"Cannot get {what}" |
| 451 |
|
| 452 |
if msg_exception is None: |
| 453 |
msg_exception = f"Retrieval of {what} failed." |
| 454 |
|
| 455 |
# Get the URL data |
| 456 |
try: |
| 457 |
is_jenkins_call = url.startswith(self.url) |
| 458 |
self.module.params["force_basic_auth"] = is_jenkins_call |
| 459 |
|
| 460 |
response, info = fetch_url( |
| 461 |
self.module, |
| 462 |
url, |
| 463 |
timeout=self.timeout, |
| 464 |
cookies=self.cookies, |
| 465 |
headers=self.crumb if is_jenkins_call else self.updates_url_credentials or self.crumb, |
| 466 |
**kwargs, |
| 467 |
) |
| 468 |
|
| 469 |
if info["status"] != 200: |
| 470 |
if dont_fail: |
| 471 |
raise FailedInstallingWithPluginManager(info["msg"]) |
| 472 |
else: |
| 473 |
self.module.fail_json(msg=msg_status, details=info["msg"]) |
| 474 |
except Exception as e: |
| 475 |
if dont_fail: |
| 476 |
raise FailedInstallingWithPluginManager(e) from e |
| 477 |
else: |
| 478 |
self.module.fail_json(msg=msg_exception, details=f"{e}") |
| 479 |
|
| 480 |
return response |
| 481 |
|
| 482 |
def _get_crumb(self): |
| 483 |
crumb_data = self._get_json_data(f"{self.url}/crumbIssuer/api/json", "Crumb") |
| 484 |
|
| 485 |
if "crumbRequestField" in crumb_data and "crumb" in crumb_data: |
| 486 |
self.crumb[crumb_data["crumbRequestField"]] = crumb_data["crumb"] |
| 487 |
else: |
| 488 |
self.module.fail_json(msg="Required fields not found in the Crum response.", details=crumb_data) |
| 489 |
|
| 490 |
def _get_installed_plugins(self): |
| 491 |
plugins_data = self._get_json_data(f"{self.url}/pluginManager/api/json?depth=1", "list of plugins") |
| 492 |
|
| 493 |
# Check if we got valid data |
| 494 |
if "plugins" not in plugins_data: |
| 495 |
self.module.fail_json(msg="No valid plugin data found.") |
| 496 |
|
| 497 |
# Create final list of installed/pined plugins |
| 498 |
self.is_installed = False |
| 499 |
self.is_pinned = False |
| 500 |
self.is_enabled = False |
| 501 |
self.installed_plugins = plugins_data["plugins"] |
| 502 |
|
| 503 |
for p in plugins_data["plugins"]: |
| 504 |
if p["shortName"] == self.params["name"]: |
| 505 |
self.is_installed = True |
| 506 |
|
| 507 |
if p["pinned"]: |
| 508 |
self.is_pinned = True |
| 509 |
|
| 510 |
if p["enabled"]: |
| 511 |
self.is_enabled = True |
| 512 |
|
| 513 |
break |
| 514 |
|
| 515 |
def _install_dependencies(self): |
| 516 |
dependencies = self._get_versioned_dependencies() |
| 517 |
self.dependencies_states = [] |
| 518 |
|
| 519 |
for dep_name, dep_version in dependencies.items(): |
| 520 |
if not any(p["shortName"] == dep_name and p["version"] == dep_version for p in self.installed_plugins): |
| 521 |
dep_params = self.params.copy() |
| 522 |
dep_params["name"] = dep_name |
| 523 |
dep_params["version"] = dep_version |
| 524 |
dep_module = AnsibleModule( |
| 525 |
argument_spec=self.module.argument_spec, supports_check_mode=self.module.check_mode |
| 526 |
) |
| 527 |
dep_module.params = dep_params |
| 528 |
dep_plugin = JenkinsPlugin(dep_module) |
| 529 |
if not dep_plugin.install(): |
| 530 |
self.dependencies_states.append({"name": dep_name, "version": dep_version, "state": "absent"}) |
| 531 |
else: |
| 532 |
self.dependencies_states.append({"name": dep_name, "version": dep_version, "state": "present"}) |
| 533 |
else: |
| 534 |
self.dependencies_states.append({"name": dep_name, "version": dep_version, "state": "present"}) |
| 535 |
|
| 536 |
def _install_with_plugin_manager(self): |
| 537 |
if not self.module.check_mode: |
| 538 |
# Install the plugin (with dependencies) |
| 539 |
install_script = ( |
| 540 |
f"""d = Jenkins.instance.updateCenter.getPlugin("{self.params["name"]}").deploy(); d.get();""" |
| 541 |
) |
| 542 |
|
| 543 |
if self.params["with_dependencies"]: |
| 544 |
install_script = ( |
| 545 |
f'Jenkins.instance.updateCenter.getPlugin("{self.params["name"]}")' |
| 546 |
f".getNeededDependencies().each{{it.deploy()}}; {install_script}" |
| 547 |
) |
| 548 |
|
| 549 |
script_data = {"script": install_script} |
| 550 |
data = urlencode(script_data) |
| 551 |
|
| 552 |
# Send the installation request |
| 553 |
self._get_url_data( |
| 554 |
f"{self.url}/scriptText", |
| 555 |
msg_status="Cannot install plugin.", |
| 556 |
msg_exception="Plugin installation has failed.", |
| 557 |
data=data, |
| 558 |
dont_fail=True, |
| 559 |
) |
| 560 |
|
| 561 |
hpi_file = f"{self.params['jenkins_home']}/plugins/{self.params['name']}.hpi" |
| 562 |
|
| 563 |
if os.path.isfile(hpi_file): |
| 564 |
os.remove(hpi_file) |
| 565 |
|
| 566 |
def install(self): |
| 567 |
changed = False |
| 568 |
plugin_file = f"{self.params['jenkins_home']}/plugins/{self.params['name']}.jpi" |
| 569 |
|
| 570 |
if not self.is_installed and self.params["version"] in [None, "latest"]: |
| 571 |
try: |
| 572 |
self._install_with_plugin_manager() |
| 573 |
changed = True |
| 574 |
except FailedInstallingWithPluginManager: # Fallback to manually downloading the plugin |
| 575 |
pass |
| 576 |
|
| 577 |
if not changed: |
| 578 |
# Check if the plugin directory exists |
| 579 |
if not os.path.isdir(self.params["jenkins_home"]): |
| 580 |
self.module.fail_json(msg="Jenkins home directory doesn't exist.") |
| 581 |
|
| 582 |
checksum_old = None |
| 583 |
if os.path.isfile(plugin_file): |
| 584 |
# Make the checksum of the currently installed plugin |
| 585 |
with open(plugin_file, "rb") as plugin_fh: |
| 586 |
plugin_content = plugin_fh.read() |
| 587 |
checksum_old = hashlib.sha1(plugin_content).hexdigest() |
| 588 |
|
| 589 |
# Install dependencies |
| 590 |
if self.params["with_dependencies"]: |
| 591 |
self._install_dependencies() |
| 592 |
|
| 593 |
if self.params["version"] in [None, "latest"]: |
| 594 |
# Take latest version |
| 595 |
plugin_urls = self._get_latest_plugin_urls() |
| 596 |
else: |
| 597 |
# Take specific version |
| 598 |
plugin_urls = self._get_versioned_plugin_urls() |
| 599 |
if ( |
| 600 |
self.params["updates_expiration"] == 0 |
| 601 |
or self.params["version"] not in [None, "latest"] |
| 602 |
or checksum_old is None |
| 603 |
): |
| 604 |
# Download the plugin file directly |
| 605 |
r = self._download_plugin(plugin_urls) |
| 606 |
|
| 607 |
# Write downloaded plugin into file if checksums don't match |
| 608 |
if checksum_old is None: |
| 609 |
# No previously installed plugin |
| 610 |
if not self.module.check_mode: |
| 611 |
self._write_file(plugin_file, r) |
| 612 |
|
| 613 |
changed = True |
| 614 |
else: |
| 615 |
# Get data for the MD5 |
| 616 |
data = r.read() |
| 617 |
|
| 618 |
# Make new checksum |
| 619 |
checksum_new = hashlib.sha1(data).hexdigest() |
| 620 |
|
| 621 |
# If the checksum is different from the currently installed |
| 622 |
# plugin, store the new plugin |
| 623 |
if checksum_old != checksum_new: |
| 624 |
if not self.module.check_mode: |
| 625 |
self._write_file(plugin_file, data) |
| 626 |
|
| 627 |
changed = True |
| 628 |
elif self.params["version"] == "latest": |
| 629 |
# Check for update from the updates JSON file |
| 630 |
plugin_data = self._download_updates() |
| 631 |
|
| 632 |
# If the latest version changed, download it |
| 633 |
if checksum_old != to_bytes(plugin_data["sha1"]): |
| 634 |
if not self.module.check_mode: |
| 635 |
r = self._download_plugin(plugin_urls) |
| 636 |
self._write_file(plugin_file, r) |
| 637 |
|
| 638 |
changed = True |
| 639 |
|
| 640 |
# Change file attributes if needed |
| 641 |
if os.path.isfile(plugin_file): |
| 642 |
params = {"dest": plugin_file} |
| 643 |
params.update(self.params) |
| 644 |
file_args = self.module.load_file_common_arguments(params) |
| 645 |
|
| 646 |
if not self.module.check_mode: |
| 647 |
# Not sure how to run this in the check mode |
| 648 |
changed = self.module.set_fs_attributes_if_different(file_args, changed) |
| 649 |
else: |
| 650 |
# See the comment above |
| 651 |
changed = True |
| 652 |
|
| 653 |
return changed |
| 654 |
|
| 655 |
def _get_latest_plugin_urls(self): |
| 656 |
urls = [] |
| 657 |
for base_url in self.params["updates_url"]: |
| 658 |
for update_segment in self.params["latest_plugins_url_segments"]: |
| 659 |
urls.append(f"{base_url}/{update_segment}/{self.params['name']}.hpi") |
| 660 |
return urls |
| 661 |
|
| 662 |
def _get_latest_compatible_plugin_version(self, plugin_name=None): |
| 663 |
if not hasattr(self, "jenkins_version"): |
| 664 |
self.module.params["force_basic_auth"] = True |
| 665 |
resp, info = fetch_url(self.module, self.url) |
| 666 |
raw_version = info.get("x-jenkins") |
| 667 |
self.jenkins_version = self.parse_version(raw_version) |
| 668 |
name = plugin_name or self.params["name"] |
| 669 |
cache_path = f"{self.params['jenkins_home']}/ansible_jenkins_plugin_cache.json" |
| 670 |
plugin_version_urls = [] |
| 671 |
for base_url in self.params["updates_url"]: |
| 672 |
for update_json in self.params["plugin_versions_url_segment"]: |
| 673 |
plugin_version_urls.append(f"{base_url}/{update_json}") |
| 674 |
|
| 675 |
try: # Check if file is saved localy |
| 676 |
if os.path.exists(cache_path): |
| 677 |
file_mtime = os.path.getmtime(cache_path) |
| 678 |
else: |
| 679 |
file_mtime = 0 |
| 680 |
|
| 681 |
now = time.time() |
| 682 |
if now - file_mtime >= 86400: |
| 683 |
response = self._get_urls_data(plugin_version_urls, what="plugin-versions.json") |
| 684 |
plugin_data = json.loads(response.read(), object_pairs_hook=OrderedDict) |
| 685 |
|
| 686 |
# Save it to file for next time |
| 687 |
with open(cache_path, "w") as f: |
| 688 |
json.dump(plugin_data, f) |
| 689 |
|
| 690 |
with open(cache_path) as f: |
| 691 |
plugin_data = json.load(f) |
| 692 |
|
| 693 |
except Exception as e: |
| 694 |
if os.path.exists(cache_path): |
| 695 |
os.remove(cache_path) |
| 696 |
self.module.fail_json(msg="Failed to parse plugin-versions.json", details=f"{e}") |
| 697 |
|
| 698 |
plugin_versions = plugin_data.get("plugins", {}).get(name) |
| 699 |
if not plugin_versions: |
| 700 |
self.module.fail_json(msg=f"Plugin '{name}' not found.") |
| 701 |
|
| 702 |
sorted_versions = list(reversed(plugin_versions.items())) |
| 703 |
|
| 704 |
for idx, (version_title, version_info) in enumerate(sorted_versions): |
| 705 |
required_core = version_info.get("requiredCore", "0.0") |
| 706 |
if self.parse_version(required_core) <= self.jenkins_version: |
| 707 |
return "latest" if idx == 0 else version_title |
| 708 |
|
| 709 |
self.module.warn(f"No compatible version found for plugin '{name}'. Installing latest version.") |
| 710 |
return "latest" |
| 711 |
|
| 712 |
def _get_versioned_plugin_urls(self): |
| 713 |
urls = [] |
| 714 |
for base_url in self.params["updates_url"]: |
| 715 |
for versioned_segment in self.params["versioned_plugins_url_segments"]: |
| 716 |
urls.append( |
| 717 |
f"{base_url}/{versioned_segment}/{self.params['name']}/{self.params['version']}/{self.params['name']}.hpi" |
| 718 |
) |
| 719 |
return urls |
| 720 |
|
| 721 |
def _get_update_center_urls(self): |
| 722 |
urls = [] |
| 723 |
for base_url in self.params["updates_url"]: |
| 724 |
for update_json in self.params["update_json_url_segment"]: |
| 725 |
urls.append(f"{base_url}/{update_json}") |
| 726 |
return urls |
| 727 |
|
| 728 |
def _get_versioned_dependencies(self): |
| 729 |
# Get dependencies for the specified plugin version |
| 730 |
plugin_data = self._download_updates()["dependencies"] |
| 731 |
|
| 732 |
dependencies_info = { |
| 733 |
dep["name"]: self._get_latest_compatible_plugin_version(dep["name"]) |
| 734 |
for dep in plugin_data |
| 735 |
if not dep.get("optional", False) |
| 736 |
} |
| 737 |
|
| 738 |
return dependencies_info |
| 739 |
|
| 740 |
def _download_updates(self): |
| 741 |
try: |
| 742 |
updates_file, download_updates = download_updates_file(self.params["updates_expiration"]) |
| 743 |
except OSError as e: |
| 744 |
self.module.fail_json(msg="Cannot create temporal directory.", details=f"{e}") |
| 745 |
|
| 746 |
# Download the updates file if needed |
| 747 |
if download_updates: |
| 748 |
urls = self._get_update_center_urls() |
| 749 |
|
| 750 |
# Get the data |
| 751 |
r = self._get_urls_data( |
| 752 |
urls, msg_status="Remote updates not found.", msg_exception="Updates download failed." |
| 753 |
) |
| 754 |
|
| 755 |
# Write the updates file |
| 756 |
tmp_update_fd, tmp_updates_file = tempfile.mkstemp() |
| 757 |
os.write(tmp_update_fd, r.read()) |
| 758 |
|
| 759 |
try: |
| 760 |
os.close(tmp_update_fd) |
| 761 |
except OSError as e: |
| 762 |
self.module.fail_json(msg=f"Cannot close the tmp updates file {tmp_updates_file}.", details=f"{e}") |
| 763 |
else: |
| 764 |
tmp_updates_file = updates_file |
| 765 |
|
| 766 |
# Open the updates file |
| 767 |
try: |
| 768 |
f = open(tmp_updates_file, encoding="utf-8") |
| 769 |
|
| 770 |
# Read only the second line |
| 771 |
dummy = f.readline() |
| 772 |
data = json.loads(f.readline()) |
| 773 |
except OSError as e: |
| 774 |
self.module.fail_json( |
| 775 |
msg=f"Cannot open{' temporary' if tmp_updates_file != updates_file else ''} updates file.", |
| 776 |
details=f"{e}", |
| 777 |
) |
| 778 |
except Exception as e: |
| 779 |
self.module.fail_json( |
| 780 |
msg=f"Cannot load JSON data from the{' temporary' if tmp_updates_file != updates_file else ''} updates file.", |
| 781 |
details=f"{e}", |
| 782 |
) |
| 783 |
|
| 784 |
# Move the updates file to the right place if we could read it |
| 785 |
if tmp_updates_file != updates_file: |
| 786 |
self.module.atomic_move(os.path.abspath(tmp_updates_file), os.path.abspath(updates_file)) |
| 787 |
|
| 788 |
# Check if we have the plugin data available |
| 789 |
if not data.get("plugins", {}).get(self.params["name"]): |
| 790 |
self.module.fail_json(msg="Cannot find plugin data in the updates file.") |
| 791 |
|
| 792 |
return data["plugins"][self.params["name"]] |
| 793 |
|
| 794 |
def _download_plugin(self, plugin_urls): |
| 795 |
# Download the plugin |
| 796 |
|
| 797 |
return self._get_urls_data(plugin_urls, msg_status="Plugin not found.", msg_exception="Plugin download failed.") |
| 798 |
|
| 799 |
def _write_file(self, f, data): |
| 800 |
# Store the plugin into a temp file and then move it |
| 801 |
tmp_f_fd, tmp_f = tempfile.mkstemp() |
| 802 |
|
| 803 |
if isinstance(data, (str, bytes)): |
| 804 |
os.write(tmp_f_fd, data) |
| 805 |
else: |
| 806 |
os.write(tmp_f_fd, data.read()) |
| 807 |
|
| 808 |
try: |
| 809 |
os.close(tmp_f_fd) |
| 810 |
except OSError as e: |
| 811 |
self.module.fail_json(msg=f"Cannot close the temporal plugin file {tmp_f}.", details=f"{e}") |
| 812 |
|
| 813 |
# Move the file onto the right place |
| 814 |
self.module.atomic_move(os.path.abspath(tmp_f), os.path.abspath(f)) |
| 815 |
|
| 816 |
def uninstall(self): |
| 817 |
changed = False |
| 818 |
|
| 819 |
# Perform the action |
| 820 |
if self.is_installed: |
| 821 |
if not self.module.check_mode: |
| 822 |
self._pm_query("doUninstall", "Uninstallation") |
| 823 |
|
| 824 |
changed = True |
| 825 |
|
| 826 |
return changed |
| 827 |
|
| 828 |
def pin(self): |
| 829 |
return self._pinning("pin") |
| 830 |
|
| 831 |
def unpin(self): |
| 832 |
return self._pinning("unpin") |
| 833 |
|
| 834 |
def _pinning(self, action): |
| 835 |
changed = False |
| 836 |
|
| 837 |
# Check if the plugin is pinned/unpinned |
| 838 |
if action == "pin" and not self.is_pinned or action == "unpin" and self.is_pinned: |
| 839 |
# Perform the action |
| 840 |
if not self.module.check_mode: |
| 841 |
self._pm_query(action, f"{action.capitalize()}ning") |
| 842 |
|
| 843 |
changed = True |
| 844 |
|
| 845 |
return changed |
| 846 |
|
| 847 |
def enable(self): |
| 848 |
return self._enabling("enable") |
| 849 |
|
| 850 |
def disable(self): |
| 851 |
return self._enabling("disable") |
| 852 |
|
| 853 |
def _enabling(self, action): |
| 854 |
changed = False |
| 855 |
|
| 856 |
# Check if the plugin is pinned/unpinned |
| 857 |
if action == "enable" and not self.is_enabled or action == "disable" and self.is_enabled: |
| 858 |
# Perform the action |
| 859 |
if not self.module.check_mode: |
| 860 |
self._pm_query(f"make{action.capitalize()}d", f"{action[:-1].capitalize()}ing") |
| 861 |
|
| 862 |
changed = True |
| 863 |
|
| 864 |
return changed |
| 865 |
|
| 866 |
def _pm_query(self, action, msg): |
| 867 |
url = f"{self.params['url']}/pluginManager/plugin/{self.params['name']}/{action}" |
| 868 |
|
| 869 |
# Send the request |
| 870 |
self._get_url_data( |
| 871 |
url, msg_status=f"Plugin not found. {url}", msg_exception=f"{msg} has failed.", method="POST" |
| 872 |
) |
| 873 |
|
| 874 |
@staticmethod |
| 875 |
def parse_version(version_str): |
| 876 |
return tuple(int(x) for x in version_str.split(".")) |
| 877 |
|
| 878 |
|
| 879 |
def main(): |
| 880 |
# Module arguments |
| 881 |
argument_spec = url_argument_spec() |
| 882 |
argument_spec.update( |
| 883 |
group=dict(type="str", default="jenkins"), |
| 884 |
jenkins_home=dict(type="path", default="/var/lib/jenkins"), |
| 885 |
mode=dict(default="0644", type="raw"), |
| 886 |
name=dict(type="str", required=True), |
| 887 |
owner=dict(type="str", default="jenkins"), |
| 888 |
state=dict( |
| 889 |
choices=["present", "absent", "pinned", "unpinned", "enabled", "disabled", "latest"], default="present" |
| 890 |
), |
| 891 |
timeout=dict(default=30, type="int"), |
| 892 |
updates_expiration=dict(default=86400, type="int"), |
| 893 |
updates_url=dict( |
| 894 |
type="list", elements="str", default=["https://updates.jenkins.io", "http://mirrors.jenkins.io"] |
| 895 |
), |
| 896 |
updates_url_username=dict(type="str"), |
| 897 |
updates_url_password=dict(type="str", no_log=True), |
| 898 |
update_json_url_segment=dict( |
| 899 |
type="list", elements="str", default=["update-center.json", "updates/update-center.json"] |
| 900 |
), |
| 901 |
plugin_versions_url_segment=dict( |
| 902 |
type="list", elements="str", default=["plugin-versions.json", "current/plugin-versions.json"] |
| 903 |
), |
| 904 |
latest_plugins_url_segments=dict(type="list", elements="str", default=["latest"]), |
| 905 |
versioned_plugins_url_segments=dict(type="list", elements="str", default=["download/plugins", "plugins"]), |
| 906 |
url=dict(default="http://localhost:8080"), |
| 907 |
url_password=dict(no_log=True), |
| 908 |
version=dict(), |
| 909 |
with_dependencies=dict(default=True, type="bool"), |
| 910 |
) |
| 911 |
# Module settings |
| 912 |
module = AnsibleModule( |
| 913 |
argument_spec=argument_spec, |
| 914 |
add_file_common_args=True, |
| 915 |
supports_check_mode=True, |
| 916 |
) |
| 917 |
|
| 918 |
# Convert timeout to float |
| 919 |
try: |
| 920 |
module.params["timeout"] = float(module.params["timeout"]) |
| 921 |
except ValueError as e: |
| 922 |
module.fail_json(msg=f"Cannot convert {module.params['timeout']} to float.", details=f"{e}") |
| 923 |
# Instantiate the JenkinsPlugin object |
| 924 |
jp = JenkinsPlugin(module) |
| 925 |
|
| 926 |
# Set version to latest if state is latest |
| 927 |
if module.params["state"] == "latest": |
| 928 |
module.params["state"] = "present" |
| 929 |
module.params["version"] = jp._get_latest_compatible_plugin_version() |
| 930 |
|
| 931 |
# Set version to latest compatible version if version is latest |
| 932 |
if module.params["version"] == "latest": |
| 933 |
module.params["version"] = jp._get_latest_compatible_plugin_version() |
| 934 |
|
| 935 |
# Create some shortcuts |
| 936 |
name = module.params["name"] |
| 937 |
state = module.params["state"] |
| 938 |
|
| 939 |
# Initial change state of the task |
| 940 |
changed = False |
| 941 |
|
| 942 |
# Perform action depending on the requested state |
| 943 |
if state == "present": |
| 944 |
changed = jp.install() |
| 945 |
elif state == "absent": |
| 946 |
changed = jp.uninstall() |
| 947 |
elif state == "pinned": |
| 948 |
changed = jp.pin() |
| 949 |
elif state == "unpinned": |
| 950 |
changed = jp.unpin() |
| 951 |
elif state == "enabled": |
| 952 |
changed = jp.enable() |
| 953 |
elif state == "disabled": |
| 954 |
changed = jp.disable() |
| 955 |
|
| 956 |
# Print status of the change |
| 957 |
module.exit_json( |
| 958 |
changed=changed, |
| 959 |
plugin=name, |
| 960 |
state=state, |
| 961 |
dependencies=jp.dependencies_states if hasattr(jp, "dependencies_states") else None, |
| 962 |
) |
| 963 |
|
| 964 |
|
| 965 |
if __name__ == "__main__": |
| 966 |
main() |