Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: ipa_host
10 author: Thomas Krahn (@Nosmoht)
11 short_description: Manage FreeIPA host
12 description:
13 - Add, modify and delete an IPA host using IPA API.
14 attributes:
15 check_mode:
16 support: full
17 diff_mode:
18 support: none
19 options:
20 fqdn:
21 description:
22 - Full qualified domain name.
23 - Can not be changed as it is the unique identifier.
24 required: true
25 aliases: ["name"]
26 type: str
27 description:
28 description:
29 - A description of this host.
30 type: str
31 userclass:
32 description:
33 - Host category (semantics placed on this attribute are for local interpretation).
34 type: str
35 version_added: 12.0.0
36 force:
37 description:
38 - Force host name even if not in DNS.
39 type: bool
40 ip_address:
41 description:
42 - Add the host to DNS with this IP address.
43 type: str
44 mac_address:
45 description:
46 - List of Hardware MAC address(es) off this host.
47 - If option is omitted MAC addresses are not checked nor changed.
48 - If an empty list is passed all assigned MAC addresses are removed.
49 - MAC addresses that are already assigned but not passed are removed.
50 aliases: ["macaddress"]
51 type: list
52 elements: str
53 l:
54 description:
55 - Host locality (for example V(Baltimore, MD)).
56 aliases: ["locality"]
57 type: str
58 version_added: 12.0.0
59 ns_host_location:
60 description:
61 - Host location (for example V(Lab 2)).
62 aliases: ["nshostlocation"]
63 type: str
64 ns_hardware_platform:
65 description:
66 - Host hardware platform (for example V(Lenovo T61")).
67 aliases: ["nshardwareplatform"]
68 type: str
69 ns_os_version:
70 description:
71 - Host operating system and version (for example V(Fedora 9)).
72 aliases: ["nsosversion"]
73 type: str
74 user_certificate:
75 description:
76 - List of Base-64 encoded server certificates.
77 - If option is omitted certificates are not checked nor changed.
78 - If an empty list is passed all assigned certificates are removed.
79 - Certificates already assigned but not passed are removed.
80 aliases: ["usercertificate"]
81 type: list
82 elements: str
83 state:
84 description:
85 - State to ensure.
86 default: present
87 choices: ["absent", "disabled", "enabled", "present"]
88 type: str
89 force_creation:
90 description:
91 - Create host if O(state=disabled) or O(state=enabled) but not present.
92 default: true
93 type: bool
94 version_added: 9.5.0
95 update_dns:
96 description:
97 - If set V(true) with O(state=absent), then removes DNS records of the host managed by FreeIPA DNS.
98 - This option has no effect for states other than V(absent).
99 type: bool
100 random_password:
101 description: Generate a random password to be used in bulk enrollment.
102 type: bool
103 extends_documentation_fragment:
104 - community.general._ipa.documentation
105 - community.general._ipa.connection_notes
106 - community.general._attributes
107 """
108
109 EXAMPLES = r"""
110 - name: Ensure host is present
111 community.general.ipa_host:
112 name: host01.example.com
113 description: Example host
114 userclass: Server
115 ip_address: 192.168.0.123
116 locality: Baltimore, MD
117 ns_host_location: Lab
118 ns_os_version: CentOS 7
119 ns_hardware_platform: Lenovo T61
120 mac_address:
121 - "08:00:27:E3:B1:2D"
122 - "52:54:00:BD:97:1E"
123 state: present
124 ipa_host: ipa.example.com
125 ipa_user: admin
126 ipa_pass: topsecret
127
128 - name: Generate a random password for bulk enrolment
129 community.general.ipa_host:
130 name: host01.example.com
131 description: Example host
132 ip_address: 192.168.0.123
133 state: present
134 ipa_host: ipa.example.com
135 ipa_user: admin
136 ipa_pass: topsecret
137 random_password: true
138
139 - name: Ensure host is disabled
140 community.general.ipa_host:
141 name: host01.example.com
142 state: disabled
143 ipa_host: ipa.example.com
144 ipa_user: admin
145 ipa_pass: topsecret
146
147 - name: Ensure that all user certificates are removed
148 community.general.ipa_host:
149 name: host01.example.com
150 user_certificate: []
151 ipa_host: ipa.example.com
152 ipa_user: admin
153 ipa_pass: topsecret
154
155 - name: Ensure host is absent
156 community.general.ipa_host:
157 name: host01.example.com
158 state: absent
159 ipa_host: ipa.example.com
160 ipa_user: admin
161 ipa_pass: topsecret
162
163 - name: Ensure host and its DNS record is absent
164 community.general.ipa_host:
165 name: host01.example.com
166 state: absent
167 ipa_host: ipa.example.com
168 ipa_user: admin
169 ipa_pass: topsecret
170 update_dns: true
171 """
172
173 RETURN = r"""
174 host:
175 description: Host as returned by IPA API.
176 returned: always
177 type: dict
178 host_diff:
179 description: List of options that differ and would be changed.
180 returned: if check mode and a difference is found
181 type: list
182 """
183
184 import traceback
185
186 from ansible.module_utils.basic import AnsibleModule
187
188 from ansible_collections.community.general.plugins.module_utils._ipa import IPAClient, ipa_argument_spec
189
190
191 class HostIPAClient(IPAClient):
192 def __init__(self, module, host, port, protocol):
193 super().__init__(module, host, port, protocol)
194
195 def host_show(self, name):
196 return self._post_json(method="host_show", name=name)
197
198 def host_find(self, name):
199 return self._post_json(method="host_find", name=None, item={"all": True, "fqdn": name})
200
201 def host_add(self, name, host):
202 return self._post_json(method="host_add", name=name, item=host)
203
204 def host_mod(self, name, host):
205 return self._post_json(method="host_mod", name=name, item=host)
206
207 def host_del(self, name, update_dns):
208 return self._post_json(method="host_del", name=name, item={"updatedns": update_dns})
209
210 def host_disable(self, name):
211 return self._post_json(method="host_disable", name=name)
212
213
214 def get_host_dict(
215 description=None,
216 userclass=None,
217 force=None,
218 ip_address=None,
219 l=None,
220 ns_host_location=None,
221 ns_hardware_platform=None,
222 ns_os_version=None,
223 user_certificate=None,
224 mac_address=None,
225 random_password=None,
226 ):
227 data = {}
228 if description is not None:
229 data["description"] = description
230 if userclass is not None:
231 data["userclass"] = userclass
232 if force is not None:
233 data["force"] = force
234 if ip_address is not None:
235 data["ip_address"] = ip_address
236 if l is not None:
237 data["l"] = l
238 if ns_host_location is not None:
239 data["nshostlocation"] = ns_host_location
240 if ns_hardware_platform is not None:
241 data["nshardwareplatform"] = ns_hardware_platform
242 if ns_os_version is not None:
243 data["nsosversion"] = ns_os_version
244 if user_certificate is not None:
245 data["usercertificate"] = [{"__base64__": item} for item in user_certificate]
246 if mac_address is not None:
247 data["macaddress"] = mac_address
248 if random_password is not None:
249 data["random"] = random_password
250 return data
251
252
253 def get_host_diff(client, ipa_host, module_host):
254 non_updateable_keys = ["force", "ip_address"]
255 if not module_host.get("random"):
256 non_updateable_keys.append("random")
257 for key in non_updateable_keys:
258 if key in module_host:
259 del module_host[key]
260
261 return client.get_diff(ipa_data=ipa_host, module_data=module_host)
262
263
264 def ensure(module, client):
265 name = module.params["fqdn"]
266 state = module.params["state"]
267 force_creation = module.params["force_creation"]
268
269 ipa_host = client.host_find(name=name)
270 module_host = get_host_dict(
271 description=module.params["description"],
272 userclass=module.params["userclass"],
273 force=module.params["force"],
274 ip_address=module.params["ip_address"],
275 l=module.params["l"],
276 ns_host_location=module.params["ns_host_location"],
277 ns_hardware_platform=module.params["ns_hardware_platform"],
278 ns_os_version=module.params["ns_os_version"],
279 user_certificate=module.params["user_certificate"],
280 mac_address=module.params["mac_address"],
281 random_password=module.params["random_password"],
282 )
283 changed = False
284 if state in ["present", "enabled", "disabled"]:
285 if not ipa_host and (force_creation or state == "present"):
286 changed = True
287 if not module.check_mode:
288 # OTP password generated by FreeIPA is visible only for host_add command
289 # so, return directly from here.
290 return changed, client.host_add(name=name, host=module_host)
291 else:
292 if not ipa_host and state in ["disabled", "enabled"]:
293 module.fail_json(msg=f"No host with name {name} found")
294
295 diff = get_host_diff(client, ipa_host, module_host)
296 ipa_host_show = client.host_show(name=name)
297 host_needs_to_be_disabled = ipa_host_show.get("has_keytab", True) and (
298 module.params["random_password"] or state == "disabled"
299 )
300 if diff or host_needs_to_be_disabled:
301 changed = True
302 if not module.check_mode:
303 data = {}
304 for key in diff:
305 data[key] = module_host.get(key)
306 if "usercertificate" not in data:
307 data["usercertificate"] = [cert["__base64__"] for cert in ipa_host.get("usercertificate", [])]
308 if host_needs_to_be_disabled:
309 client.host_disable(name=name)
310 if diff:
311 return changed, client.host_mod(name=name, host=data)
312 else:
313 return changed, client.host_find(name=name)
314 elif state == "absent":
315 if ipa_host:
316 changed = True
317 update_dns = module.params.get("update_dns", False)
318 if not module.check_mode:
319 client.host_del(name=name, update_dns=update_dns)
320
321 return changed, client.host_find(name=name)
322
323
324 def main():
325 argument_spec = ipa_argument_spec()
326 argument_spec.update(
327 description=dict(type="str"),
328 fqdn=dict(type="str", required=True, aliases=["name"]),
329 force=dict(type="bool"),
330 ip_address=dict(type="str"),
331 l=dict(type="str", aliases=["locality"]),
332 ns_host_location=dict(type="str", aliases=["nshostlocation"]),
333 ns_hardware_platform=dict(type="str", aliases=["nshardwareplatform"]),
334 ns_os_version=dict(type="str", aliases=["nsosversion"]),
335 userclass=dict(type="str"),
336 user_certificate=dict(type="list", aliases=["usercertificate"], elements="str"),
337 mac_address=dict(type="list", aliases=["macaddress"], elements="str"),
338 update_dns=dict(type="bool"),
339 state=dict(type="str", default="present", choices=["present", "absent", "enabled", "disabled"]),
340 random_password=dict(type="bool", no_log=False),
341 force_creation=dict(type="bool", default=True),
342 )
343
344 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
345
346 client = HostIPAClient(
347 module=module,
348 host=module.params["ipa_host"],
349 port=module.params["ipa_port"],
350 protocol=module.params["ipa_prot"],
351 )
352
353 try:
354 client.login(username=module.params["ipa_user"], password=module.params["ipa_pass"])
355 changed, host = ensure(module, client)
356 module.exit_json(changed=changed, host=host)
357 except Exception as e:
358 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
359
360
361 if __name__ == "__main__":
362 main()