8

I have this playbook:

  roles:
    - { role: common}
    - { role: mariadb}
    - { role: wordpress}

What is want is in every role I want to have first task as some conditional which if true then I want to skip the whole role and playbook continues to next.

Now I can use when like this:

  roles:
    - { role: common, when: mvar is False }

But for that I have to evaluate the mvar in playbook itself but for that mvar I need all other vars etc. stuff which is in that role itself. So it will be easier for me to do in role.

Is there any way?

techraf
  • 64,883
  • 27
  • 193
  • 198
Mr. Mirror
  • 95
  • 1
  • 1
  • 4
  • read this https://leucos.github.io/ansible-files-layout really good resource if you are just starting up and want to see "bigger picture". – Kyslik Feb 26 '17 at 12:26

3 Answers3

7

In each role, in tasks/main.yml include a file with tasks only when the condition is met:

- include: real_tasks.yml
  when: condition_is_met
techraf
  • 64,883
  • 27
  • 193
  • 198
2

In addition to @techraf's answer, one can also use include_tasks instead of include.

- include_tasks: real_tasks.yml
  when: condition_is_met

Ansible include documentation says:

Notes

Include has some unintuitive behaviours depending on if it is running in a static or dynamic in play or in playbook context, in an effort to clarify behaviours we are moving to a new set modules (include_tasks, include_role, import_playbook, import_tasks) that have well established and clear behaviours. This module will still be supported for some time but we are looking at deprecating it in the near future.

dheerendra
  • 121
  • 4
0

In addition to the answers above, you could also consider using Tags to skip specific tasks or roles depending on how you are calling the roles.

https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html

This will work well if the condition is determined in a less dynamic manner - so if you have a large playbook but know at the point of execution that you want to skip certain parts. Tags can also be used to selectively run specific tasks.

Note: using tags in this way is often a great way to test specific parts of a playbook during development without running the whole thing.