0

I just started using Ansible. Is there a Best Practice when managing multiple users accounts with Ansible; (e.g; creating, disabling, and removing user accounts). I thought, managing accounts from a csv file would be earlier. I haven't been able to find any reference or examples.
I created the following test below. But for usability, it seems it would be easier to run this against a csv file, and not have to edit the yml file every time.

    - hosts: servers
      remote_user: root
      tasks:
        - name: adding several users
          user:
             name={{ item.name }}
             state=present
             comment={{ item.comment }}
             password=$1$*)^%$CeUUJM&v#0pQhHjqjpqX1
             update_password=on_create
             createhome=yes
             groups={{ item.groups }}
          with_items:
             - { name: 'testuser3', comment: 'testuser3', groups: 'wheel' }
             - { name: 'testuser4', comment: 'testuser4', groups: 'users' }

Thank you for your help.

2

There is a good chapter in the docs: Variable File Separation.

Define users.yml:

users:
  - name: testuser3
    comment: testuser3
    groups: wheel
  - name: testuser4
    comment: testuser4
    groups: users

And in your playbook:

- hosts: servers
  remote_user: root
  vars_files:
    - /vars/users.yml
  tasks:
    - name: adding several users
      user:
        name: "{{ item.name }}"
        state: present
        comment: "{{ item.comment }}"
        password: "$1$*)^%$CeUUJM&v#0pQhHjqjpqX1"
        update_password: on_create
        createhome: yes
        groups: "{{ item.groups }}"
      with_items: "{{ users }}"

P.S. I also changed argument syntax to YAML instead of key=value – trust me, it is more robust in complex playbooks.

And if you want to manage different user sets on different hosts, you may want to use inventory group/host variables instead of play-level variable files.

| improve this answer | |
1

Since Ansible version 2.8 there is a module called read_csv.

# Example CSV file with header
#
#   name,uid,gid
#   dag,500,500
#   jeroen,501,500

# Read a CSV file and access the first item
- name: Read users from CSV file and return a list
  read_csv:
    path: users.csv
  register: users
  delegate_to: localhost

- debug:
    msg: 'User {{ users.list.1.name }} has UID {{ users.list.1.uid }} and GID {{ users.list.1.gid }}'
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.