Debian Codegraph @

ansible_collections/community/zabbix/plugins/modules/zabbix_script.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2022, BGmot
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = """
12 module: zabbix_script
13 short_description: Create/update/delete Zabbix scripts
14 version_added: 1.7.0
15 author:
16 - Evgeny Yurchenko (@BGmot)
17 description:
18 - This module allows you to create, update and delete scripts.
19 requirements:
20 - "python >= 3.9"
21 options:
22 name:
23 description:
24 - Name of the script.
25 required: true
26 type: str
27 script_type:
28 description:
29 - Script type. Required when state is 'present'.
30 - A value of 'url' is only available in 7.0 or later
31 type: str
32 required: false
33 choices: ["script", "ipmi", "ssh", "telnet", "webhook", "url"]
34 url:
35 description:
36 - The URL for quick access
37 - Required if script_type is C(url)
38 - Only available if script_type is C(url)
39 type: str
40 new_window:
41 description:
42 - Should URL be opened in a new window?
43 - Only available if script_type is C(url)
44 type: bool
45 default: true
46 command:
47 description:
48 - Command to run. Required when state is 'present'
49 type: str
50 required: false
51 scope:
52 description:
53 - Script scope.
54 type: str
55 required: false
56 choices: ["action_operation", "manual_host_action", "manual_event_action"]
57 default: "action_operation"
58 execute_on:
59 description:
60 - Where to run the script.
61 - Used if type is C(script).
62 type: str
63 required: false
64 choices: ["zabbix_agent", "zabbix_server", "zabbix_server_proxy"]
65 default: "zabbix_server_proxy"
66 menu_path:
67 description:
68 - Folders separated by slash that form a menu like navigation in frontend when clicked on host or event.
69 - Used if scope is C(manual_host_action) or C(manual_event_action).
70 type: str
71 required: false
72 authtype:
73 description:
74 - Authentication method used for SSH script type.
75 - Used if type is C(ssh).
76 type: str
77 required: false
78 choices: ["password", "public_key"]
79 username:
80 description:
81 - User name used for authentication.
82 - Used if type is C(ssh) or C(telnet)
83 type: str
84 required: false
85 password:
86 description:
87 - Password used for SSH scripts with password authentication and Telnet scripts.
88 - Used if type is C(ssh) and authtype is C(password) or type is C(telnet).
89 type: str
90 required: false
91 publickey:
92 description:
93 - Name of the public key file used for SSH scripts with public key authentication.
94 - Used if type is C(ssh) and authtype is C(public_key).
95 type: str
96 required: false
97 privatekey:
98 description:
99 - Name of the private key file used for SSH scripts with public key authentication.
100 - Used if type is C(ssh) and authtype is C(public_key).
101 type: str
102 required: false
103 port:
104 description:
105 - Port number used for SSH and Telnet scripts.
106 - Used if type is C(ssh) or C(telnet).
107 type: str
108 required: false
109 host_group:
110 description:
111 - host group name that the script can be run on. If set to "all", the script will be available on all host groups.
112 type: str
113 required: false
114 default: "all"
115 user_group:
116 description:
117 - user group name that will be allowed to run the script. If set to "all", the script will be available for all user groups.
118 - Used if scope is C(manual_host_action) or C(manual_event_action).
119 type: str
120 required: false
121 default: "all"
122 host_access:
123 description:
124 - Host permissions needed to run the script.
125 - Used if scope is C(manual_host_action) or C(manual_event_action).
126 type: str
127 required: false
128 choices: ["read", "write"]
129 default: "read"
130 confirmation:
131 description:
132 - Confirmation pop up text. The pop up will appear when trying to run the script from the Zabbix frontend.
133 - Used if scope is C(manual_host_action) or C(manual_event_action).
134 type: str
135 required: false
136 script_timeout:
137 description:
138 - Webhook script execution timeout in seconds. Time suffixes are supported, e.g. 30s, 1m.
139 - Required if type is C(webhook).
140 - "Possible values: 1-60s."
141 type: str
142 default: "30s"
143 required: false
144 parameters:
145 description:
146 - Array of webhook input parameters.
147 - Used if type is C(webhook).
148 type: list
149 elements: dict
150 suboptions:
151 name:
152 description:
153 - Parameter name. Required when 'parameters' is specified for a 'webhook' script.
154 type: str
155 required: false
156 value:
157 description:
158 - Parameter value. Supports macros.
159 type: str
160 required: false
161 default: ""
162 description:
163 description:
164 - Description of the script.
165 type: str
166 required: false
167 state:
168 description:
169 - State of the script.
170 type: str
171 required: false
172 choices: ["present", "absent"]
173 default: "present"
174 user_input_enabled:
175 description:
176 - Allow advanced user input configuration
177 - Available for Zabbix >= 7.0.
178 type: bool
179 default: false
180 user_input_prompt:
181 description:
182 - Prompt to display when user input is enabled
183 - Required when user_input_enabled is C(True)
184 - Available for Zabbix >= 7.0.
185 type: str
186 user_input_type:
187 description:
188 - Choosing 'regex' allows the use of a regular expression
189 - Choosing 'dropdown' allows a pre-defined list of choices
190 - Required if user_input_enabled is C(true)
191 - Available for Zabbix >= 7.0.
192 type: str
193 choices: ["regex", "dropdown"]
194 user_input_regex:
195 description:
196 - A regular expression to validate user input
197 - Required if user_input_type is C(regex)
198 - Available for Zabbix >= 7.0.
199 type: str
200 user_input_list:
201 description:
202 - A list of possible choices for the user.
203 - Required if user_input_type is C(dropdown).
204 - NOTE the first option will be the default.
205 - Available for Zabbix >= 7.0.
206 type: list
207 elements: str
208 user_input_default_input:
209 description:
210 - Default user input
211 - Available if user_input_type is C(regex)
212 - Available for Zabbix >= 7.0.
213 type: str
214 extends_documentation_fragment:
215 - community.zabbix.zabbix
216
217 """
218
219 EXAMPLES = """
220 # If you want to use Username and Password to be authenticated by Zabbix Server
221 - name: Set credentials to access Zabbix Server API
222 ansible.builtin.set_fact:
223 ansible_user: Admin
224 ansible_httpapi_pass: zabbix
225
226 # If you want to use API token to be authenticated by Zabbix Server
227 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
228 - name: Set API token
229 ansible.builtin.set_fact:
230 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
231
232 - name: test - Create new action operation script to execute webhook
233 # set task level variables as we change ansible_connection plugin here
234 vars:
235 ansible_network_os: community.zabbix.zabbix
236 ansible_connection: httpapi
237 ansible_httpapi_port: 443
238 ansible_httpapi_use_ssl: true
239 ansible_httpapi_validate_certs: false
240 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
241 ansible_host: zabbix-example-fqdn.org
242 community.zabbix.zabbix_script:
243 name: Test action operation script
244 scope: action_operation
245 script_type: webhook
246 command: "return 0"
247 description: "Test action operation script"
248 state: present
249 """
250
251 RETURN = """
252 """
253
254
255 from ansible.module_utils.basic import AnsibleModule
256
257 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
258 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
259 from ansible.module_utils.compat.version import LooseVersion
260
261
262 class Script(ZabbixBase):
263 def get_script_ids(self, script_name):
264 script_ids = []
265 scripts = self._zapi.script.get({"filter": {"name": script_name}})
266 for script in scripts:
267 script_ids.append(script["scriptid"])
268 return script_ids
269
270 def create_script(self, name, script_type, command, scope, execute_on, menu_path, authtype, username, password,
271 publickey, privatekey, port, host_group, user_group, host_access, confirmation, script_timeout,
272 parameters, description, url, new_window, user_input_enabled, user_input_type, user_input_regex,
273 user_input_list, user_input_default_input, user_input_prompt):
274 if self._module.check_mode:
275 self._module.exit_json(changed=True)
276
277 self._zapi.script.create(self.generate_script_config(name, script_type, command, scope, execute_on, menu_path,
278 authtype, username, password, publickey, privatekey, port, host_group, user_group,
279 host_access, confirmation, script_timeout, parameters, description, url, new_window,
280 user_input_enabled, user_input_type, user_input_regex, user_input_list,
281 user_input_default_input, user_input_prompt))
282
283 def delete_script(self, script_ids):
284 if self._module.check_mode:
285 self._module.exit_json(changed=True)
286 self._zapi.script.delete(script_ids)
287
288 def generate_script_config(self, name, script_type, command, scope, execute_on, menu_path, authtype, username, password,
289 publickey, privatekey, port, host_group, user_group, host_access, confirmation, script_timeout,
290 parameters, description, url, new_window, user_input_enabled, user_input_type, user_input_regex,
291 user_input_list, user_input_default_input, user_input_prompt):
292 if host_group == "all":
293 groupid = "0"
294 else:
295 groups = self._zapi.hostgroup.get({"filter": {"name": host_group}})
296 if not groups:
297 self._module.fail_json(changed=False, msg="Host group '%s' not found" % host_group)
298 groupid = groups[0]["groupid"]
299
300 if user_group == "all":
301 usrgrpid = "0"
302 else:
303 user_groups = self._zapi.usergroup.get({"filter": {"name": user_group}})
304 if not user_groups:
305 self._module.fail_json(changed=False, msg="User group '%s' not found" % user_group)
306 usrgrpid = user_groups[0]["usrgrpid"]
307
308 request = {
309 "name": name,
310 "type": str(zabbix_utils.helper_to_numeric_value([
311 "script",
312 "ipmi",
313 "ssh",
314 "telnet",
315 "",
316 "webhook",
317 "url"], script_type)),
318 "scope": str(zabbix_utils.helper_to_numeric_value([
319 "",
320 "action_operation",
321 "manual_host_action",
322 "",
323 "manual_event_action"], scope)),
324 "groupid": groupid
325 }
326
327 if command:
328 request["command"] = command
329
330 if description is not None:
331 request["description"] = description
332
333 if script_type == "script":
334 if execute_on is None:
335 execute_on = "zabbix_server_proxy"
336 request["execute_on"] = str(zabbix_utils.helper_to_numeric_value([
337 "zabbix_agent",
338 "zabbix_server",
339 "zabbix_server_proxy"], execute_on))
340
341 if scope in ["manual_host_action", "manual_event_action"]:
342 if menu_path is None:
343 request["menu_path"] = ""
344 else:
345 request["menu_path"] = menu_path
346 request["usrgrpid"] = usrgrpid
347 request["host_access"] = str(zabbix_utils.helper_to_numeric_value([
348 "",
349 "",
350 "read",
351 "write"], host_access))
352 if confirmation is None:
353 request["confirmation"] = ""
354 else:
355 request["confirmation"] = confirmation
356
357 if script_type == "url":
358 request["url"] = url
359 if new_window:
360 request["new_window"] = "1"
361 else:
362 request["new_window"] = "0"
363
364 if script_type == "ssh":
365 request["authtype"] = str(zabbix_utils.helper_to_numeric_value([
366 "password",
367 "public_key"], authtype))
368 if authtype == "public_key":
369 request["publickey"] = publickey
370 request["privatekey"] = privatekey
371
372 if script_type in ["ssh", "telnet"]:
373 request["username"] = username
374 if (script_type == "ssh" and authtype == "password") or script_type == "telnet":
375 request["password"] = password
376 if port is not None:
377 request["port"] = port
378
379 if script_type == "webhook":
380 request["timeout"] = script_timeout
381 if parameters:
382 for parameter in parameters:
383 if "name" not in parameter.keys() or parameter["name"] is None:
384 self._module.fail_json(msg="When providing parameters to a webhook script, the 'name' option is required.")
385 request["parameters"] = parameters
386
387 if user_input_enabled:
388 request["manualinput_prompt"] = user_input_prompt
389 request["manualinput"] = "1"
390 if user_input_type == "regex":
391 request["manualinput_validator_type"] = "0"
392 request["manualinput_validator"] = user_input_regex
393 if user_input_default_input:
394 request["manualinput_default_value"] = user_input_default_input
395
396 else:
397 request["manualinput_validator_type"] = "1"
398 request["manualinput_validator"] = ",".join(user_input_list)
399
400 return request
401
402 def update_script(self, script_id, name, script_type, command, scope, execute_on, menu_path, authtype, username, password,
403 publickey, privatekey, port, host_group, user_group, host_access, confirmation, script_timeout, parameters,
404 description, url, new_window, user_input_enabled, user_input_type, user_input_regex, user_input_list,
405 user_input_default_input, user_input_prompt):
406 generated_config = self.generate_script_config(name, script_type, command, scope, execute_on, menu_path, authtype, username,
407 password, publickey, privatekey, port, host_group, user_group, host_access,
408 confirmation, script_timeout, parameters, description, url, new_window,
409 user_input_enabled, user_input_type, user_input_regex, user_input_list,
410 user_input_default_input, user_input_prompt)
411 live_config = self._zapi.script.get({"filter": {"name": name}})[0]
412
413 change_parameters = {}
414 difference = zabbix_utils.helper_cleanup_data(zabbix_utils.helper_compare_dictionaries(generated_config, live_config, change_parameters))
415
416 if not difference:
417 self._module.exit_json(changed=False, msg="Script %s up to date" % name)
418
419 if self._module.check_mode:
420 self._module.exit_json(changed=True)
421 generated_config["scriptid"] = live_config["scriptid"]
422 self._zapi.script.update(generated_config)
423 self._module.exit_json(changed=True, msg="Script %s updated" % name)
424
425
426 def main():
427 argument_spec = zabbix_utils.zabbix_common_argument_spec()
428 argument_spec.update(dict(
429 name=dict(type="str", required=True),
430 script_type=dict(
431 type="str",
432 choices=["script", "ipmi", "ssh", "telnet", "webhook", "url"]),
433 command=dict(type="str"),
434 url=dict(type="str"),
435 new_window=dict(type="bool", default=True),
436 scope=dict(
437 type="str",
438 choices=["action_operation", "manual_host_action", "manual_event_action"],
439 default="action_operation"),
440 execute_on=dict(
441 type="str",
442 choices=["zabbix_agent", "zabbix_server", "zabbix_server_proxy"],
443 default="zabbix_server_proxy"),
444 menu_path=dict(type="str"),
445 authtype=dict(
446 type="str",
447 choices=["password", "public_key"]),
448 username=dict(type="str"),
449 password=dict(type="str", no_log=True),
450 publickey=dict(type="str"),
451 privatekey=dict(type="str", no_log=True),
452 port=dict(type="str"),
453 host_group=dict(type="str", default="all"),
454 user_group=dict(type="str", default="all"),
455 host_access=dict(
456 type="str",
457 choices=["read", "write"],
458 default="read"),
459 confirmation=dict(type="str"),
460 script_timeout=dict(type="str", default="30s"),
461 parameters=dict(
462 type="list",
463 elements="dict",
464 options=dict(
465 name=dict(type="str"),
466 value=dict(type="str", default="")
467 )
468 ),
469 description=dict(type="str"),
470 user_input_enabled=dict(type="bool", default=False),
471 user_input_prompt=dict(type="str"),
472 user_input_type=dict(type="str", choices=["regex", "dropdown"]),
473 user_input_regex=dict(type="str"),
474 user_input_list=dict(type="list", elements="str"),
475 user_input_default_input=dict(type="str"),
476 state=dict(
477 type="str",
478 default="present",
479 choices=["present", "absent"])
480 ))
481
482 required_if = [
483 ("state", "present", ("script_type",)),
484 ("script_type", "ssh", ("authtype", "username", "command",)),
485 ("script_type", "url", ("new_window", "url",)),
486 ("authtype", "password", ("password",)),
487 ("authtype", "public_key", ("publickey", "privatekey",)),
488 ("script_type", "telnet", ("username", "password", "command",)),
489 ("script_type", "script", ("command",)),
490 ("script_type", "ipmi", ("command",)),
491 ("script_type", "webhook", ("command",)),
492 ("user_input_enabled", True, ("user_input_type", "user_input_prompt",)),
493 ("user_input_type", "regex", ("user_input_regex",)),
494 ("user_input_type", "dropdown", ("user_input_list",))
495 ]
496
497 module = AnsibleModule(
498 argument_spec=argument_spec,
499 required_if=required_if,
500 supports_check_mode=True
501 )
502
503 name = module.params["name"]
504 script_type = module.params["script_type"]
505 command = module.params["command"]
506 scope = module.params["scope"]
507 execute_on = module.params["execute_on"]
508 menu_path = module.params["menu_path"]
509 authtype = module.params["authtype"]
510 username = module.params["username"]
511 password = module.params["password"]
512 publickey = module.params["publickey"]
513 privatekey = module.params["privatekey"]
514 port = module.params["port"]
515 host_group = module.params["host_group"]
516 user_group = module.params["user_group"]
517 host_access = module.params["host_access"]
518 confirmation = module.params["confirmation"]
519 script_timeout = module.params["script_timeout"]
520 parameters = module.params["parameters"]
521 description = module.params["description"]
522 state = module.params["state"]
523 url = module.params["url"]
524 new_window = module.params["new_window"]
525 user_input_enabled = module.params["user_input_enabled"]
526 user_input_prompt = module.params["user_input_prompt"]
527 user_input_type = module.params["user_input_type"]
528 user_input_regex = module.params["user_input_regex"]
529 user_input_list = module.params["user_input_list"]
530 user_input_default_input = module.params["user_input_default_input"]
531
532 script = Script(module)
533 script_ids = script.get_script_ids(name)
534
535 # Delete script
536 if state == "absent":
537 if not script_ids:
538 module.exit_json(changed=False, msg="Script not found, no change: %s" % name)
539 script.delete_script(script_ids)
540 module.exit_json(changed=True, result="Successfully deleted script(s) %s" % name)
541
542 elif state == "present":
543 if script_type == "url":
544 if LooseVersion(script._zbx_api_version) < LooseVersion('7.0'):
545 module.fail_json(changed=False, msg="A type of 'url' is only available for Zabbix >= 7.0")
546 if scope not in ["manual_host_action", "manual_event_action"]:
547 module.fail_json(changed=False, msg="A scope of '%s' is not valid for type of 'url'" % scope)
548 else:
549 if url:
550 module.fail_json(changed=False, msg="A url can only be set for a type of 'url'")
551
552 if not user_input_enabled:
553 FIELDS = {
554 "user_input_prompt": user_input_prompt,
555 "user_input_type": user_input_type,
556 "user_input_regex": user_input_regex,
557 "user_input_list": user_input_list,
558 "user_input_default_input": user_input_default_input
559 }
560 for f, v in FIELDS.items():
561 if v:
562 module.fail_json(changed=False, msg=f"The attribute '{f}' can't be assigned unless user_input_enabled is 'True'")
563 else:
564 if LooseVersion(script._zbx_api_version) < LooseVersion('7.0'):
565 module.fail_json(changed=False, msg="user_input options are only available for Zabbix >= 7.0")
566 if len(user_input_prompt) < 1:
567 module.fail_json(changed=False, msg="The attribute 'user_input_prompt' is required when user_input_enabled is 'True'")
568 if user_input_type == "dropdown":
569 if len(user_input_list) < 1:
570 module.fail_json(changed=False, msg="The attribute 'user_input_list' cannot be empty when user_input_type is 'dropdown'")
571 if user_input_regex:
572 module.fail_json(changed=False, msg="The attribute 'user_input_regex' can't be assigned unless user_input_type is 'regex'")
573 elif user_input_default_input:
574 module.fail_json(changed=False, msg="The attribute 'user_input_default_input' can't be assigned unless user_input_type is 'regex'")
575 elif user_input_list:
576 module.fail_json(changed=False, msg="The attribute 'user_input_list' can't be assigned unless user_input_type is 'dropdown'")
577
578 if not script_ids:
579 script.create_script(name, script_type, command, scope, execute_on, menu_path, authtype, username, password,
580 publickey, privatekey, port, host_group, user_group, host_access, confirmation, script_timeout,
581 parameters, description, url, new_window, user_input_enabled, user_input_type, user_input_regex,
582 user_input_list, user_input_default_input, user_input_prompt)
583 module.exit_json(changed=True, msg="Script %s created" % name)
584 else:
585 script.update_script(script_ids[0], name, script_type, command, scope, execute_on, menu_path, authtype, username,
586 password, publickey, privatekey, port, host_group, user_group, host_access, confirmation,
587 script_timeout, parameters, description, url, new_window, user_input_enabled,
588 user_input_type, user_input_regex, user_input_list, user_input_default_input, user_input_prompt)
589
590
591 if __name__ == "__main__":
592 main()