You can apply the when condition to a task, block, and role only. import_playbook is the only way how to apply a condition to a playbook.
For testing, simplify the code by putting the condition into variables. For example,
shell> cat group_vars/all/conditions.yml
condition_01: "{{ env_tag|d('') == 'azure' and my_var is defined }}"
Then the playbooks
shell> cat pb1.yml
- hosts: all
tasks:
- debug:
var: inventory_hostname
shell> cat pb2.yml
- import_playbook: pb1.yml
when: condition_01
- hosts: all
tasks:
- debug:
var: inventory_hostname
when: condition_01
work as expected
shell> ansible-playbook pb2.yml -l test_11 -e my_var=foo -e env_tag=azure
PLAY [all] ************************************************************************************
TASK [debug] **********************************************************************************
ok: [test_11] =>
inventory_hostname: test_11
PLAY [all] ************************************************************************************
TASK [debug] **********************************************************************************
ok: [test_11] =>
inventory_hostname: test_11
PLAY RECAP ************************************************************************************
test_11: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
- You can use the condition only once with a third playbook. For example,
shell> cat pb3.yml
- import_playbook: pb2.yml
when: condition_01
shell> cat pb2.yml
- import_playbook: pb1.yml
- hosts: all
tasks:
- debug:
var: inventory_hostname
gives the same result
shell> ansible-playbook pb3.yml -l test_11 -e my_var=foo -e env_tag=azure
PLAY [all] ************************************************************************************
TASK [debug] **********************************************************************************
ok: [test_11] =>
inventory_hostname: test_11
PLAY [all] ************************************************************************************
TASK [debug] **********************************************************************************
ok: [test_11] =>
inventory_hostname: test_11
PLAY RECAP ************************************************************************************
test_11: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0