Harinder
Harinder

Reputation: 21

Is there a way to filter ansible vars based on condition

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

Answers (1)

Zeitounator
Zeitounator

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:

  • I defined a "private" variable _default_services. This is the list of services that will always be included.
  • I calculated the variable services which is an addition of two lists: _default_services and the additional value to add depending on user input. For this last one:
    • I used rmetcd containing the value (which should be "yes" or "no")
    • I applied the bool filter to cast the value to boolean
    • and I used the ternary filter to select a single element list if true (['etcd']) and an empty list if false ([]).

Upvotes: 1

Related Questions