`run_once` used together with `when` not generating expected result

535 views
Skip to first unread message

Qiu Yu

unread,
Jan 18, 2016, 8:26:15 AM1/18/16
to Ansible Project
Hi,

I have following playbook, which I expect it to run only once, on one of the `group2` hosts.

site.yml
---
- hosts:
   
- group1
   
- group2
  roles
:
 
- { role: test }

roles/test/tasks/main.yml
---
- include: test.yml
 
when: inventory_hostname in groups['group2']

roles/test/tasks/test.yml
---
- name: test - include together with run_once
  debug
: var='abc'
  run_once
: true

However, after skipping the `host1` from group1 (since it is the first in site.yml), it never run on host2.

$ ansible-playbook -i test_inventory site.yml
PLAY [group1;group2] **********************************************************

GATHERING FACTS
***************************************************************
ok
: [host1]
ok
: [host2]

TASK
: [test | test - include together with run_once] **************************
skipping
: [host1]

PLAY RECAP
********************************************************************
host1
: ok=1    changed=0    unreachable=0    failed=0
host2
: ok=1    changed=0    unreachable=0    failed=0

# cat test_inventory
[group1]
host1

[group2]
host2

Does that mean `run_once` and `when` better not to be used together? Shouldn't that `include: test.yml` only executed when `inventory_hostname in groups['group2']` satisfied? Some pointer or explanation would be highly appreciated.


Thanks,
QY

Brian Coca

unread,
Jan 18, 2016, 10:30:58 AM1/18/16
to Ansible Project
run_once limits the task to run on the 'first host' in the current
play, so the when only evaluates for that host, if that host is not in
'group2' it will be skipped an no other host will be evaluated.



--
Brian Coca

Qiu Yu

unread,
Jan 18, 2016, 1:44:44 PM1/18/16
to Ansible Project
Does that mean the `include` statement will be evaluated first no matter if `when` statement is satisfied or not?

QY

Brian Coca

unread,
Jan 18, 2016, 1:49:08 PM1/18/16
to Ansible Project
This is tricky, task includes are now dynamic in 2.0. Before 2.0 the
when: does not stop the include from happening, it just gets applied
to each included task, in 2.0 it does that only if the when cannot be
resolved with the information available at the time of the include.

--
Brian Coca

Qiu Yu

unread,
Jan 18, 2016, 2:00:16 PM1/18/16
to Ansible Project
That explains a lot! Thanks Brian!!

QY 

Larry Smith

unread,
Jan 18, 2016, 2:54:34 PM1/18/16
to Ansible Project
I banged my head against this same thing months ago until it finally clicked on what was going on!

csu...@gmail.com

unread,
Aug 26, 2020, 11:42:33 AM8/26/20
to Ansible Project
Yes but what is the solution to combine those?
I need to execute a task on the second host in the play.

Op maandag 18 januari 2016 om 20:54:34 UTC+1 schreef mrles...@gmail.com:
Reply all
Reply to author
Forward
0 new messages