Hi,
It’s definitely something you can do with Ansible although your playbook might become kind of a mess
I’d say if you value readability and simplicity, use something else (a simple bash or python script would be more appropriate for this kind of logical flow IMO, though I really like to bend Ansible for this kind of stuff ), if not, a bit of Jinja magic will do the trick.
I’ll see if I can figure something out on the upcoming week-end.