我们假设user01定义了两个组:groupA和groupB(除了主要组之外)。
我可以使用以下方法将帐户添加到groupC(确保user01属于groupC):
- user: name=user01 groups=groupC append=yes
Run Code Online (Sandbox Code Playgroud)
如何在不指定帐户应属于的所有组的情况下user01从中删除groupB(确保user01不属于)?groupB
据我所知,你不能只使用普通的用户模块。
然而,对于一些相当疯狂的旋转,您可以在剧本中完成。但我不确定我是否推荐这个;这只是一个有趣的练习。(我确实测试过这个并且它有效。)
有趣的部分是“构建新组列表”任务,该任务删除列表条目。如果在 python 列表上调用 .remove() 返回新列表,那么这都是不必要的。
---
- hosts: target
gather_facts: no
vars:
group_to_remove: admins
new_groups_list: []
user_to_check: user1
tasks:
- user: name="{{ user_to_check }}" groups=testers,developers,admins
- name: get the current groups list
command: groups "{{ user_to_check }}"
register: current_groups
- debug: var=current_groups
# parse the output of the groups command into a python list
# of the current groups
- set_fact:
current_group_list: "{{ current_groups.stdout.replace( user_to_check+' : ','').split(' ') }}"
- name: show user_group_list
debug: var=current_group_list
- name: build the new groups list
set_fact:
new_groups_list: "{{ new_groups_list + [ item ] }}"
no_log: False
when: "not '{{ group_to_remove }}' == '{{ item }}'"
with_items: "{{ current_group_list }}"
# turn the list, into a comma-delimited string
- set_fact:
new_groups: "{{ ','.join(new_groups_list) }}"
- name: show new_groups_list
debug: var=new_groups
- name: set new user groups
user: name="{{ user_to_check }}" groups="{{ new_groups }}"
- name: get the new groups list
command: groups "{{ user_to_check }}"
register: new_groups
- debug: var=new_groups
Run Code Online (Sandbox Code Playgroud)
考虑到要删除的用户和组都是已知的,所提供的解决方案似乎相当复杂。我使用了这个 ansible 代码,它足以获得幂等行为,并且与其他建议的解决方案具有相同的 gpasswd 依赖性。
- name: remove user dovecot from the certuser group
become: true
command: "gpasswd -d dovecot certuser"
register: command_result
changed_when: "not 'is not a member of' in command_result.stderr"
failed_when: false
Run Code Online (Sandbox Code Playgroud)
如果您认为如果组不存在任务就会失败,只需修改最后一行:
- name: remove user dovecot from the certuser group
become: true
command: "gpasswd -d dovecot certuser"
register: command_result
changed_when: "not 'is not a member of' in command_result.stderr"
failed_when: "'does not exist in /etc/group' in command_result.stderr"
Run Code Online (Sandbox Code Playgroud)