Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an item to a list dependent on a conditional in ansible

Tags:

ansible

I would like to add an item to a list in ansible dependent on some condition being met.

This doesn't work:

  some_dictionary:
    app:
       - something
       - something else
       - something conditional # only want this item when some_condition == True
         when: some_condition

I am not sure of the correct way to do this. Can I create a new task to add to the app value in the some_dictionary somehow?

like image 935
Mike Vella Avatar asked Aug 26 '16 11:08

Mike Vella


2 Answers

You can filter out all falsey values with select(), but remember to apply the list() filter afterwards. This seems an easier and more readable approach for me:

- name: Test
  hosts: localhost
  gather_facts: no
  vars:
      mylist:
        - "{{ (true)  | ternary('a','') }}"
        - "{{ (false) | ternary('b','') }}"
        - "{{ (true)  | ternary('c','') }}"
 
  tasks:
  - debug:
      var: mylist|select|list

Result:

TASK [debug] *****************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "mylist|select()|list": [
        "a", 
        "c"
    ]
}

Replace (true) and (false) with whatever test you want.

like image 184
Alvaro Flaño Larrondo Avatar answered Oct 25 '22 04:10

Alvaro Flaño Larrondo


Is there a reason you have to do everything in one go?

This is pretty easy if you specify the additional item(s) to add in separate vars, as you can just do list1 + list2.

---
- hosts: localhost
  gather_facts: False
  connection: local
  vars:
    mylist:
      - one
      - two
    mycondition: False
    myconditionalitem: foo
  tasks:
    - debug:
        msg: "{{ mylist + [myconditionalitem] if mycondition else mylist }}"
like image 34
Halberom Avatar answered Oct 25 '22 03:10

Halberom