6

I want to run ansible adhoc command on a list of EC2 instances. I want ansible to run it in sequence but ansible runs them in random. For example:

13:42:21 @cnayak ansible :► ansible aws -a "hostname"
ec2 | SUCCESS | rc=0 >>
ip-172-31-36-255

ec3 | SUCCESS | rc=0 >>
ip-172-31-45-174

13:42:26 @cnayak ansible :► ansible aws -a "hostname"
ec3 | SUCCESS | rc=0 >>
ip-172-31-45-174

ec2 | SUCCESS | rc=0 >>
ip-172-31-36-255

Any way to make them run in order?

slm
  • 15,396
  • 12
  • 109
  • 124
Chandan Nayak
  • 10,117
  • 5
  • 26
  • 36

3 Answers3

13

By default ansible runs tasks in parallel. If you want them to be executed serially then you can limit number of workers running at the same time by using "--forks" option.

Adding "--forks 1" to your ansible invocation should run your command sequentially on all hosts (in order defined by inventory).

bjakubski
  • 1,477
  • 10
  • 9
7

You can use the forks with adhoc command and serial: 1 inside the playbook.

On adhoc command:

ansible aws -a "hostname" --forks=1

Inside the playbook:

- hosts: aws
  become: yes
  gather_facts: yes
  serial: 1
  tasks:
    - YOUR TASKS HERE
Arbab Nazar
  • 22,378
  • 10
  • 76
  • 82
2

--forks=1 hasn't been sorting inventory for me in recent versions of ansible (2.7)

Another approach I find useful is using the "oneline" output callback, so I can use the standard sort and grep tools on the output:

ANSIBLE_LOAD_CALLBACK_PLUGINS=1 \
ANSIBLE_STDOUT_CALLBACK=oneline \
ansible \
  -m debug -a "msg={{ansible_host}}\t{{inventory_hostname}}" \
  | sort \
  | grep -oP '"msg": \K"[^"]*"' \
  | xargs -n 1 echo -e

This has been useful for quick-n-dirty reports on arbitrary vars or (oneline) shell command outputs.