Devendra Date
Devendra Date

Reputation: 133

Add user to group using Ansible

I have installed and configured Ansible on the server for config management purpose.

under /etc/ansible/hosts file, I have added [servers] part and mentioned all servers which I need to maintain

I have one Ubuntu server in that

In my test.yml file I have written this code,

---
- hosts: servers
  become: yes
  tasks:
  - name: Add user
    user:
      name: james
      shell: /bin/bash
     groups: wheel
     state: present
    remove: yes

Problem is that in Ubuntu there is no wheel group present but sudo is.

so I want that server to add a user in sudo group and for others to add to the wheel group

how I can do condition in ansible in that code

Upvotes: 1

Views: 6684

Answers (1)

techraf
techraf

Reputation: 68509

You can include variables depending on distribution with include_vars module.

Ansible saves the value of target system's distribution in ansible_distribution fact.


Use a variable (group_for_james) in your task instead of a string:

- name: Add user
  user:
    name: james
    shell: /bin/bash
    groups: "{{ group_for_james }}"
    state: present
    remove: yes

Define a default value for user in the play:

vars:
  group_for_james: wheel

Then create a vars file for Ubuntu (save it for example as vars/ubuntu.yml):

group_for_james: sudo

Add a task (before the Add user task) which will overwrite the value if the target is running Ubuntu:

- include_vars: vars/ubuntu.yml
  when: ansible_distribution == 'Ubuntu'

Other patterns for including are also possible, see the third example on the linked doc page.

Upvotes: 4

Related Questions