Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2019, sky-joker
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_template_info
13 short_description: Gather information about Zabbix template
14 author:
15 - sky-joker (@sky-joker)
16 description:
17 - This module allows you to search for Zabbix template.
18 requirements:
19 - "python >= 3.9"
20 options:
21 template_name:
22 description:
23 - Name of the template in Zabbix.
24 required: false
25 type: str
26 format:
27 description:
28 - Format to use when dumping template.
29 choices: ["json", "xml", "yaml", "none"]
30 default: json
31 type: str
32 omit_date:
33 description:
34 - Removes the date field for the dumped template
35 - This parameter will be ignored since Zabbix 6.4.
36 required: false
37 type: bool
38 default: false
39 all_templategroups:
40 description:
41 - return info about all templategroups.
42 required: false
43 type: bool
44 extends_documentation_fragment:
45 - community.zabbix.zabbix
46 """
47
48 EXAMPLES = """
49 # If you want to use Username and Password to be authenticated by Zabbix Server
50 - name: Set credentials to access Zabbix Server API
51 ansible.builtin.set_fact:
52 ansible_user: Admin
53 ansible_httpapi_pass: zabbix
54
55 # If you want to use API token to be authenticated by Zabbix Server
56 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
57 - name: Set API token
58 ansible.builtin.set_fact:
59 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
60
61 - name: Get Zabbix template as JSON
62 # set task level variables as we change ansible_connection plugin here
63 vars:
64 ansible_network_os: community.zabbix.zabbix
65 ansible_connection: httpapi
66 ansible_httpapi_port: 443
67 ansible_httpapi_use_ssl: true
68 ansible_httpapi_validate_certs: false
69 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
70 ansible_host: zabbix-example-fqdn.org
71 community.zabbix.zabbix_template_info:
72 template_name: Template
73 format: json
74 omit_date: yes
75 register: template_json
76
77 - name: Get Zabbix template as XML
78 # set task level variables as we change ansible_connection plugin here
79 vars:
80 ansible_network_os: community.zabbix.zabbix
81 ansible_connection: httpapi
82 ansible_httpapi_port: 443
83 ansible_httpapi_use_ssl: true
84 ansible_httpapi_validate_certs: false
85 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
86 ansible_host: zabbix-example-fqdn.org
87 community.zabbix.zabbix_template_info:
88 template_name: Template
89 format: xml
90 omit_date: no
91 register: template_json
92
93 - name: Get Zabbix template as YAML
94 # set task level variables as we change ansible_connection plugin here
95 vars:
96 ansible_network_os: community.zabbix.zabbix
97 ansible_connection: httpapi
98 ansible_httpapi_port: 443
99 ansible_httpapi_use_ssl: true
100 ansible_httpapi_validate_certs: false
101 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
102 ansible_host: zabbix-example-fqdn.org
103 community.zabbix.zabbix_template_info:
104 template_name: Template
105 format: yaml
106 omit_date: no
107 register: template_yaml
108
109 - name: Determine if Zabbix template exists
110 # set task level variables as we change ansible_connection plugin here
111 vars:
112 ansible_network_os: community.zabbix.zabbix
113 ansible_connection: httpapi
114 ansible_httpapi_port: 443
115 ansible_httpapi_use_ssl: true
116 ansible_httpapi_validate_certs: false
117 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
118 ansible_host: zabbix-example-fqdn.org
119 community.zabbix.zabbix_template_info:
120 template_name: Template
121 format: none
122 register: template
123
124 - name: Get info about all templategroups
125 # set task level variables as we change ansible_connection plugin here
126 vars:
127 ansible_network_os: community.zabbix.zabbix
128 ansible_connection: httpapi
129 ansible_httpapi_port: 443
130 ansible_httpapi_use_ssl: true
131 ansible_httpapi_validate_certs: false
132 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
133 ansible_host: zabbix-example-fqdn.org
134 community.zabbix.zabbix_template_info:
135 all_templategroups: true
136 register: all_templategroups
137 """
138
139 RETURN = """
140 ---
141 template_id:
142 description: The ID of the template
143 returned: always
144 type: str
145
146 template_json:
147 description: The JSON of the template
148 returned: when format is json and omit_date is true
149 type: str
150 sample: {
151 "changed": false,
152 "failed": false,
153 "template_id": "10529",
154 "template_json": {
155 "zabbix_export": {
156 "groups": [
157 {
158 "name": "Templates",
159 "uuid": "7df96b18c230490a9a0a9e2307226338"
160 }
161 ],
162 "templates": [
163 {
164 "groups": [
165 {
166 "name": "Templates"
167 }
168 ],
169 "name": "ExampleTemplateForTempleteInfoModule",
170 "template": "ExampleTemplateForTempleteInfoModule",
171 "uuid": "615e9b0662bb4399a2503a9aaa743517"
172 }
173 ],
174 "version": "6.0"
175 }
176 }
177 }
178
179 template_xml:
180 description: The XML of the template
181 returned: when format is xml and omit_date is false
182 type: str
183 sample: >-
184 <zabbix_export>
185 <version>6.0</version>
186 <groups>
187 <group>
188 <uuid>7df96b18c230490a9a0a9e2307226338</uuid>
189 <name>Templates</name>
190 </group>
191 </groups>
192 <templates>
193 <template>
194 <uuid>9a83162273f74032a1005fdb13943038</uuid>
195 <template>ExampleTemplateForTempleteInfoModule</template>
196 <name>ExampleTemplateForTempleteInfoModule</name>
197 <groups>
198 <group>
199 <name>Templates</name>
200 </group>
201 </groups>
202 </template>
203 </templates>
204 </zabbix_export>
205
206 template_yaml:
207 description: The YAML of the template
208 returned: when format is yaml and omit_date is false
209 type: str
210 sample: >-
211 zabbix_export:
212 version: "6.0"
213 groups:
214 -
215 uuid: 7df96b18c230490a9a0a9e2307226338
216 name: Templates
217 templates:
218 -
219 uuid: 67b075276bf047d3aeb8f7d5c2121c6a
220 template: ExampleTemplateForTempleteInfoModule
221 name: ExampleTemplateForTempleteInfoModule
222 groups:
223 -
224 name: Templatesn
225 """
226
227
228 import traceback
229 import json
230 import xml.etree.ElementTree as ET
231
232 from ansible.module_utils.basic import AnsibleModule
233 from ansible.module_utils.compat.version import LooseVersion
234 from ansible.module_utils._text import to_native
235
236 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
237 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
238
239
240 class TemplateInfo(ZabbixBase):
241 def get_template_id(self, template_name):
242 template_id = []
243 try:
244 template_list = self._zapi.template.get({"output": ["templateid"],
245 "filter": {"host": template_name}})
246 except Exception as e:
247 self._module.fail_json(msg="Failed to get template: %s" % e)
248
249 if template_list:
250 template_id.append(template_list[0]["templateid"])
251
252 return template_id
253
254 def load_json_template(self, template_json, omit_date=False):
255 try:
256 jsondoc = json.loads(template_json)
257 # remove date field if requested
258 if omit_date and "date" in jsondoc["zabbix_export"]:
259 del jsondoc["zabbix_export"]["date"]
260 return jsondoc
261 except ValueError as e:
262 self._module.fail_json(msg="Invalid JSON provided", details=to_native(e), exception=traceback.format_exc())
263
264 def load_yaml_template(self, template_yaml, omit_date=False):
265 if omit_date and LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
266 yaml_lines = template_yaml.splitlines(True)
267 for index, line in enumerate(yaml_lines):
268 if "date:" in line:
269 del yaml_lines[index]
270 return "".join(yaml_lines)
271 else:
272 return template_yaml
273
274 def dump_template(self, template_id, template_type="json", omit_date=False):
275 try:
276 dump = self._zapi.configuration.export({"format": template_type, "options": {"templates": template_id}})
277 if template_type == "xml":
278 xmlroot = ET.fromstring(dump.encode("utf-8"))
279 # remove date field if requested
280 if omit_date:
281 date = xmlroot.find(".date")
282 if date is not None:
283 xmlroot.remove(date)
284 return str(ET.tostring(xmlroot, encoding="utf-8").decode("utf-8"))
285 elif template_type == "yaml":
286 return self.load_yaml_template(dump, omit_date)
287 else:
288 return self.load_json_template(dump, omit_date)
289 except Exception as e:
290 self._module.fail_json(msg="Unable to export template: %s" % e)
291
292 def get_all_groups(self):
293 group_list = self._zapi.templategroup.get({"output": "extend"})
294 if len(group_list) < 1:
295 self._module.fail_json(msg="No Hostgroup can be found")
296 return group_list
297
298
299 def main():
300 argument_spec = zabbix_utils.zabbix_common_argument_spec()
301 argument_spec.update(dict(
302 template_name=dict(type="str", required=False),
303 omit_date=dict(type="bool", required=False, default=False),
304 format=dict(type="str", choices=["json", "xml", "yaml", "none"], default="json"),
305 all_templategroups=dict(type="bool", required=False),
306 ))
307 module = AnsibleModule(
308 argument_spec=argument_spec,
309 supports_check_mode=True
310 )
311
312 template_name = module.params["template_name"]
313 all_templategroups = module.params["all_templategroups"]
314 omit_date = module.params["omit_date"]
315 format = module.params["format"]
316
317 template_info = TemplateInfo(module)
318
319 if template_name:
320 template_id = template_info.get_template_id(template_name)
321
322 if not template_id:
323 module.fail_json(msg="Template not found: %s" % template_name)
324
325 if format == "json":
326 module.exit_json(
327 changed=False,
328 template_id=template_id[0],
329 template_json=template_info.dump_template(template_id, template_type="json", omit_date=omit_date)
330 )
331 elif format == "xml":
332 module.exit_json(
333 changed=False,
334 template_id=template_id[0],
335 template_xml=template_info.dump_template(template_id, template_type="xml", omit_date=omit_date)
336 )
337 elif format == "yaml":
338 module.exit_json(
339 changed=False,
340 template_id=template_id[0],
341 template_yaml=template_info.dump_template(template_id, template_type="yaml", omit_date=omit_date)
342 )
343 elif format == "none":
344 module.exit_json(changed=False, template_id=template_id[0])
345
346 if all_templategroups:
347 template_groups = template_info.get_all_groups()
348 module.exit_json(template_groups=template_groups)
349
350
351 if __name__ == "__main__":
352 main()