如何从 Ansible 中的指定组中删除用户? [英] How to remove user from a specified group in Ansible?
问题描述
假设 user01
定义了两个组:groupA
和 groupB
(除了主要组).
Let's assume user01
has two groups defined: groupA
and groupB
(in addition to the primary group).
我可以使用以下方法将帐户添加到 groupC
(确保 user01
属于 groupC
):
I can add the account to groupC
(ensure user01
belongs to groupC
) using:
- user: name=user01 groups=groupC append=yes
如何从 groupB
中删除 user01
(确保 user01
不属于 groupB
)而不指定所有该帐户应属于哪些组?
How can I remove user01
from groupB
(ensure user01
does not belong to groupB
) without specifying all the groups the account should belong to?
推荐答案
据我所知,你不能只使用普通的用户模块.
As far as I can tell, you can't with just the normal user module.
但是,通过一些相当疯狂的旋转,您可以在剧本中做到这一点.不过,我不确定我是否推荐这个;这只是一个有趣的练习.(我确实测试过它并且有效.)
However, with some fairly crazy gyrations, you can do it in a playbook. I'm not sure I recommend this though; it was just an interesting exercise. (I did test this and it worked.)
有趣的部分是构建新组列表"任务,它删除了一个列表条目.如果在 python 列表上调用 .remove() 返回新列表,那都是不必要的.
The interesting part is the task "build the new groups list", which removes a list entry. If calling .remove() on a python list returned the new list, that would all be uneccessary.
---
- 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
这篇关于如何从 Ansible 中的指定组中删除用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!