Debian Codegraph @

lib/ansible/modules/group.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Stephen Fromm <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = """
10 ---
11 module: group
12 version_added: "0.0.2"
13 short_description: Add or remove groups
14 requirements:
15 - groupadd
16 - groupdel
17 - groupmod
18 description:
19 - Manage presence of groups on a host.
20 - For Windows targets, use the M(ansible.windows.win_group) module instead.
21 options:
22 name:
23 description:
24 - Name of the group to manage.
25 type: str
26 required: true
27 gid:
28 description:
29 - Optional I(GID) to set for the group.
30 type: int
31 state:
32 description:
33 - Whether the group should be present or not on the remote host.
34 type: str
35 choices: [ absent, present ]
36 default: present
37 force:
38 description:
39 - Whether to delete a group even if it is the primary group of a user.
40 - Only applicable on platforms which implement a C(--force) flag on the group deletion command.
41 - Not applicable on macOS, *BSD and BusyBox based distros.
42 type: bool
43 default: false
44 version_added: "2.15"
45 system:
46 description:
47 - If V(yes), indicates that the group created is a system group.
48 type: bool
49 default: no
50 local:
51 description:
52 - Forces the use of "local" command alternatives on platforms that implement it.
53 - This is useful in environments that use centralized authentication when you want to manipulate the local groups.
54 (for example, it uses C(lgroupadd) instead of C(groupadd)).
55 - This requires that these commands exist on the targeted host, otherwise it will be a fatal error.
56 type: bool
57 default: no
58 version_added: "2.6"
59 non_unique:
60 description:
61 - This option allows to change the group ID to a non-unique value. Requires O(gid).
62 - Not supported on macOS or BusyBox distributions.
63 type: bool
64 default: no
65 version_added: "2.8"
66 gid_min:
67 description:
68 - Sets the GID_MIN value for group creation.
69 - Overwrites /etc/login.defs default value.
70 - Currently supported on Linux. Does nothing when used with other platforms.
71 - Requires O(local) is omitted or V(False).
72 type: int
73 version_added: "2.18"
74 gid_max:
75 description:
76 - Sets the GID_MAX value for group creation.
77 - Overwrites /etc/login.defs default value.
78 - Currently supported on Linux. Does nothing when used with other platforms.
79 - Requires O(local) is omitted or V(False).
80 type: int
81 version_added: "2.18"
82 extends_documentation_fragment: action_common_attributes
83 attributes:
84 check_mode:
85 support: full
86 diff_mode:
87 support: none
88 platform:
89 platforms: posix
90 seealso:
91 - module: ansible.builtin.user
92 - module: ansible.windows.win_group
93 author:
94 - Stephen Fromm (@sfromm)
95 """
96
97 EXAMPLES = """
98 - name: Ensure group "somegroup" exists
99 ansible.builtin.group:
100 name: somegroup
101 state: present
102
103 - name: Ensure group "docker" exists with correct gid
104 ansible.builtin.group:
105 name: docker
106 state: present
107 gid: 1750
108 """
109
110 RETURN = r"""
111 gid:
112 description: Group ID of the group.
113 returned: When O(state) is C(present)
114 type: int
115 sample: 1001
116 name:
117 description: Group name.
118 returned: always
119 type: str
120 sample: users
121 state:
122 description: Whether the group is present or not.
123 returned: always
124 type: str
125 sample: 'absent'
126 system:
127 description: Whether the group is a system group or not.
128 returned: When O(state) is C(present)
129 type: bool
130 sample: False
131 """
132
133 import grp
134 import os
135
136 from ansible.module_utils.common.text.converters import to_bytes
137 from ansible.module_utils.basic import AnsibleModule
138 from ansible.module_utils.common.sys_info import get_platform_subclass
139
140
141 class Group(object):
142 """
143 This is a generic Group manipulation class that is subclassed
144 based on platform.
145
146 A subclass may wish to override the following action methods:-
147 - group_del()
148 - group_add()
149 - group_mod()
150
151 All subclasses MUST define platform and distribution (which may be None).
152 """
153
154 platform = 'Generic'
155 distribution = None # type: str | None
156 GROUPFILE = '/etc/group'
157
158 def __new__(cls, *args, **kwargs):
159 new_cls = get_platform_subclass(Group)
160 return super(cls, new_cls).__new__(new_cls)
161
162 def __init__(self, module):
163 self.module = module
164 self.state = module.params['state']
165 self.name = module.params['name']
166 self.force = module.params['force']
167 self.gid = module.params['gid']
168 self.system = module.params['system']
169 self.local = module.params['local']
170 self.non_unique = module.params['non_unique']
171 self.gid_min = module.params['gid_min']
172 self.gid_max = module.params['gid_max']
173
174 if self.local:
175 if self.gid_min is not None:
176 module.fail_json(msg="'gid_min' can not be used with 'local'")
177 if self.gid_max is not None:
178 module.fail_json(msg="'gid_max' can not be used with 'local'")
179
180 def execute_command(self, cmd):
181 return self.module.run_command(cmd)
182
183 def group_del(self):
184 if self.local:
185 command_name = 'lgroupdel'
186 else:
187 command_name = 'groupdel'
188 cmd = [self.module.get_bin_path(command_name, True), self.name]
189 return self.execute_command(cmd)
190
191 def _local_check_gid_exists(self):
192 if self.gid:
193 for gr in grp.getgrall():
194 if self.gid == gr.gr_gid and self.name != gr.gr_name:
195 self.module.fail_json(msg="GID '{0}' already exists with group '{1}'".format(self.gid, gr.gr_name))
196
197 def group_add(self, **kwargs):
198 if self.local:
199 command_name = 'lgroupadd'
200 self._local_check_gid_exists()
201 else:
202 command_name = 'groupadd'
203 cmd = [self.module.get_bin_path(command_name, True)]
204 for key in kwargs:
205 if key == 'gid' and kwargs[key] is not None:
206 cmd.append('-g')
207 cmd.append(str(kwargs[key]))
208 if self.non_unique:
209 cmd.append('-o')
210 elif key == 'system' and kwargs[key] is True:
211 cmd.append('-r')
212 if self.gid_min is not None:
213 cmd.append('-K')
214 cmd.append('GID_MIN=' + str(self.gid_min))
215 if self.gid_max is not None:
216 cmd.append('-K')
217 cmd.append('GID_MAX=' + str(self.gid_max))
218 cmd.append(self.name)
219 return self.execute_command(cmd)
220
221 def group_mod(self, **kwargs):
222 if self.local:
223 command_name = 'lgroupmod'
224 self._local_check_gid_exists()
225 else:
226 command_name = 'groupmod'
227 cmd = [self.module.get_bin_path(command_name, True)]
228 info = self.group_info()
229 for key in kwargs:
230 if key == 'gid':
231 if kwargs[key] is not None and info[2] != int(kwargs[key]):
232 cmd.append('-g')
233 cmd.append(str(kwargs[key]))
234 if self.non_unique:
235 cmd.append('-o')
236 if len(cmd) == 1:
237 return (None, '', '')
238 if self.module.check_mode:
239 return (0, '', '')
240 cmd.append(self.name)
241 return self.execute_command(cmd)
242
243 def group_exists(self):
244 # The grp module does not distinguish between local and directory accounts.
245 # It's output cannot be used to determine whether or not a group exists locally.
246 # It returns True if the group exists locally or in the directory, so instead
247 # look in the local GROUP file for an existing account.
248 if self.local:
249 if not os.path.exists(self.GROUPFILE):
250 self.module.fail_json(msg="'local: true' specified but unable to find local group file {0} to parse.".format(self.GROUPFILE))
251
252 exists = False
253 name_test = '{0}:'.format(self.name)
254 with open(self.GROUPFILE, 'rb') as f:
255 reversed_lines = f.readlines()[::-1]
256 for line in reversed_lines:
257 if line.startswith(to_bytes(name_test)):
258 exists = True
259 break
260 return exists
261 else:
262 try:
263 if grp.getgrnam(self.name):
264 return True
265 except KeyError:
266 return False
267
268 def group_info(self):
269 if not self.group_exists():
270 return False
271 try:
272 info = list(grp.getgrnam(self.name))
273 except KeyError:
274 return False
275 return info
276
277
278 # ===========================================
279
280 class Linux(Group):
281 """
282 This is a Linux Group manipulation class. This is to apply the '-f' parameter to the groupdel command
283
284 This overrides the following methods from the generic class:-
285 - group_del()
286 """
287
288 platform = 'Linux'
289 distribution = None
290
291 def group_del(self):
292 if self.local:
293 command_name = 'lgroupdel'
294 else:
295 command_name = 'groupdel'
296 cmd = [self.module.get_bin_path(command_name, True)]
297 if self.force:
298 cmd.append('-f')
299 cmd.append(self.name)
300 return self.execute_command(cmd)
301
302
303 # ===========================================
304
305 class SunOS(Group):
306 """
307 This is a SunOS Group manipulation class. Solaris doesn't have
308 the 'system' group concept.
309
310 This overrides the following methods from the generic class:-
311 - group_add()
312 """
313
314 platform = 'SunOS'
315 distribution = None
316 GROUPFILE = '/etc/group'
317
318 def group_add(self, **kwargs):
319 cmd = [self.module.get_bin_path('groupadd', True)]
320 for key in kwargs:
321 if key == 'gid' and kwargs[key] is not None:
322 cmd.append('-g')
323 cmd.append(str(kwargs[key]))
324 if self.non_unique:
325 cmd.append('-o')
326 if self.gid_min is not None:
327 cmd.append('-K')
328 cmd.append('GID_MIN=' + str(self.gid_min))
329 if self.gid_max is not None:
330 cmd.append('-K')
331 cmd.append('GID_MAX=' + str(self.gid_max))
332 cmd.append(self.name)
333 return self.execute_command(cmd)
334
335
336 # ===========================================
337
338 class AIX(Group):
339 """
340 This is a AIX Group manipulation class.
341
342 This overrides the following methods from the generic class:-
343 - group_del()
344 - group_add()
345 - group_mod()
346 """
347
348 platform = 'AIX'
349 distribution = None
350 GROUPFILE = '/etc/group'
351
352 def group_del(self):
353 cmd = [self.module.get_bin_path('rmgroup', True), self.name]
354 return self.execute_command(cmd)
355
356 def group_add(self, **kwargs):
357 cmd = [self.module.get_bin_path('mkgroup', True)]
358 for key in kwargs:
359 if key == 'gid' and kwargs[key] is not None:
360 cmd.append('id=' + str(kwargs[key]))
361 elif key == 'system' and kwargs[key] is True:
362 cmd.append('-a')
363 if self.gid_min is not None:
364 cmd.append('-K')
365 cmd.append('GID_MIN=' + str(self.gid_min))
366 if self.gid_max is not None:
367 cmd.append('-K')
368 cmd.append('GID_MAX=' + str(self.gid_max))
369 cmd.append(self.name)
370 return self.execute_command(cmd)
371
372 def group_mod(self, **kwargs):
373 cmd = [self.module.get_bin_path('chgroup', True)]
374 info = self.group_info()
375 for key in kwargs:
376 if key == 'gid':
377 if kwargs[key] is not None and info[2] != int(kwargs[key]):
378 cmd.append('id=' + str(kwargs[key]))
379 if len(cmd) == 1:
380 return (None, '', '')
381 if self.module.check_mode:
382 return (0, '', '')
383 cmd.append(self.name)
384 return self.execute_command(cmd)
385
386
387 # ===========================================
388
389 class FreeBsdGroup(Group):
390 """
391 This is a FreeBSD Group manipulation class.
392
393 This overrides the following methods from the generic class:-
394 - group_del()
395 - group_add()
396 - group_mod()
397 """
398
399 platform = 'FreeBSD'
400 distribution = None
401 GROUPFILE = '/etc/group'
402
403 def group_del(self):
404 if self.module.params['force']:
405 self.module.fail_json(msg='The force option is not supported for group deletion on this platform.')
406 cmd = [self.module.get_bin_path('pw', True), 'groupdel', self.name]
407 return self.execute_command(cmd)
408
409 def group_add(self, **kwargs):
410 cmd = [self.module.get_bin_path('pw', True), 'groupadd', self.name]
411 if self.gid is not None:
412 cmd.append('-g')
413 cmd.append(str(self.gid))
414 if self.non_unique:
415 cmd.append('-o')
416 if self.gid_min is not None:
417 cmd.append('-K')
418 cmd.append('GID_MIN=' + str(self.gid_min))
419 if self.gid_max is not None:
420 cmd.append('-K')
421 cmd.append('GID_MAX=' + str(self.gid_max))
422 return self.execute_command(cmd)
423
424 def group_mod(self, **kwargs):
425 cmd = [self.module.get_bin_path('pw', True), 'groupmod', self.name]
426 info = self.group_info()
427 cmd_len = len(cmd)
428 if self.gid is not None and int(self.gid) != info[2]:
429 cmd.append('-g')
430 cmd.append(str(self.gid))
431 if self.non_unique:
432 cmd.append('-o')
433 # modify the group if cmd will do anything
434 if cmd_len != len(cmd):
435 if self.module.check_mode:
436 return (0, '', '')
437 return self.execute_command(cmd)
438 return (None, '', '')
439
440
441 class DragonFlyBsdGroup(FreeBsdGroup):
442 """
443 This is a DragonFlyBSD Group manipulation class.
444 It inherits all behaviors from FreeBsdGroup class.
445 """
446
447 platform = 'DragonFly'
448
449
450 # ===========================================
451
452 class DarwinGroup(Group):
453 """
454 This is a Mac macOS Darwin Group manipulation class.
455
456 This overrides the following methods from the generic class:-
457 - group_del()
458 - group_add()
459 - group_mod()
460
461 group manipulation are done using dseditgroup(1).
462 """
463
464 platform = 'Darwin'
465 distribution = None
466
467 def group_add(self, **kwargs):
468 cmd = [self.module.get_bin_path('dseditgroup', True)]
469 cmd += ['-o', 'create']
470 if self.gid is not None:
471 cmd += ['-i', str(self.gid)]
472 elif 'system' in kwargs and kwargs['system'] is True:
473 gid = self.get_lowest_available_system_gid()
474 if gid is not False:
475 self.gid = str(gid)
476 cmd += ['-i', str(self.gid)]
477 cmd += ['-L', self.name]
478 (rc, out, err) = self.execute_command(cmd)
479 return (rc, out, err)
480
481 def group_del(self):
482 if self.module.params['force']:
483 self.module.fail_json(msg='The force option is not supported for group deletion on this platform.')
484 cmd = [self.module.get_bin_path('dseditgroup', True)]
485 cmd += ['-o', 'delete']
486 cmd += ['-L', self.name]
487 (rc, out, err) = self.execute_command(cmd)
488 return (rc, out, err)
489
490 def group_mod(self, gid=None):
491 info = self.group_info()
492 if self.gid is not None and int(self.gid) != info[2]:
493 cmd = [self.module.get_bin_path('dseditgroup', True)]
494 cmd += ['-o', 'edit']
495 if gid is not None:
496 cmd += ['-i', str(gid)]
497 cmd += ['-L', self.name]
498 (rc, out, err) = self.execute_command(cmd)
499 return (rc, out, err)
500 return (None, '', '')
501
502 def get_lowest_available_system_gid(self):
503 # check for lowest available system gid (< 500)
504 try:
505 cmd = [self.module.get_bin_path('dscl', True)]
506 cmd += ['/Local/Default', '-list', '/Groups', 'PrimaryGroupID']
507 (rc, out, err) = self.execute_command(cmd)
508 lines = out.splitlines()
509 highest = 0
510 for group_info in lines:
511 parts = group_info.split(' ')
512 if len(parts) > 1:
513 gid = int(parts[-1])
514 if gid > highest and gid < 500:
515 highest = gid
516 if highest == 0 or highest == 499:
517 return False
518 return (highest + 1)
519 except Exception:
520 return False
521
522
523 class OpenBsdGroup(Group):
524 """
525 This is a OpenBSD Group manipulation class.
526
527 This overrides the following methods from the generic class:-
528 - group_del()
529 - group_add()
530 - group_mod()
531 """
532
533 platform = 'OpenBSD'
534 distribution = None
535 GROUPFILE = '/etc/group'
536
537 def group_del(self):
538 if self.module.params['force']:
539 self.module.fail_json(msg='The force option is not supported for group deletion on this platform.')
540 cmd = [self.module.get_bin_path('groupdel', True), self.name]
541 return self.execute_command(cmd)
542
543 def group_add(self, **kwargs):
544 cmd = [self.module.get_bin_path('groupadd', True)]
545 if self.gid is not None:
546 cmd.append('-g')
547 cmd.append(str(self.gid))
548 if self.non_unique:
549 cmd.append('-o')
550 if self.gid_min is not None:
551 cmd.append('-K')
552 cmd.append('GID_MIN=' + str(self.gid_min))
553 if self.gid_max is not None:
554 cmd.append('-K')
555 cmd.append('GID_MAX=' + str(self.gid_max))
556 cmd.append(self.name)
557 return self.execute_command(cmd)
558
559 def group_mod(self, **kwargs):
560 cmd = [self.module.get_bin_path('groupmod', True)]
561 info = self.group_info()
562 if self.gid is not None and int(self.gid) != info[2]:
563 cmd.append('-g')
564 cmd.append(str(self.gid))
565 if self.non_unique:
566 cmd.append('-o')
567 if len(cmd) == 1:
568 return (None, '', '')
569 if self.module.check_mode:
570 return (0, '', '')
571 cmd.append(self.name)
572 return self.execute_command(cmd)
573
574
575 # ===========================================
576
577 class NetBsdGroup(Group):
578 """
579 This is a NetBSD Group manipulation class.
580
581 This overrides the following methods from the generic class:-
582 - group_del()
583 - group_add()
584 - group_mod()
585 """
586
587 platform = 'NetBSD'
588 distribution = None
589 GROUPFILE = '/etc/group'
590
591 def group_del(self):
592 if self.module.params['force']:
593 self.module.fail_json(msg='The force option is not supported for group deletion on this platform.')
594 cmd = [self.module.get_bin_path('groupdel', True), self.name]
595 return self.execute_command(cmd)
596
597 def group_add(self, **kwargs):
598 cmd = [self.module.get_bin_path('groupadd', True)]
599 if self.gid is not None:
600 cmd.append('-g')
601 cmd.append(str(self.gid))
602 if self.non_unique:
603 cmd.append('-o')
604 if self.gid_min is not None:
605 cmd.append('-K')
606 cmd.append('GID_MIN=' + str(self.gid_min))
607 if self.gid_max is not None:
608 cmd.append('-K')
609 cmd.append('GID_MAX=' + str(self.gid_max))
610 cmd.append(self.name)
611 return self.execute_command(cmd)
612
613 def group_mod(self, **kwargs):
614 cmd = [self.module.get_bin_path('groupmod', True)]
615 info = self.group_info()
616 if self.gid is not None and int(self.gid) != info[2]:
617 cmd.append('-g')
618 cmd.append(str(self.gid))
619 if self.non_unique:
620 cmd.append('-o')
621 if len(cmd) == 1:
622 return (None, '', '')
623 if self.module.check_mode:
624 return (0, '', '')
625 cmd.append(self.name)
626 return self.execute_command(cmd)
627
628
629 # ===========================================
630
631
632 class BusyBoxGroup(Group):
633 """
634 BusyBox group manipulation class for systems that have addgroup and delgroup.
635
636 It overrides the following methods:
637 - group_add()
638 - group_del()
639 - group_mod()
640 """
641
642 def group_add(self, **kwargs):
643 cmd = [self.module.get_bin_path('addgroup', True)]
644 if self.gid is not None:
645 cmd.extend(['-g', str(self.gid)])
646
647 if self.system:
648 cmd.append('-S')
649
650 if self.gid_min is not None:
651 cmd.append('-K')
652 cmd.append('GID_MIN=' + str(self.gid_min))
653
654 if self.gid_max is not None:
655 cmd.append('-K')
656 cmd.append('GID_MAX=' + str(self.gid_max))
657
658 cmd.append(self.name)
659
660 return self.execute_command(cmd)
661
662 def group_del(self):
663 if self.module.params['force']:
664 self.module.fail_json(msg='The force option is not supported for group deletion on this platform.')
665
666 cmd = [self.module.get_bin_path('delgroup', True), self.name]
667 return self.execute_command(cmd)
668
669 def group_mod(self, **kwargs):
670 # Since there is no groupmod command, modify /etc/group directly
671 info = self.group_info()
672 if self.gid is not None and self.gid != info[2]:
673 with open('/etc/group', 'rb') as f:
674 b_groups = f.read()
675
676 b_name = to_bytes(self.name)
677 b_current_group_string = b'%s:x:%d:' % (b_name, info[2])
678 b_new_group_string = b'%s:x:%d:' % (b_name, self.gid)
679
680 if b':%d:' % self.gid in b_groups:
681 self.module.fail_json(msg="gid '{gid}' in use".format(gid=self.gid))
682
683 if self.module.check_mode:
684 return 0, '', ''
685 b_new_groups = b_groups.replace(b_current_group_string, b_new_group_string)
686 with open('/etc/group', 'wb') as f:
687 f.write(b_new_groups)
688 return 0, '', ''
689
690 return None, '', ''
691
692
693 class AlpineGroup(BusyBoxGroup):
694
695 platform = 'Linux'
696 distribution = 'Alpine'
697
698
699 def main():
700 module = AnsibleModule(
701 argument_spec=dict(
702 state=dict(type='str', default='present', choices=['absent', 'present']),
703 name=dict(type='str', required=True),
704 force=dict(type='bool', default=False),
705 gid=dict(type='int'),
706 system=dict(type='bool', default=False),
707 local=dict(type='bool', default=False),
708 non_unique=dict(type='bool', default=False),
709 gid_min=dict(type='int'),
710 gid_max=dict(type='int'),
711 ),
712 supports_check_mode=True,
713 required_if=[
714 ['non_unique', True, ['gid']],
715 ],
716 )
717
718 if module.params['force'] and module.params['local']:
719 module.fail_json(msg='force is not a valid option for local, force=True and local=True are mutually exclusive')
720
721 group = Group(module)
722
723 module.debug('Group instantiated - platform %s' % group.platform)
724 if group.distribution:
725 module.debug('Group instantiated - distribution %s' % group.distribution)
726
727 rc = None
728 out = ''
729 err = ''
730 result = {}
731 result['name'] = group.name
732 result['state'] = group.state
733
734 if group.state == 'absent':
735
736 if group.group_exists():
737 if module.check_mode:
738 module.exit_json(changed=True)
739 (rc, out, err) = group.group_del()
740 if rc != 0:
741 module.fail_json(name=group.name, msg=err)
742
743 elif group.state == 'present':
744
745 if not group.group_exists():
746 if module.check_mode:
747 module.exit_json(changed=True)
748 (rc, out, err) = group.group_add(gid=group.gid, system=group.system)
749 else:
750 (rc, out, err) = group.group_mod(gid=group.gid)
751
752 if rc is not None and rc != 0:
753 module.fail_json(name=group.name, msg=err)
754
755 if rc is None:
756 result['changed'] = False
757 else:
758 result['changed'] = True
759 if out:
760 result['stdout'] = out
761 if err:
762 result['stderr'] = err
763
764 if group.group_exists():
765 info = group.group_info()
766 result['system'] = group.system
767 result['gid'] = info[2]
768
769 module.exit_json(**result)
770
771
772 if __name__ == '__main__':
773 main()