Reputation: 21
I have this vars in the playbook and multiple tasks, I just want to filter the items from vars list based on the prompt input. Right now I have to exclude that item using when from multiple tasks. Please see following example:
vars_prompt:
- name: rmetcd
prompt: "remove etcd: YES OR NO?"
private: no
vars:
containers:
- "etcd"
- "mysql"
- "postgres"
folders:
- "etcd"
- "mysql"
- "postgres"
tasks:
- name: remove container
shell: "docker rm -f {{ item }}"
with_items: "{{ containers }}"
when:
- '"etcd" not in item'
- name: remove folder
file:
path: "{{ item }}"
state: absent
with_items: "{{ folders }}"
when:
- '"etcd" not in item'
when: rmetcd == "NO"
Upvotes: 0
Views: 545
Reputation: 44808
I would take the problem in reverse order: rather than filtering my list for each task to potentially take out an element, I would define my list with default elements and add the additional one if user answered yes.
Note: your two lists are identical, I only kept one in the following example:
---
- hosts: localhost
gather_facts: false
vars_prompt:
- name: rmetcd
prompt: "Remove etcd [yes/no]?"
private: no
vars:
_default_services:
- mysql
- postgres
services: "{{ _default_services + (rmetcd | bool | ternary(['etcd'], [])) }}"
tasks:
- name: task1
debug:
msg: "remove container {{ item }}"
loop: "{{ services }}"
- name: taks2
debug:
msg: "remove folder {{ item }}"
loop: "{{ services }}"
The key points:
_default_services
. This is the list of services that will always be included.services
which is an addition of two lists: _default_services
and the additional value to add depending on user input. For this last one:
rmetcd
containing the value (which should be "yes" or "no")bool
filter to cast the value to booleanternary
filter to select a single element list if true (['etcd']
) and an empty list if false ([]
).Upvotes: 1