Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Adfinis SyGroup AG
4 # @keachi
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: udm_user
12 author:
13 - keachi (@keachi)
14 short_description: Manage posix users on a univention corporate server
15 description:
16 - This module allows to manage posix users on a univention corporate server (UCS). It uses the Python API of the UCS to
17 create a new object or edit it.
18 notes:
19 - This module uses L(passlib, https://pypi.org/project/passlib/) for password hashing when available,
20 falling back to the Python C(crypt) module or L(legacycrypt, https://pypi.org/project/legacycrypt/).
21 requirements:
22 - passlib (Python library, recommended), or legacycrypt on Python 3.13 or newer
23 - It requires no dependency on Python 3.12 and earlier, but then it relies on the deprecated standard library C(crypt).
24 extends_documentation_fragment:
25 - community.general._attributes
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: partial
31 options:
32 state:
33 default: "present"
34 choices: [present, absent]
35 description:
36 - Whether the user is present or not.
37 type: str
38 username:
39 required: true
40 description:
41 - User name.
42 aliases: ['name']
43 type: str
44 firstname:
45 description:
46 - First name. Required if O(state=present).
47 type: str
48 lastname:
49 description:
50 - Last name. Required if O(state=present).
51 type: str
52 password:
53 description:
54 - Password. Required if O(state=present).
55 type: str
56 birthday:
57 description:
58 - Birthday.
59 type: str
60 city:
61 description:
62 - City of users business address.
63 type: str
64 country:
65 description:
66 - Country of users business address.
67 type: str
68 department_number:
69 description:
70 - Department number of users business address.
71 aliases: [departmentNumber]
72 type: str
73 description:
74 description:
75 - Description (not gecos).
76 type: str
77 display_name:
78 description:
79 - Display name (not gecos).
80 aliases: [displayName]
81 type: str
82 email:
83 default: ['']
84 description:
85 - A list of e-mail addresses.
86 type: list
87 elements: str
88 employee_number:
89 description:
90 - Employee number.
91 aliases: [employeeNumber]
92 type: str
93 employee_type:
94 description:
95 - Employee type.
96 aliases: [employeeType]
97 type: str
98 gecos:
99 description:
100 - GECOS.
101 type: str
102 groups:
103 default: []
104 description:
105 - 'POSIX groups, the LDAP DNs of the groups is found with the LDAP filter for each group as $GROUP: V((&(objectClass=posixGroup\)(cn=$GROUP\)\)).'
106 type: list
107 elements: str
108 home_share:
109 description:
110 - Home NFS share. Must be a LDAP DN, for example V(cn=home,cn=shares,ou=school,dc=example,dc=com).
111 aliases: [homeShare]
112 type: str
113 home_share_path:
114 description:
115 - Path to home NFS share, inside the homeShare.
116 aliases: [homeSharePath]
117 type: str
118 home_telephone_number:
119 default: []
120 description:
121 - List of private telephone numbers.
122 aliases: [homeTelephoneNumber]
123 type: list
124 elements: str
125 homedrive:
126 description:
127 - Windows home drive, for example V("H:").
128 type: str
129 mail_alternative_address:
130 default: []
131 description:
132 - List of alternative e-mail addresses.
133 aliases: [mailAlternativeAddress]
134 type: list
135 elements: str
136 mail_home_server:
137 description:
138 - FQDN of mail server.
139 aliases: [mailHomeServer]
140 type: str
141 mail_primary_address:
142 description:
143 - Primary e-mail address.
144 aliases: [mailPrimaryAddress]
145 type: str
146 mobile_telephone_number:
147 default: []
148 description:
149 - Mobile phone number.
150 aliases: [mobileTelephoneNumber]
151 type: list
152 elements: str
153 organisation:
154 description:
155 - Organisation.
156 aliases: [organization]
157 type: str
158 overridePWHistory:
159 type: bool
160 default: false
161 description:
162 - Override password history.
163 aliases: [override_pw_history]
164 overridePWLength:
165 type: bool
166 default: false
167 description:
168 - Override password check.
169 aliases: [override_pw_length]
170 pager_telephonenumber:
171 default: []
172 description:
173 - List of pager telephone numbers.
174 aliases: [pagerTelephonenumber]
175 type: list
176 elements: str
177 phone:
178 description:
179 - List of telephone numbers.
180 type: list
181 elements: str
182 default: []
183 postcode:
184 description:
185 - Postal code of users business address.
186 type: str
187 primary_group:
188 description:
189 - Primary group. This must be the group LDAP DN.
190 - If not specified, it defaults to V(cn=Domain Users,cn=groups,$LDAP_BASE_DN).
191 aliases: [primaryGroup]
192 type: str
193 profilepath:
194 description:
195 - Windows profile directory.
196 type: str
197 pwd_change_next_login:
198 choices: ['0', '1']
199 description:
200 - Change password on next login.
201 aliases: [pwdChangeNextLogin]
202 type: str
203 room_number:
204 description:
205 - Room number of users business address.
206 aliases: [roomNumber]
207 type: str
208 samba_privileges:
209 description:
210 - Samba privilege, like allow printer administration, do domain join.
211 aliases: [sambaPrivileges]
212 type: list
213 elements: str
214 default: []
215 samba_user_workstations:
216 description:
217 - Allow the authentication only on this Microsoft Windows host.
218 aliases: [sambaUserWorkstations]
219 type: list
220 elements: str
221 default: []
222 sambahome:
223 description:
224 - Windows home path, for example V('\\\\$FQDN\\$USERNAME').
225 type: str
226 scriptpath:
227 description:
228 - Windows logon script.
229 type: str
230 secretary:
231 default: []
232 description:
233 - A list of superiors as LDAP DNs.
234 type: list
235 elements: str
236 serviceprovider:
237 default: ['']
238 description:
239 - Enable user for the following service providers.
240 type: list
241 elements: str
242 shell:
243 default: '/bin/bash'
244 description:
245 - Login shell.
246 type: str
247 street:
248 description:
249 - Street of users business address.
250 type: str
251 title:
252 description:
253 - Title, for example V(Prof.).
254 type: str
255 unixhome:
256 description:
257 - Unix home directory.
258 - If not specified, it defaults to C(/home/$USERNAME).
259 type: str
260 userexpiry:
261 description:
262 - Account expiry date, for example V(1999-12-31).
263 - If not specified, it defaults to the current day plus one year.
264 type: str
265 position:
266 default: ''
267 description:
268 - Define the whole position of users object inside the LDAP tree, for example V(cn=employee,cn=users,ou=school,dc=example,dc=com).
269 type: str
270 update_password:
271 default: always
272 choices: [always, on_create]
273 description:
274 - V(always) updates passwords if they differ.
275 - V(on_create) only sets the password for newly created users.
276 type: str
277 ou:
278 default: ''
279 description:
280 - Organizational Unit inside the LDAP Base DN, for example V(school) for LDAP OU C(ou=school,dc=example,dc=com).
281 type: str
282 subpath:
283 default: 'cn=users'
284 description:
285 - LDAP subpath inside the organizational unit, for example V(cn=teachers,cn=users) for LDAP container C(cn=teachers,cn=users,dc=example,dc=com).
286 type: str
287 """
288
289
290 EXAMPLES = r"""
291 - name: Create a user on a UCS
292 community.general.udm_user:
293 name: FooBar
294 password: secure_password
295 firstname: Foo
296 lastname: Bar
297
298 - name: Create a user with the DN uid=foo,cn=teachers,cn=users,ou=school,dc=school,dc=example,dc=com
299 community.general.udm_user:
300 name: foo
301 password: secure_password
302 firstname: Foo
303 lastname: Bar
304 ou: school
305 subpath: 'cn=teachers,cn=users'
306
307 # or define the position
308 - name: Create a user with the DN uid=foo,cn=teachers,cn=users,ou=school,dc=school,dc=example,dc=com
309 community.general.udm_user:
310 name: foo
311 password: secure_password
312 firstname: Foo
313 lastname: Bar
314 position: 'cn=teachers,cn=users,ou=school,dc=school,dc=example,dc=com'
315 """
316
317
318 RETURN = """#"""
319
320
321 from datetime import date, timedelta
322
323 from ansible.module_utils.basic import AnsibleModule
324
325 from ansible_collections.community.general.plugins.module_utils import _deps as deps
326
327 with deps.declare("crypt_context"):
328 from ansible_collections.community.general.plugins.module_utils._crypt import CryptContext, has_crypt_context
329
330 if not has_crypt_context:
331 raise ImportError("Failed to import any of: passlib, crypt, legacycrypt")
332
333 from ansible_collections.community.general.plugins.module_utils._univention_umc import (
334 base_dn,
335 ldap_search,
336 umc_module_for_add,
337 umc_module_for_edit,
338 )
339
340
341 def main():
342 expiry = date.strftime(date.today() + timedelta(days=365), "%Y-%m-%d")
343 module = AnsibleModule(
344 argument_spec=dict(
345 birthday=dict(type="str"),
346 city=dict(type="str"),
347 country=dict(type="str"),
348 department_number=dict(type="str", aliases=["departmentNumber"]),
349 description=dict(type="str"),
350 display_name=dict(type="str", aliases=["displayName"]),
351 email=dict(default=[""], type="list", elements="str"),
352 employee_number=dict(type="str", aliases=["employeeNumber"]),
353 employee_type=dict(type="str", aliases=["employeeType"]),
354 firstname=dict(type="str"),
355 gecos=dict(type="str"),
356 groups=dict(default=[], type="list", elements="str"),
357 home_share=dict(type="str", aliases=["homeShare"]),
358 home_share_path=dict(type="str", aliases=["homeSharePath"]),
359 home_telephone_number=dict(default=[], type="list", elements="str", aliases=["homeTelephoneNumber"]),
360 homedrive=dict(type="str"),
361 lastname=dict(type="str"),
362 mail_alternative_address=dict(default=[], type="list", elements="str", aliases=["mailAlternativeAddress"]),
363 mail_home_server=dict(type="str", aliases=["mailHomeServer"]),
364 mail_primary_address=dict(type="str", aliases=["mailPrimaryAddress"]),
365 mobile_telephone_number=dict(default=[], type="list", elements="str", aliases=["mobileTelephoneNumber"]),
366 organisation=dict(type="str", aliases=["organization"]),
367 overridePWHistory=dict(default=False, type="bool", aliases=["override_pw_history"]),
368 overridePWLength=dict(default=False, type="bool", aliases=["override_pw_length"]),
369 pager_telephonenumber=dict(default=[], type="list", elements="str", aliases=["pagerTelephonenumber"]),
370 password=dict(type="str", no_log=True),
371 phone=dict(default=[], type="list", elements="str"),
372 postcode=dict(type="str"),
373 primary_group=dict(type="str", aliases=["primaryGroup"]),
374 profilepath=dict(type="str"),
375 pwd_change_next_login=dict(type="str", choices=["0", "1"], aliases=["pwdChangeNextLogin"]),
376 room_number=dict(type="str", aliases=["roomNumber"]),
377 samba_privileges=dict(default=[], type="list", elements="str", aliases=["sambaPrivileges"]),
378 samba_user_workstations=dict(default=[], type="list", elements="str", aliases=["sambaUserWorkstations"]),
379 sambahome=dict(type="str"),
380 scriptpath=dict(type="str"),
381 secretary=dict(default=[], type="list", elements="str"),
382 serviceprovider=dict(default=[""], type="list", elements="str"),
383 shell=dict(default="/bin/bash", type="str"),
384 street=dict(type="str"),
385 title=dict(type="str"),
386 unixhome=dict(type="str"),
387 userexpiry=dict(type="str"),
388 username=dict(required=True, aliases=["name"], type="str"),
389 position=dict(default="", type="str"),
390 update_password=dict(default="always", choices=["always", "on_create"], type="str"),
391 ou=dict(default="", type="str"),
392 subpath=dict(default="cn=users", type="str"),
393 state=dict(default="present", choices=["present", "absent"], type="str"),
394 ),
395 supports_check_mode=True,
396 required_if=([("state", "present", ["firstname", "lastname", "password"])]),
397 )
398
399 deps.validate(module)
400
401 crypt_context = CryptContext(schemes=["sha512_crypt", "sha256_crypt", "md5_crypt", "des_crypt"])
402
403 username = module.params["username"]
404 position = module.params["position"]
405 ou = module.params["ou"]
406 subpath = module.params["subpath"]
407 state = module.params["state"]
408 changed = False
409 diff = None
410
411 users = list(ldap_search(f"(&(objectClass=posixAccount)(uid={username}))", attr=["uid"]))
412 if position != "":
413 container = position
414 else:
415 if ou != "":
416 ou = f"ou={ou},"
417 if subpath != "":
418 subpath = f"{subpath},"
419 container = f"{subpath}{ou}{base_dn()}"
420 user_dn = f"uid={username},{container}"
421
422 exists = bool(len(users))
423
424 if state == "present":
425 try:
426 if not exists:
427 obj = umc_module_for_add("users/user", container)
428 else:
429 obj = umc_module_for_edit("users/user", user_dn)
430
431 if module.params["display_name"] is None:
432 module.params["display_name"] = f"{module.params['firstname']} {module.params['lastname']}"
433 if module.params["unixhome"] is None:
434 module.params["unixhome"] = f"/home/{module.params['username']}"
435 # Build a mapping from alias names to canonical param names,
436 # so that UDM object keys (camelCase) can be resolved to the
437 # corresponding module.params keys (snake_case).
438 alias_to_param = {}
439 for param_name, param_spec in module.argument_spec.items():
440 for alias in param_spec.get("aliases", []):
441 alias_to_param[alias] = param_name
442 for k in obj.keys():
443 param_name = alias_to_param.get(k, k)
444 if (
445 k != "password"
446 and k != "groups"
447 and k != "overridePWHistory"
448 and param_name in module.params
449 and module.params[param_name] is not None
450 ):
451 obj[k] = module.params[param_name]
452 # handle some special values
453 obj["e-mail"] = module.params["email"]
454 if "userexpiry" in obj and obj.get("userexpiry") is None:
455 obj["userexpiry"] = expiry
456 password = module.params["password"]
457 if obj["password"] is None:
458 obj["password"] = password
459 if module.params["update_password"] == "always":
460 old_password = obj["password"].split("}", 2)[1]
461 if not crypt_context.verify(password, old_password):
462 obj["overridePWHistory"] = module.params["overridePWHistory"]
463 obj["overridePWLength"] = module.params["overridePWLength"]
464 obj["password"] = password
465
466 diff = obj.diff()
467 if exists:
468 for k in obj.keys():
469 if obj.hasChanged(k):
470 changed = True
471 else:
472 changed = True
473 if not module.check_mode:
474 if not exists:
475 obj.create()
476 elif changed:
477 obj.modify()
478 except Exception:
479 module.fail_json(msg=f"Creating/editing user {username} in {container} failed")
480 try:
481 groups = module.params["groups"]
482 if groups:
483 filter = f"(&(objectClass=posixGroup)(|(cn={')(cn='.join(groups)})))"
484 group_dns = list(ldap_search(filter, attr=["dn"]))
485 for dn in group_dns:
486 grp = umc_module_for_edit("groups/group", dn[0])
487 if user_dn not in grp["users"]:
488 grp["users"].append(user_dn)
489 if not module.check_mode:
490 grp.modify()
491 changed = True
492 except Exception:
493 module.fail_json(msg=f"Adding groups to user {username} failed")
494
495 if state == "absent" and exists:
496 try:
497 obj = umc_module_for_edit("users/user", user_dn)
498 if not module.check_mode:
499 obj.remove()
500 changed = True
501 except Exception:
502 module.fail_json(msg=f"Removing user {username} failed")
503
504 module.exit_json(changed=changed, username=username, diff=diff, container=container)
505
506
507 if __name__ == "__main__":
508 main()