Looping through hosts in a playbook

I’m working on a playbook, that will be deploying a java app to four hosts. I want it to push the app out to each node, making sure the correct directories exist to push the new version to - that’s the easy part, and it can do all four of the nodes at once, no issue there. But then I want it to loop through the list of hosts, taking them out of the load balancer, changing the app version that is linked on each node, and then put them back into the load balancer, one at a time. All of the tasks are easily enough performed, but the looping part I’m not sure about. I’ve googled looping through hosts, but mainly I’m finding articles on how to loop through hosts in a template.

Is it possible to run through hosts in a loop as a task, or alternatively, can the tasks be run from a template? I suppose I could just set the whole playbook to do just one host at a time (serial: 1), or do multiple ansible runs, limiting the run to one host at a time, but that seems a bit inelegant - it seems like the tasks that can safely be run in parallel should be, and the tasks that can’t should be looped. Am I overthinking this?

Roger, did you try to use “with_items” (http://docs.ansible.com/ansible/playbooks_loops.html#standard-loops)?

You might benefit from looking at http://radar.oreilly.com/2013/07/zero-downtime-application-updates-with-ansible.html

that seems close to what you’r trying to achiev

You can have multiple plays in a playbook. Put the tasks that can be done in parallel in one play and the tasks that need to be done one at a time in another play with “serial: 1”.

Hi Alexander,

I don’t think “with_items” is the way to go here - if I use “with_items”, it’s going to try to execute on all of the hosts at once, unless it can be used in a method that I haven’t thought of.

Thanks Philippe, I’ll look at that.

Oh, that’s an interesting idea, thanks Paul - I’ll do some experimenting with that.