如何从Ansible中的指定组中删除用户?

问题描述 投票:4回答:5

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

我可以使用以下方式将帐户添加到groupC(确保user01属于groupC):

- user: name=user01 groups=groupC append=yes

如何在不指定帐户应属于的所有组的情况下从user01中删除groupB(确保user01不属于groupB

ansible ansible-playbook
5个回答
4
投票

据我所知,不能只使用普通的用户模块。

但是,通过一些相当疯狂的旋转,您可以在剧本中做到这一点。我不确定我是否建议这样做;这只是一个有趣的练习。 (我确实对此进行了测试,并且可以正常工作。)

有趣的部分是任务“构建新的组列表”,该任务将删除列表条目。如果在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

2
投票

缺少该功能,这是该功能的打开错误:

https://github.com/ansible/ansible/issues/11024

作为解决方法,请使用类似的方法。

  become: true
  shell: "/usr/sbin/delgroup telegraf varnish"
  ignore_errors: yes
  when: ansible_hostname | lower not in groups['varnish'] | lower

请根据您的需求进行调整,如果当前主机不在ansible组清漆列表中,我将从主机清漆组中删除telegraf用户


1
投票

改进answer from higuita添加了正确的条件:

- name: Get info from user1
  user:
    name: user1
    state: present
  register: user1_data

- name: remove user1 user from grouptodelete group
  become: true
  command: "gpasswd -d user1 grouptodelete"
  when: user1_data.groups is defined and 'grouptodelete' in user1_data.groups

0
投票

示例:从“泊坞窗”组中删除所有用户

- name: get all user into docker group
  shell: |
    awk -F':' '/^docker:/ {print $4}' /etc/group
  register: users_intogroup_docker
  changed_when: False

- name: no user into docker group
  command: gpasswd -d {{ item }} docker
  with_items: "{{ users_intogroup_docker.stdout.split(',') }}"
  when: not item in [""]

-1
投票

[还有一种使用Ansible的方法也必须使用正确的标志

您需要对no或false使用append标志来告诉Ansbile不要将用户追加到组中

- user:
    name: hive
    shell: /bin/bash
    groups: hadoop
    append: no
    state: present
© www.soinside.com 2019 - 2024. All rights reserved.