Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) Ansible Project
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_node
11 short_description: Manage Jenkins nodes
12 version_added: 10.0.0
13 description:
14 - Manage Jenkins nodes with Jenkins REST API.
15 requirements:
16 - "python-jenkins >= 0.4.12"
17 author:
18 - Connor Newton (@phyrwork)
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: partial
24 details:
25 - Check mode is unable to show configuration changes for a node that is not yet present.
26 diff_mode:
27 support: none
28 options:
29 url:
30 description:
31 - URL of the Jenkins server.
32 default: http://localhost:8080
33 type: str
34 name:
35 description:
36 - Name of the Jenkins node to manage.
37 required: true
38 type: str
39 user:
40 description:
41 - User to authenticate with the Jenkins server.
42 type: str
43 token:
44 description:
45 - API token to authenticate with the Jenkins server.
46 type: str
47 state:
48 description:
49 - Specifies whether the Jenkins node should be V(present) (created), V(absent) (deleted), V(enabled) (online) or V(disabled)
50 (offline).
51 default: present
52 choices: ['enabled', 'disabled', 'present', 'absent']
53 type: str
54 num_executors:
55 description:
56 - When specified, sets the Jenkins node executor count.
57 type: int
58 labels:
59 description:
60 - When specified, sets the Jenkins node labels.
61 type: list
62 elements: str
63 offline_message:
64 description:
65 - Specifies the offline reason message to be set when configuring the Jenkins node state.
66 - If O(offline_message) is given and requested O(state) is not V(disabled), an error is raised.
67 - Internally O(offline_message) is set using the V(toggleOffline) API, so updating the message when the node is already
68 offline (current state V(disabled)) is not possible. In this case, a warning is issued.
69 type: str
70 version_added: 10.0.0
71 """
72
73 EXAMPLES = r"""
74 - name: Create a Jenkins node using token authentication
75 community.general.jenkins_node:
76 url: http://localhost:8080
77 user: jenkins
78 token: 11eb751baabb66c4d1cb8dc4e0fb142cde
79 name: my-node
80 state: present
81
82 - name: Set number of executors on Jenkins node
83 community.general.jenkins_node:
84 name: my-node
85 state: present
86 num_executors: 4
87
88 - name: Set labels on Jenkins node
89 community.general.jenkins_node:
90 name: my-node
91 state: present
92 labels:
93 - label-1
94 - label-2
95 - label-3
96
97 - name: Set Jenkins node offline with offline message.
98 community.general.jenkins_node:
99 name: my-node
100 state: disabled
101 offline_message: >-
102 This node is offline for some reason.
103 """
104
105 RETURN = r"""
106 url:
107 description: URL used to connect to the Jenkins server.
108 returned: success
109 type: str
110 sample: https://jenkins.mydomain.com
111 user:
112 description: User used for authentication.
113 returned: success
114 type: str
115 sample: jenkins
116 name:
117 description: Name of the Jenkins node.
118 returned: success
119 type: str
120 sample: my-node
121 state:
122 description: State of the Jenkins node.
123 returned: success
124 type: str
125 sample: present
126 created:
127 description: Whether or not the Jenkins node was created by the task.
128 returned: success
129 type: bool
130 deleted:
131 description: Whether or not the Jenkins node was deleted by the task.
132 returned: success
133 type: bool
134 disabled:
135 description: Whether or not the Jenkins node was disabled by the task.
136 returned: success
137 type: bool
138 enabled:
139 description: Whether or not the Jenkins node was enabled by the task.
140 returned: success
141 type: bool
142 configured:
143 description: Whether or not the Jenkins node was configured by the task.
144 returned: success
145 type: bool
146 """
147
148 import traceback
149 from xml.etree import ElementTree as et
150
151 from ansible.module_utils.basic import AnsibleModule
152
153 from ansible_collections.community.general.plugins.module_utils import _deps as deps
154
155 with deps.declare(
156 "python-jenkins",
157 reason="python-jenkins is required to interact with Jenkins",
158 url="https://opendev.org/jjb/python-jenkins",
159 ):
160 import jenkins
161
162
163 class JenkinsNode:
164 def __init__(self, module: AnsibleModule) -> None:
165 self.module = module
166
167 self.name = module.params["name"]
168 self.state = module.params["state"]
169 self.token = module.params["token"]
170 self.user = module.params["user"]
171 self.url = module.params["url"]
172 self.num_executors = module.params["num_executors"]
173 self.labels = module.params["labels"]
174 self.offline_message: str | None = module.params["offline_message"]
175
176 if self.offline_message is not None:
177 self.offline_message = self.offline_message.strip()
178
179 if self.state != "disabled":
180 self.module.fail_json("can not set offline message when state is not disabled")
181
182 if self.labels is not None:
183 for label in self.labels:
184 if " " in label:
185 self.module.fail_json(f"labels must not contain spaces: got invalid label {label}")
186
187 self.instance = self.get_jenkins_instance()
188 self.result = {
189 "changed": False,
190 "url": self.url,
191 "user": self.user,
192 "name": self.name,
193 "state": self.state,
194 "created": False,
195 "deleted": False,
196 "disabled": False,
197 "enabled": False,
198 "configured": False,
199 "warnings": [],
200 }
201
202 def get_jenkins_instance(self):
203 try:
204 if self.user and self.token:
205 return jenkins.Jenkins(self.url, self.user, self.token)
206 elif self.user and not self.token:
207 return jenkins.Jenkins(self.url, self.user)
208 else:
209 return jenkins.Jenkins(self.url)
210 except Exception as e:
211 self.module.fail_json(msg=f"Unable to connect to Jenkins server, {e}")
212
213 def configure_node(self, present):
214 if not present:
215 # Node would only not be present if in check mode and if not present there
216 # is no way to know what would and would not be changed.
217 if not self.module.check_mode:
218 raise Exception("configure_node present is False outside of check mode")
219 return
220
221 configured = False
222
223 data = self.instance.get_node_config(self.name)
224 root = et.fromstring(data)
225
226 if self.num_executors is not None:
227 elem = root.find("numExecutors")
228 if elem is None:
229 elem = et.SubElement(root, "numExecutors")
230 if elem.text is None or int(elem.text) != self.num_executors:
231 elem.text = str(self.num_executors)
232 configured = True
233
234 if self.labels is not None:
235 elem = root.find("label")
236 if elem is None:
237 elem = et.SubElement(root, "label")
238 labels = []
239 if elem.text:
240 labels = elem.text.split()
241 if labels != self.labels:
242 elem.text = " ".join(self.labels)
243 configured = True
244
245 if configured:
246 data = et.tostring(root, encoding="unicode")
247
248 self.instance.reconfig_node(self.name, data)
249
250 self.result["configured"] = configured
251 if configured:
252 self.result["changed"] = True
253
254 def present_node(self, configure=True): # type: (bool) -> bool
255 """Assert node present.
256
257 Args:
258 configure: If True, run node configuration after asserting node present.
259
260 Returns:
261 True if the node is present, False otherwise (i.e. is check mode).
262 """
263
264 def create_node():
265 try:
266 self.instance.create_node(self.name, launcher=jenkins.LAUNCHER_SSH)
267 except jenkins.JenkinsException as e:
268 # Some versions of python-jenkins < 1.8.3 has an authorization bug when
269 # handling redirects returned when posting to resources. If the node is
270 # created OK then can ignore the error.
271 if not self.instance.node_exists(self.name):
272 self.module.fail_json(msg=f"Create node failed: {e}", exception=traceback.format_exc())
273
274 # TODO: Remove authorization workaround.
275 self.result["warnings"].append(
276 "suppressed 401 Not Authorized on redirect after node created: see https://review.opendev.org/c/jjb/python-jenkins/+/931707"
277 )
278
279 present = self.instance.node_exists(self.name)
280 created = False
281 if not present:
282 if not self.module.check_mode:
283 create_node()
284 present = True
285
286 created = True
287
288 if configure:
289 self.configure_node(present)
290
291 self.result["created"] = created
292 if created:
293 self.result["changed"] = True
294
295 return present # Used to gate downstream queries when in check mode.
296
297 def absent_node(self):
298 def delete_node():
299 try:
300 self.instance.delete_node(self.name)
301 except jenkins.JenkinsException as e:
302 # Some versions of python-jenkins < 1.8.3 has an authorization bug when
303 # handling redirects returned when posting to resources. If the node is
304 # deleted OK then can ignore the error.
305 if self.instance.node_exists(self.name):
306 self.module.fail_json(msg=f"Delete node failed: {e}", exception=traceback.format_exc())
307
308 # TODO: Remove authorization workaround.
309 self.result["warnings"].append(
310 "suppressed 401 Not Authorized on redirect after node deleted: see https://review.opendev.org/c/jjb/python-jenkins/+/931707"
311 )
312
313 present = self.instance.node_exists(self.name)
314 deleted = False
315 if present:
316 if not self.module.check_mode:
317 delete_node()
318
319 deleted = True
320
321 self.result["deleted"] = deleted
322 if deleted:
323 self.result["changed"] = True
324
325 def enabled_node(self):
326 def get_offline(): # type: () -> bool
327 return self.instance.get_node_info(self.name)["offline"]
328
329 present = self.present_node()
330
331 enabled = False
332
333 if present:
334
335 def enable_node():
336 try:
337 self.instance.enable_node(self.name)
338 except jenkins.JenkinsException as e:
339 # Some versions of python-jenkins < 1.8.3 has an authorization bug when
340 # handling redirects returned when posting to resources. If the node is
341 # disabled OK then can ignore the error.
342 offline = get_offline()
343
344 if offline:
345 self.module.fail_json(msg=f"Enable node failed: {e}", exception=traceback.format_exc())
346
347 # TODO: Remove authorization workaround.
348 self.result["warnings"].append(
349 "suppressed 401 Not Authorized on redirect after node enabled: see https://review.opendev.org/c/jjb/python-jenkins/+/931707"
350 )
351
352 offline = get_offline()
353
354 if offline:
355 if not self.module.check_mode:
356 enable_node()
357
358 enabled = True
359 else:
360 # Would have created node with initial state enabled therefore would not have
361 # needed to enable therefore not enabled.
362 if not self.module.check_mode:
363 raise Exception("enabled_node present is False outside of check mode")
364 enabled = False
365
366 self.result["enabled"] = enabled
367 if enabled:
368 self.result["changed"] = True
369
370 def disabled_node(self):
371 def get_offline_info():
372 info = self.instance.get_node_info(self.name)
373
374 offline = info["offline"]
375 offline_message = info["offlineCauseReason"]
376
377 return offline, offline_message
378
379 # Don't configure until after disabled, in case the change in configuration
380 # causes the node to pick up a job.
381 present = self.present_node(False)
382
383 disabled = False
384 changed = False
385
386 if present:
387 offline, offline_message = get_offline_info()
388
389 if self.offline_message is not None and self.offline_message != offline_message:
390 if offline:
391 # n.b. Internally disable_node uses toggleOffline gated by a not
392 # offline condition. This means that disable_node can not be used to
393 # update an offline message if the node is already offline.
394 #
395 # Toggling the node online to set the message when toggling offline
396 # again is not an option as during this transient online time jobs
397 # may be scheduled on the node which is not acceptable.
398 self.result["warnings"].append("unable to change offline message when already offline")
399 else:
400 offline_message = self.offline_message
401 changed = True
402
403 def disable_node():
404 try:
405 self.instance.disable_node(self.name, offline_message)
406 except jenkins.JenkinsException as e:
407 # Some versions of python-jenkins < 1.8.3 has an authorization bug when
408 # handling redirects returned when posting to resources. If the node is
409 # disabled OK then can ignore the error.
410 offline, _offline_message = get_offline_info()
411
412 if not offline:
413 self.module.fail_json(msg=f"Disable node failed: {e}", exception=traceback.format_exc())
414
415 # TODO: Remove authorization workaround.
416 self.result["warnings"].append(
417 "suppressed 401 Not Authorized on redirect after node disabled: see https://review.opendev.org/c/jjb/python-jenkins/+/931707"
418 )
419
420 if not offline:
421 if not self.module.check_mode:
422 disable_node()
423
424 disabled = True
425
426 else:
427 # Would have created node with initial state enabled therefore would have
428 # needed to disable therefore disabled.
429 if not self.module.check_mode:
430 raise Exception("disabled_node present is False outside of check mode")
431 disabled = True
432
433 if disabled:
434 changed = True
435
436 self.result["disabled"] = disabled
437
438 if changed:
439 self.result["changed"] = True
440
441 self.configure_node(present)
442
443
444 def main():
445 module = AnsibleModule(
446 argument_spec=dict(
447 name=dict(required=True, type="str"),
448 url=dict(default="http://localhost:8080"),
449 user=dict(),
450 token=dict(no_log=True),
451 state=dict(choices=["enabled", "disabled", "present", "absent"], default="present"),
452 num_executors=dict(type="int"),
453 labels=dict(type="list", elements="str"),
454 offline_message=dict(type="str"),
455 ),
456 supports_check_mode=True,
457 )
458
459 deps.validate(module)
460
461 jenkins_node = JenkinsNode(module)
462
463 state = module.params.get("state")
464 if state == "enabled":
465 jenkins_node.enabled_node()
466 elif state == "disabled":
467 jenkins_node.disabled_node()
468 elif state == "present":
469 jenkins_node.present_node()
470 else:
471 jenkins_node.absent_node()
472
473 module.exit_json(**jenkins_node.result)
474
475
476 if __name__ == "__main__":
477 main()