Inforedaster Inforedaster - 15 days ago 10
YAML Question

ansible conditional "when" not works with role

in my playbook i have a condition to execute role according the version in the playbook command but it executes the two roles when i add version=8

- hosts: tomcat-servers
remote_user: root
become: yes
become_method: sudo

pre_tasks:
- debug: var=version
roles:
- { role: tomcat7, when: version == '7' }
- { role: tomcat8, when: version == '8' }


the command :

ansible-playbook -i hosts site.yml --extra-vars "version=8"


for the debug output :

TASK [debug] *******************************************************************
ok: [192.168.139.129] => {
"version": "8"
}


any help?

ansible 2.1.0.0

Answer

(sample output from pastebin above)

ubuntu# ansible-playbook -i hosts site.yml --extra-vars "version=8"

PLAY [tomcat-servers] **********************************************************

TASK [setup] *******************************************************************
ok: [192.168.139.129]

TASK [debug] *******************************************************************
ok: [192.168.139.129] => {
    "version": "8"
}

TASK [tomcat7 : Install Java 1.8] **********************************************
skipping: [192.168.139.129]

[..]
TASK [tomcat8 : Install Java 1.8] **********************************************
ok: [192.168.139.129]

TASK [tomcat8 : add group "tomcat"] ********************************************
ok: [192.168.139.129]

[...]
PLAY RECAP *********************************************************************
192.168.139.129            : ok=14   changed=0    unreachable=0    failed=0

You can see from the tasks above that there are two types:

  1. skipping: [192.168.139.129]
  2. ok: [192.168.139.129]

This is ansibles way notifying you if a task is executed or not.

So when you specify version=8, you are only executing tomcat8 role, but tomcat7 tasks are displayed as skipped.

If you enable colours, you can see the different colours for the tasks (skipped = blue, changed = yellow)

enter image description here