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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With