Conditionally running a filter in a chain

31 views
Skip to first unread message

Jean-Francois Bibeau

unread,
Aug 24, 2017, 10:36:41 AM8/24/17
to Ansible Project
Hi,

Trying to do the following, and struggling to find a way to do this.

I build a list of strings, and want to conditionally append a string at the end of the list, but only if the variable is defined.

This works fine:

play_hosts | union([optional_ip])


Which appends optional_ip to play_hosts, however if optional_ip is not defined, I would like to simply drop the union filter... If I change it to:

play_hosts | union([optional_ip | default(None)])

It appends an empty string. I was hoping I could maybe use "or omit" after the union but can't quite get that to work.

Any suggestions?

Thanks!

Kai Stian Olstad

unread,
Aug 25, 2017, 4:23:23 PM8/25/17
to ansible...@googlegroups.com
You could try to add a when to the task
when: optional_ip is defined

--
Kai Stian Olstad

Daniel JD

unread,
Aug 26, 2017, 6:31:37 AM8/26/17
to Ansible Project
Isn't play_hosts a reserved ansible variable (deprecatd but still..). Maybe try another name.

Jean-Francois Bibeau

unread,
Aug 26, 2017, 9:09:12 AM8/26/17
to Ansible Project
Thanks Kai, that's one option for sure.

Jean-Francois Bibeau

unread,
Aug 26, 2017, 9:10:02 AM8/26/17
to Ansible Project
@Daniel - I'm using the Ansible play_hosts variable and optionally joining another IP to that existing list.

Jean-Francois Bibeau

unread,
Aug 28, 2017, 9:49:30 AM8/28/17
to Ansible Project
I like Kai's suggestion and will likely end up breaking the tasks into multiple chunks using 'when'. However for completeness' sake, I also got the following to work:

play_hosts | union(optional_ip is defined | ternary([optional_ip], []))

(ie: union the variable if it's defined, otherwise union empty list).
Reply all
Reply to author
Forward
0 new messages