Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) [email protected]
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7
8 from __future__ import (absolute_import, division, print_function)
9 __metaclass__ = type
10
11
12 RETURN = r"""
13 ---
14 hosts:
15 description: List of Zabbix hosts. See https://www.zabbix.com/documentation/4.0/manual/api/reference/host/get for list of host values.
16 returned: success
17 type: dict
18 sample: [ { "available": "1", "description": "", "disable_until": "0", "error": "", "flags": "0", "groups": ["1"], "host": "Host A", ... } ]
19 """
20
21 DOCUMENTATION = r"""
22 ---
23 module: zabbix_host_info
24 short_description: Gather information about Zabbix host
25 description:
26 - This module allows you to search for Zabbix host entries.
27 - This module was called C(zabbix_host_facts) before Ansible 2.9. The usage did not change.
28 author:
29 - "Michael Miko (@RedWhiteMiko)"
30 requirements:
31 - "python >= 3.9"
32 options:
33 host_name:
34 description:
35 - Name of the host in Zabbix.
36 - host_name is the unique identifier used and cannot be updated using this module.
37 - Required when I(host_ip) is not used.
38 - If neither host_name nor host_ip specified then all the hosts configured in Zabbix returned.
39 required: false
40 type: str
41 default: ""
42 host_ip:
43 description:
44 - Host interface IP of the host in Zabbix.
45 - Required when I(host_name) is not used.
46 required: false
47 type: list
48 elements: str
49 default: []
50 exact_match:
51 description:
52 - Find the exact match
53 type: bool
54 default: no
55 remove_duplicate:
56 description:
57 - Remove duplicate host from host result
58 type: bool
59 default: yes
60 host_inventory:
61 description:
62 - List of host inventory keys to display in result.
63 - Whole host inventory is retrieved if keys are not specified.
64 type: list
65 elements: str
66 required: false
67 default: []
68 extends_documentation_fragment:
69 - community.zabbix.zabbix
70
71 """
72
73 EXAMPLES = r"""
74 # If you want to use Username and Password to be authenticated by Zabbix Server
75 - name: Set credentials to access Zabbix Server API
76 ansible.builtin.set_fact:
77 ansible_user: Admin
78 ansible_httpapi_pass: zabbix
79
80 # If you want to use API token to be authenticated by Zabbix Server
81 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
82 - name: Set API token
83 ansible.builtin.set_fact:
84 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
85
86 - name: Get host info
87 # set task level variables as we change ansible_connection plugin here
88 vars:
89 ansible_network_os: community.zabbix.zabbix
90 ansible_connection: httpapi
91 ansible_httpapi_port: 443
92 ansible_httpapi_use_ssl: true
93 ansible_httpapi_validate_certs: false
94 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
95 ansible_host: zabbix-example-fqdn.org
96 community.zabbix.zabbix_host_info:
97 host_name: ExampleHost
98 host_ip: 127.0.0.1
99 exact_match: no
100 remove_duplicate: yes
101
102 - name: Reduce host inventory information to provided keys
103 # set task level variables as we change ansible_connection plugin here
104 vars:
105 ansible_network_os: community.zabbix.zabbix
106 ansible_connection: httpapi
107 ansible_httpapi_port: 443
108 ansible_httpapi_use_ssl: true
109 ansible_httpapi_validate_certs: false
110 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
111 ansible_host: zabbix-example-fqdn.org
112 community.zabbix.zabbix_host_info:
113 host_name: ExampleHost
114 host_inventory:
115 - os
116 - tag
117 host_ip: 127.0.0.1
118 exact_match: no
119 remove_duplicate: yes
120 """
121
122
123 from ansible.module_utils.basic import AnsibleModule
124
125 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
126 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
127 from ansible.module_utils.compat.version import LooseVersion
128
129
130 class Host(ZabbixBase):
131 def get_hosts_by_host_name(self, host_name, exact_match, host_inventory):
132 """ Get host by host name """
133 search_key = "search"
134 if exact_match:
135 search_key = "filter"
136 parameters = {
137 "output": "extend",
138 "selectParentTemplates": ["name"],
139 search_key: {"host": [host_name]},
140 "selectInventory": host_inventory,
141 "selectHostGroups": "extend",
142 "selectTags": "extend",
143 "selectMacros": "extend"
144 }
145 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
146 parameters["selectGroups"] = parameters["selectHostGroups"]
147 del parameters["selectHostGroups"]
148 host_list = self._zapi.host.get(parameters)
149 if len(host_list) < 1:
150 self._module.fail_json(msg="Host not found: %s" % host_name)
151 else:
152 return host_list
153
154 def get_hosts_by_ip(self, host_ips, host_inventory):
155 """ Get host by host ip(s) """
156 hostinterfaces = self._zapi.hostinterface.get({
157 "output": "extend",
158 "filter": {
159 "ip": host_ips
160 }
161 })
162 if len(hostinterfaces) < 1:
163 self._module.fail_json(msg="Host not found: %s" % host_ips)
164 host_list = []
165 for hostinterface in hostinterfaces:
166 host_get_params = {
167 "output": "extend",
168 "selectHostGroups": "extend",
169 "selectParentTemplates": ["name"],
170 "hostids": hostinterface["hostid"],
171 "selectInventory": host_inventory,
172 "selectTags": "extend",
173 "selectMacros": "extend"
174 }
175 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
176 host_get_params["selectGroups"] = host_get_params["selectHostGroups"]
177 del host_get_params["selectHostGroups"]
178 host = self._zapi.host.get(host_get_params)
179 host[0]["hostinterfaces"] = hostinterface
180 host_list.append(host[0])
181 return host_list
182
183 def delete_duplicate_hosts(self, hosts):
184 """ Delete duplicated hosts """
185 unique_hosts = []
186 listed_hostnames = []
187 for zabbix_host in hosts:
188 if zabbix_host["name"] in listed_hostnames:
189 continue
190 unique_hosts.append(zabbix_host)
191 listed_hostnames.append(zabbix_host["name"])
192 return unique_hosts
193
194
195 def main():
196 argument_spec = zabbix_utils.zabbix_common_argument_spec()
197 argument_spec.update(dict(
198 host_name=dict(type="str", default="", required=False),
199 host_ip=dict(type="list", default=[], required=False, elements="str"),
200 exact_match=dict(type="bool", required=False, default=False),
201 remove_duplicate=dict(type="bool", required=False, default=True),
202 host_inventory=dict(type="list", default=[], required=False, elements="str")
203 ))
204 module = AnsibleModule(
205 argument_spec=argument_spec,
206 supports_check_mode=True
207 )
208
209 host_name = module.params["host_name"]
210 host_ips = module.params["host_ip"]
211 exact_match = module.params["exact_match"]
212 is_remove_duplicate = module.params["remove_duplicate"]
213 host_inventory = module.params["host_inventory"]
214
215 if not host_inventory:
216 host_inventory = "extend"
217
218 host = Host(module)
219
220 if host_name != "" or (host_name == "" and len(host_ips) == 0):
221 hosts = host.get_hosts_by_host_name(host_name, exact_match, host_inventory)
222 if is_remove_duplicate:
223 hosts = host.delete_duplicate_hosts(hosts)
224 extended_hosts = []
225 for zabbix_host in hosts:
226 zabbix_host["hostinterfaces"] = host._zapi.hostinterface.get({
227 "output": "extend", "hostids": zabbix_host["hostid"]
228 })
229 extended_hosts.append(zabbix_host)
230 module.exit_json(ok=True, hosts=extended_hosts)
231
232 elif host_ips:
233 extended_hosts = host.get_hosts_by_ip(host_ips, host_inventory)
234 if is_remove_duplicate:
235 hosts = host.delete_duplicate_hosts(extended_hosts)
236 module.exit_json(ok=True, hosts=extended_hosts)
237 else:
238 module.exit_json(ok=False, hosts=[], result="No Host present")
239
240
241 if __name__ == "__main__":
242 main()