Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Loic Blot <[email protected]>
4 # Sponsored by Infopro Digital. http://www.infopro-digital.com/
5 # Sponsored by E.T.A.I. http://www.etai.fr/
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: omapi_host
13 short_description: Setup OMAPI hosts
14 description: Manage OMAPI hosts into compatible DHCPd servers.
15 requirements:
16 - pypureomapi
17 author:
18 - Loic Blot (@nerzhul)
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: none
24 diff_mode:
25 support: none
26 options:
27 state:
28 description:
29 - Create or remove OMAPI host.
30 type: str
31 required: true
32 choices: [absent, present]
33 hostname:
34 description:
35 - Sets the host lease hostname (mandatory if O(state=present)).
36 type: str
37 aliases: [name]
38 host:
39 description:
40 - Sets OMAPI server host to interact with.
41 type: str
42 default: localhost
43 port:
44 description:
45 - Sets the OMAPI server port to interact with.
46 type: int
47 default: 7911
48 key_name:
49 description:
50 - Sets the TSIG key name for authenticating against OMAPI server.
51 type: str
52 required: true
53 key:
54 description:
55 - Sets the TSIG key content for authenticating against OMAPI server.
56 type: str
57 required: true
58 macaddr:
59 description:
60 - Sets the lease host MAC address.
61 type: str
62 required: true
63 ip:
64 description:
65 - Sets the lease host IP address.
66 type: str
67 statements:
68 description:
69 - Attach a list of OMAPI DHCP statements with host lease (without ending semicolon).
70 type: list
71 elements: str
72 default: []
73 ddns:
74 description:
75 - Enable dynamic DNS updates for this host.
76 type: bool
77 default: false
78 """
79 EXAMPLES = r"""
80 - name: Add a host using OMAPI
81 community.general.omapi_host:
82 key_name: defomapi
83 key: +bFQtBCta6j2vWkjPkNFtgA==
84 host: 10.98.4.55
85 macaddr: 44:dd:ab:dd:11:44
86 name: server01
87 ip: 192.168.88.99
88 ddns: true
89 statements:
90 - filename "pxelinux.0"
91 - next-server 1.1.1.1
92 state: present
93
94 - name: Remove a host using OMAPI
95 community.general.omapi_host:
96 key_name: defomapi
97 key: +bFQtBCta6j2vWkjPkNFtgA==
98 host: 10.1.1.1
99 macaddr: 00:66:ab:dd:11:44
100 state: absent
101 """
102
103 RETURN = r"""
104 lease:
105 description: Dictionary containing host information.
106 returned: success
107 type: dict
108 contains:
109 ip-address:
110 description: IP address, if there is.
111 returned: success
112 type: str
113 sample: '192.168.1.5'
114 hardware-address:
115 description: MAC address.
116 returned: success
117 type: str
118 sample: '00:11:22:33:44:55'
119 hardware-type:
120 description: Hardware type, generally V(1).
121 returned: success
122 type: int
123 sample: 1
124 name:
125 description: Hostname.
126 returned: success
127 type: str
128 sample: 'mydesktop'
129 """
130
131 import binascii
132 import struct
133 import traceback
134
135 PUREOMAPI_IMP_ERR = None
136 try:
137 from pypureomapi import (
138 OMAPI_OP_STATUS,
139 OMAPI_OP_UPDATE,
140 Omapi,
141 OmapiError,
142 OmapiErrorNotFound,
143 OmapiMessage,
144 pack_ip,
145 pack_mac,
146 unpack_ip,
147 unpack_mac,
148 )
149
150 pureomapi_found = True
151 except ImportError:
152 PUREOMAPI_IMP_ERR = traceback.format_exc()
153 pureomapi_found = False
154
155 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
156 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
157
158
159 class OmapiHostManager:
160 def __init__(self, module):
161 self.module = module
162 self.omapi = None
163 self.connect()
164
165 def connect(self):
166 try:
167 self.omapi = Omapi(
168 self.module.params["host"],
169 self.module.params["port"],
170 to_bytes(self.module.params["key_name"]),
171 self.module.params["key"],
172 )
173 except binascii.Error:
174 self.module.fail_json(msg="Unable to open OMAPI connection. 'key' is not a valid base64 key.")
175 except OmapiError as e:
176 self.module.fail_json(
177 msg=f"Unable to open OMAPI connection. Ensure 'host', 'port', 'key' and 'key_name' are valid. Exception was: {e}"
178 )
179 except OSError as e:
180 self.module.fail_json(msg=f"Unable to connect to OMAPI server: {e}")
181
182 def get_host(self, macaddr):
183 msg = OmapiMessage.open(to_bytes("host", errors="surrogate_or_strict"))
184 msg.obj.append((to_bytes("hardware-address", errors="surrogate_or_strict"), pack_mac(macaddr)))
185 msg.obj.append((to_bytes("hardware-type", errors="surrogate_or_strict"), struct.pack("!I", 1)))
186 response = self.omapi.query_server(msg)
187 if response.opcode != OMAPI_OP_UPDATE:
188 return None
189 return response
190
191 @staticmethod
192 def unpack_facts(obj):
193 result = {}
194 for k, v in dict(obj).items():
195 result[to_text(k)] = v
196
197 if "hardware-address" in result:
198 result["hardware-address"] = to_native(unpack_mac(result["hardware-address"]))
199
200 if "ip-address" in result:
201 result["ip-address"] = to_native(unpack_ip(result["ip-address"]))
202
203 if "hardware-type" in result:
204 result["hardware-type"] = struct.unpack("!I", result["hardware-type"])
205
206 return result
207
208 def setup_host(self):
209 if self.module.params["hostname"] is None or len(self.module.params["hostname"]) == 0:
210 self.module.fail_json(msg="name attribute could not be empty when adding or modifying host.")
211
212 msg = None
213 host_response = self.get_host(self.module.params["macaddr"])
214 # If host was not found using macaddr, add create message
215 if host_response is None:
216 msg = OmapiMessage.open(to_bytes("host", errors="surrogate_or_strict"))
217 msg.message.append((to_bytes("create"), struct.pack("!I", 1)))
218 msg.message.append((to_bytes("exclusive"), struct.pack("!I", 1)))
219 msg.obj.append((to_bytes("hardware-address"), pack_mac(self.module.params["macaddr"])))
220 msg.obj.append((to_bytes("hardware-type"), struct.pack("!I", 1)))
221 msg.obj.append((to_bytes("name"), to_bytes(self.module.params["hostname"])))
222 if self.module.params["ip"] is not None:
223 msg.obj.append(
224 (to_bytes("ip-address", errors="surrogate_or_strict"), pack_ip(self.module.params["ip"]))
225 )
226
227 stmt_join = ""
228 if self.module.params["ddns"]:
229 stmt_join += f'ddns-hostname "{self.module.params["hostname"]}"; '
230
231 try:
232 if len(self.module.params["statements"]) > 0:
233 stmt_join += "; ".join(self.module.params["statements"])
234 stmt_join += "; "
235 except TypeError as e:
236 self.module.fail_json(msg=f"Invalid statements found: {e}")
237
238 if len(stmt_join) > 0:
239 msg.obj.append((to_bytes("statements"), to_bytes(stmt_join)))
240
241 try:
242 response = self.omapi.query_server(msg)
243 if response.opcode != OMAPI_OP_UPDATE:
244 self.module.fail_json(
245 msg="Failed to add host, ensure authentication and host parameters are valid."
246 )
247 self.module.exit_json(changed=True, lease=self.unpack_facts(response.obj))
248 except OmapiError as e:
249 self.module.fail_json(msg=f"OMAPI error: {e}")
250 # Forge update message
251 else:
252 response_obj = self.unpack_facts(host_response.obj)
253 fields_to_update = {}
254
255 if "ip-address" not in response_obj or response_obj["ip-address"] != self.module.params["ip"]:
256 fields_to_update["ip-address"] = pack_ip(self.module.params["ip"])
257
258 # Name cannot be changed
259 if "name" not in response_obj or response_obj["name"] != self.module.params["hostname"]:
260 self.module.fail_json(
261 msg=(
262 f"Changing hostname is not supported. Old was {response_obj['name']}, "
263 f"new is {self.module.params['hostname']}. Please delete host and add new."
264 )
265 )
266
267 """
268 # It seems statements are not returned by OMAPI, then we cannot modify them at this moment.
269 if 'statements' not in response_obj and len(self.module.params['statements']) > 0 or \
270 response_obj['statements'] != self.module.params['statements']:
271 with open('/tmp/omapi', 'w') as fb:
272 for (k,v) in iteritems(response_obj):
273 fb.writelines('statements: %s %s\n' % (k, v))
274 """
275 if len(fields_to_update) == 0:
276 self.module.exit_json(changed=False, lease=response_obj)
277 else:
278 msg = OmapiMessage.update(host_response.handle)
279 msg.update_object(fields_to_update)
280
281 try:
282 response = self.omapi.query_server(msg)
283 if response.opcode != OMAPI_OP_STATUS:
284 self.module.fail_json(
285 msg="Failed to modify host, ensure authentication and host parameters are valid."
286 )
287 self.module.exit_json(changed=True)
288 except OmapiError as e:
289 self.module.fail_json(msg=f"OMAPI error: {e}")
290
291 def remove_host(self):
292 try:
293 self.omapi.del_host(self.module.params["macaddr"])
294 self.module.exit_json(changed=True)
295 except OmapiErrorNotFound:
296 self.module.exit_json()
297 except OmapiError as e:
298 self.module.fail_json(msg=f"OMAPI error: {e}")
299
300
301 def main():
302 module = AnsibleModule(
303 argument_spec=dict(
304 state=dict(type="str", required=True, choices=["absent", "present"]),
305 host=dict(type="str", default="localhost"),
306 port=dict(type="int", default=7911),
307 key_name=dict(type="str", required=True),
308 key=dict(type="str", required=True, no_log=True),
309 macaddr=dict(type="str", required=True),
310 hostname=dict(type="str", aliases=["name"]),
311 ip=dict(type="str"),
312 ddns=dict(type="bool", default=False),
313 statements=dict(type="list", elements="str", default=[]),
314 ),
315 supports_check_mode=False,
316 )
317
318 if not pureomapi_found:
319 module.fail_json(msg=missing_required_lib("pypureomapi"), exception=PUREOMAPI_IMP_ERR)
320
321 if module.params["key"] is None or len(module.params["key"]) == 0:
322 module.fail_json(msg="'key' parameter cannot be empty.")
323
324 if module.params["key_name"] is None or len(module.params["key_name"]) == 0:
325 module.fail_json(msg="'key_name' parameter cannot be empty.")
326
327 host_manager = OmapiHostManager(module)
328 try:
329 if module.params["state"] == "present":
330 host_manager.setup_host()
331 elif module.params["state"] == "absent":
332 host_manager.remove_host()
333 except ValueError as e:
334 module.fail_json(msg=f"OMAPI input value error: {e}")
335
336
337 if __name__ == "__main__":
338 main()