Ansible:仅当组存在时才将Unix组添加到用户

时间:2016-03-04 23:21:59

标签: unix ansible

我使用Ansible将用户添加到各种服务器。某些服务器定义了不同的UNIX组。我想为Ansible找到一种方法来检查我指定的组是否存在,如果该组存在,则将其添加到用户的辅助组列表中(但如果组不存在)。

有关如何使用Ansible进行此操作的任何想法?

这是我的出发点。

命令

ansible-playbook -i 'localhost,' -c local ansible_user.yml

ansible_user.yml

---

- hosts: all
  user: root
  become: yes
  vars:
    password: "!"
    user: testa
  tasks:
    - name: add user
      user: name="{{user}}"
            state=present
            password="{{password}}"
            shell=/bin/bash
            append=yes
            comment="test User"

更新:根据@udondan建议的解决方案,我能够使用以下附加任务。

    - name: Check if user exists
      shell: /usr/bin/getent group | awk -F":" '{print $1}'
      register: etc_groups

    - name: Add secondary Groups to user
      user: name="{{user}}" groups="{{item}}" append=yes
      when: '"{{item}}" in etc_groups.stdout_lines'
      with_items: 
          - sudo
          - wheel

2 个答案:

答案 0 :(得分:9)

你有什么东西可以识别那些不同的主机类型吗?

如果没有,您首先需要检查该主机上存在哪些组。您可以使用命令groups | tr -s " " "\012"执行此操作,该命令将每行输出一个组。

您可以将此作为单独的任务使用,如下所示:

- shell: groups | tr -s " " "\012"
  register: unix_groups

然后,当您要添加用户组

时,可以在以后使用注册结果
- user: ...
  when: "some_group" in unix_groups.stdout_lines

答案 1 :(得分:8)

getent模块可用于读取/ etc / group

- name: Determine available groups
  getent:
    database: group

- name: Add additional groups to user
  user: name="{{user}}" groups="{{item}}" append=yes
  when: item in ansible_facts.getent_group
  with_items: 
      - sudo
      - wheel