本文介绍了如何从Ansible中的指定组中删除用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设user01有两个已定义的组:groupAgroupB(除了主要组).

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中的指定组中删除用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 07:17