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:
- some
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.