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?
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.
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.
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.
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.
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