How to run a play based on a variable

Hey all - I’m trying to figure out a way to run a play based on the value of a variable (i.e., if variable is set, run the play, otherwise skip the play). Scouring the internet, it looks like we used to be able to do this with https://docs.ansible.com/ansible/2.9/modules/include_module.html:

- name: run stuff on standby
  include: standby_play.yml
  when: standby_cluster is defined

But the include module has been removed. import_playbook won’t work because it imports statically. include_tasks won’t work because I need to specify the hosts, not just a task list.

I can’t figure out another elegant way to do this, so asking for help.

What’s the use case? I run a lot of Oracle databases, and we do everything with Ansible. Occasionally, we run Oracle Data Guard, where we have a primary database and a standby (replica) database. When we provision (or update) a database, we need to run plays on the primary cluster hosts and, if standby_cluster is defined in config.yml, we also need to run plays on the standby cluster hosts. Right now, I have separate playbooks: one for the primary cluster, and a second for the standby (replica) cluster. I’d like to combine those into one playbook so folks don’t have to remember to run the latter if they are supporting a standby database.

Any ideas out there?

Thanks
Rob

This seems to imply that you should be able to do

- name: stuff to run on standby
  import_tasks: standby_play.yml
  when: standby_cluster is defined

and, per the doc: “All the tasks get evaluated, but the conditional is applied to each and every task”

which sounds like all the tasks will get imported, but they’ll only run on hosts that have that var defined.

import_playbook does exactly the same thing that include at the playbook level did. If you cannot do it now with import_playbook, it did not work when import_playbook was called include.

4 Likes

Alternatively, create an inventory group for your oracle data guard hosts and target the playbook to that group. It’ll do the selection at the playbook level to limit the hosts in the play loop instead of a lot skips from the static import.

Thanks all. Not elegant, but I managed to do it with include_tasks and a when: condition.

1 Like