Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: restrict list to unique elements

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?

like image 450
Karol Jędrzejczyk Avatar asked Feb 15 '18 14:02

Karol Jędrzejczyk


People also ask

How do you use limits in Ansible?

Ansible command limit optionUsing the --limit parameter of the ansible-playbook command is the easiest option to limit the execution of the code to only one host. The advantage is that you don't need to edit the Ansible Playbook code before executing to only one host.

What is Hostvars Ansible?

With hostvars , you can access variables defined for any host in the play, at any point in a playbook. You can access Ansible facts using the hostvars variable too, but only after you have gathered (or cached) facts.

How does Ansible Group_vars work?

The group_vars in Ansible are a convenient way to apply variables to multiple hosts at once. Group_vars is an Ansible-specific folder as part of the repository structure. This folder contains YAML files created to have data models, and these data models apply to all the devices listed in the hosts.


1 Answers

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.

like image 54
Konstantin Suvorov Avatar answered Nov 15 '22 10:11

Konstantin Suvorov