Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Add Unix group to user only if the group exists

Tags:

unix

ansible

I'm using Ansible to add a user to a variety of servers. Some of the servers have different UNIX groups defined. I'd like to find a way for Ansible to check for the existence of a group that I specify, and if that group exists, add it to a User's secondary groups list (but ignore the statement it if the group does not exist).

Any thoughts on how I might do this with Ansible?

Here is my starting point.

Command

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"

Updated: based on the solution suggested by @udondan, I was able to get this working with the following additional tasks.

    - 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
like image 328
Joe J Avatar asked Mar 04 '16 23:03

Joe J


People also ask

How do you check if a user exists in Linux using Ansible?

You can simply use the getent module. If the user is present, the play will continue. If the user does not exist, the play will fail. Save this answer.

What are the advantages of using Ansible to manage users and groups?

Agentless - Simplifying configuration management using Ansible does not require users to install agents or additional software and firewall ports on hosts or client systems for automation. Flexible - Configuration management tools offer robust features needed to model complex IT workflows.


1 Answers

The getent module can be used to read /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
like image 59
Frank Avatar answered Oct 16 '22 16:10

Frank