Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # This module is proudly sponsored by CGI (www.cgi.com) and
4 # KPN (www.kpn.com).
5 # Copyright (c) Ansible project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: icinga2_host
13 short_description: Manage a host in Icinga2
14 description:
15 - Add or remove a host to Icinga2 through the API.
16 - See U(https://www.icinga.com/docs/icinga2/latest/doc/12-icinga2-api/).
17 author: "Jurgen Brand (@t794104)"
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: none
23 options:
24 url:
25 type: str
26 description:
27 - HTTP, HTTPS, or FTP URL in the form V((http|https|ftp\)://[user[:pass]]@host.domain[:port]/path).
28 use_proxy:
29 description:
30 - If V(false), it does not use a proxy, even if one is defined in an environment variable on the target hosts.
31 type: bool
32 default: true
33 validate_certs:
34 description:
35 - If V(false), SSL certificates are not validated. This should only be used on personally controlled sites using self-signed
36 certificates.
37 type: bool
38 default: true
39 url_username:
40 type: str
41 description:
42 - The username for use in HTTP basic authentication.
43 - This parameter can be used without O(url_password) for sites that allow empty passwords.
44 url_password:
45 type: str
46 description:
47 - The password for use in HTTP basic authentication.
48 - If the O(url_username) parameter is not specified, the O(url_password) parameter is not used.
49 force_basic_auth:
50 description:
51 - C(httplib2), the library used by Ansible's HTTP request code only sends authentication information when a webservice
52 responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins
53 may fail. This option forces the sending of the Basic authentication header upon initial request.
54 type: bool
55 default: false
56 client_cert:
57 type: path
58 description:
59 - PEM formatted certificate chain file to be used for SSL client authentication. This file can also include the key
60 as well, and if the key is included, O(client_key) is not required.
61 client_key:
62 type: path
63 description:
64 - PEM formatted file that contains your private key to be used for SSL client authentication. If O(client_cert) contains
65 both the certificate and key, this option is not required.
66 state:
67 type: str
68 description:
69 - Apply feature state.
70 choices: ["present", "absent"]
71 default: present
72 name:
73 type: str
74 description:
75 - Name used to create / delete the host. This does not need to be the FQDN, but does needs to be unique.
76 required: true
77 aliases: [host]
78 zone:
79 type: str
80 description:
81 - The zone from where this host should be polled.
82 template:
83 type: str
84 description:
85 - The template used to define the host.
86 - Template cannot be modified after object creation.
87 check_command:
88 type: str
89 description:
90 - The command used to check if the host is alive.
91 default: "hostalive"
92 display_name:
93 type: str
94 description:
95 - The name used to display the host.
96 - If not specified, it defaults to the value of the O(name) parameter.
97 ip:
98 type: str
99 description:
100 - The IP address of the host.
101 - This is no longer required since community.general 8.0.0.
102 variables:
103 type: dict
104 description:
105 - Dictionary of variables.
106 extends_documentation_fragment:
107 - ansible.builtin.url
108 - community.general._attributes
109 """
110
111 EXAMPLES = r"""
112 - name: Add host to icinga
113 community.general.icinga2_host:
114 url: "https://icinga2.example.com"
115 url_username: "ansible"
116 url_password: "a_secret"
117 state: present
118 name: "{{ ansible_fqdn }}"
119 ip: "{{ ansible_default_ipv4.address }}"
120 variables:
121 foo: "bar"
122 delegate_to: 127.0.0.1
123 """
124
125 RETURN = r"""
126 name:
127 description: The name used to create, modify or delete the host.
128 type: str
129 returned: always
130 data:
131 description: The data structure used for create, modify or delete of the host.
132 type: dict
133 returned: always
134 """
135
136 import json
137
138 from ansible.module_utils.basic import AnsibleModule
139 from ansible.module_utils.urls import fetch_url, url_argument_spec
140
141
142 # ===========================================
143 # Icinga2 API class
144 #
145 class icinga2_api:
146 module = None
147
148 def __init__(self, module):
149 self.module = module
150
151 def call_url(self, path, data="", method="GET"):
152 headers = {
153 "Accept": "application/json",
154 "X-HTTP-Method-Override": method,
155 }
156 url = f"{self.module.params.get('url')}/{path}"
157 rsp, info = fetch_url(
158 module=self.module,
159 url=url,
160 data=data,
161 headers=headers,
162 method=method,
163 use_proxy=self.module.params["use_proxy"],
164 )
165 body = ""
166 if rsp:
167 body = json.loads(rsp.read())
168 if info["status"] >= 400:
169 body = info["body"]
170 return {"code": info["status"], "data": body}
171
172 def check_connection(self):
173 ret = self.call_url("v1/status")
174 return ret["code"] == 200
175
176 def exists(self, hostname):
177 data = {
178 "filter": f'match("{hostname}", host.name)',
179 }
180 ret = self.call_url(path="v1/objects/hosts", data=self.module.jsonify(data))
181 if ret["code"] == 200:
182 if len(ret["data"]["results"]) == 1:
183 return True
184 return False
185
186 def create(self, hostname, data):
187 ret = self.call_url(path=f"v1/objects/hosts/{hostname}", data=self.module.jsonify(data), method="PUT")
188 return ret
189
190 def delete(self, hostname):
191 data = {"cascade": 1}
192 ret = self.call_url(path=f"v1/objects/hosts/{hostname}", data=self.module.jsonify(data), method="DELETE")
193 return ret
194
195 def modify(self, hostname, data):
196 ret = self.call_url(path=f"v1/objects/hosts/{hostname}", data=self.module.jsonify(data), method="POST")
197 return ret
198
199 def diff(self, hostname, data):
200 ret = self.call_url(path=f"v1/objects/hosts/{hostname}", method="GET")
201 changed = False
202 ic_data = ret["data"]["results"][0]
203 for key in data["attrs"]:
204 if key not in ic_data["attrs"].keys():
205 changed = True
206 elif data["attrs"][key] != ic_data["attrs"][key]:
207 changed = True
208 return changed
209
210
211 # ===========================================
212 # Module execution.
213 #
214 def main():
215 # use the predefined argument spec for url
216 argument_spec = url_argument_spec()
217 # add our own arguments
218 argument_spec.update(
219 state=dict(default="present", choices=["absent", "present"]),
220 name=dict(required=True, aliases=["host"]),
221 zone=dict(),
222 template=dict(),
223 check_command=dict(default="hostalive"),
224 display_name=dict(),
225 ip=dict(),
226 variables=dict(type="dict"),
227 )
228
229 # Define the main module
230 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
231
232 state = module.params["state"]
233 name = module.params["name"]
234 zone = module.params["zone"]
235 template = []
236 if module.params["template"]:
237 template = [module.params["template"]]
238 check_command = module.params["check_command"]
239 ip = module.params["ip"]
240 display_name = module.params["display_name"]
241 if not display_name:
242 display_name = name
243 variables = module.params["variables"]
244
245 try:
246 icinga = icinga2_api(module=module)
247 icinga.check_connection()
248 except Exception as e:
249 module.fail_json(msg=f"unable to connect to Icinga. Exception message: {e}")
250
251 data = {
252 "templates": template,
253 "attrs": {
254 "address": ip,
255 "display_name": display_name,
256 "check_command": check_command,
257 "zone": zone,
258 "vars.made_by": "ansible",
259 },
260 }
261 data["attrs"].update({f"vars.{key}": value for key, value in variables.items()})
262
263 changed = False
264 if icinga.exists(name):
265 if state == "absent":
266 if module.check_mode:
267 module.exit_json(changed=True, name=name, data=data)
268 else:
269 try:
270 ret = icinga.delete(name)
271 if ret["code"] == 200:
272 changed = True
273 else:
274 module.fail_json(msg=f"bad return code ({ret['code']}) deleting host: '{ret['data']}'")
275 except Exception as e:
276 module.fail_json(msg=f"exception deleting host: {e}")
277
278 elif icinga.diff(name, data):
279 if module.check_mode:
280 module.exit_json(changed=False, name=name, data=data)
281
282 # Template attribute is not allowed in modification
283 del data["templates"]
284
285 ret = icinga.modify(name, data)
286
287 if ret["code"] == 200:
288 changed = True
289 else:
290 module.fail_json(msg=f"bad return code ({ret['code']}) modifying host: '{ret['data']}'")
291
292 else:
293 if state == "present":
294 if module.check_mode:
295 changed = True
296 else:
297 try:
298 ret = icinga.create(name, data)
299 if ret["code"] == 200:
300 changed = True
301 else:
302 module.fail_json(msg=f"bad return code ({ret['code']}) creating host: '{ret['data']}'")
303 except Exception as e:
304 module.fail_json(msg=f"exception creating host: {e}")
305
306 module.exit_json(changed=changed, name=name, data=data)
307
308
309 # import module snippets
310 if __name__ == "__main__":
311 main()