When using conditionals in ansible, most of the time you'll use 'when' and specify which parameter should be checked. This can however result in a rather lengthy and confusing list of tasks that can be easily reduced.
Here's an example of a list of tasks that create users:
- name: create regular users | --password, --groups
become: true
loop: "{{ users }}"
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
shell: "{{ item.shell | default('/bin/sh') }}"
when: not item.groups is defined and not item.password is defined
tags:
- all
- users
- name: create regular users | --password, ++groups
become: true
loop: "{{ users }}"
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
shell: "{{ item.shell | default('/bin/sh') }}"
groups: "{{ item.groups }}"
when: item.groups is defined and not item.password is defined
tags:
- all
- users
- name: create regular users | ++password, --groups
become: true
loop: "{{ users }}"
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
shell: "{{ item.shell | default('/bin/sh') }}"
password: "{{ item.password }}"
when: not item.groups is defined and item.password is defined
tags:
- all
- users
- name: create regular users | ++password, ++groups
become: true
loop: "{{ users }}"
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
shell: "{{ item.shell | default('/bin/sh') }}"
groups: "{{ item.groups }}"
password: "{{ item.password }}"
when: item.groups is defined and item.password is defined
tags:
- all
- users
As you can see, there are 4 tasks that do essentially the same with different arguments. Arguably this is more flexible than just one task that statically requires attributes but it's 4 tasks that have to be considered when searching for problems.
However, there's a best of both worlds approach to this using conditionals:
- name: create regular users
become: true
loop: "{{ users }}"
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
shell: "{{ item.shell | default('/bin/sh') }}"
groups: "{{ item.groups if item.groups is defined else omit }}"
password: "{{ item.password if item.password is defined else omit }}"
tags:
- all
- users
This way you maintain flexibility while also reducing the tasks that need to be run at the same time.
Feel free to comment and / or suggest a topic.
Comments
Post a Comment