Ansible: restrict list to unique elements

Karol Jędrzejczyk picture Karol Jędrzejczyk · Feb 15, 2018 · Viewed 8.2k times · Source

I'm writing a playbook to manage users on our servers defined in users.yml:

---
users:
- login: ab
  full_login: abcdef
  name: Aaaa Bbbb,,,
  admin_on: server1, server2
  regular_on: server3
  active: yes

I would like to include some protection from a situation when there will be two different users with the same login defined. The playbook looks like this:

---
- name: Provision users on servers
  hosts: all
  remote_user: morty
  become: yes
  vars_files: 
    - users.yml

  tasks:
  - name: Create users
    user:
      name: "{{ item.login }}"
      comment: "{{ item.name }}"
      update_password: on_create
    with_items:
      - "{{ users }}"
    when: ???

What is the recommended course of action? Should I create another list that will keep track of already processed logins or is there a better way?

Answer

Konstantin Suvorov picture Konstantin Suvorov · Feb 15, 2018

Use assertion task to make preflight checks at the very beginning of your playbook:

  - name: Safety check
    assert:
      that: >
            users | map(attribute='login') | list | count
            ==
            users | map(attribute='login') | list | unique | count

In this case we check that the length of original list of logins is the same as of list with unique logins.