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?
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.
I'd try to avoid this, but if conditional list is absolutely necessary, you can use this trick:
It will form an array-like string (
["item1","item2","item3"]
) and ansible variable templator will convert it into list before assigning toapp
.Based on Konstantin's solution I developed the following:
This will create a list with items "item1" till "itemN", but each item is only appended if the corresponding flag expands to 'True'.
Hope, this helps.