Reputation: 3
I am trying to dynamically create a conditional by declaring the following variable
in_tags: in ansible_run_tags or "all" in ansible_run_tags
and use it in a when condition like so
- include: zsh.yml
when: '"zsh" {{ in_tags }}'
However Ansible gives the following warning when I do so
[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {%
%}. Found: "zsh" {{ in_tags }}
Removing the {{ }}
causes this to fail.
fatal: [localhost]: FAILED! => {"msg": "The conditional check '\"zsh\" in_tags' failed. The error was: template error while templating string: expected token 'end of statement block', got 'in_tags'. String: {% if \"zsh\" in_tags %} True {% else %} False {% endif %}\n\nThe error appears to be in '[REDACTED]/playbook/roles/fzf/tasks/zsh.yml': line 1, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Ensure zsh integration\n ^ here\n"}
Is there a better way to write this to avoid templating within the conditional statement?
Upvotes: 0
Views: 193
Reputation: 33231
In order to achieve the dynamic evaluation in a when
block, a custom test is the correct way to do that
mkdir test_plugins
cat > test_plugins/my_when_test.py<<"PY"
def my_when_test(the_tag, ansible_run_tags):
return the_tag in ansible_run_tags or "all" in ansible_run_tags
class TestModule(object):
def tests(self):
return {
"my_when_test": my_when_test,
}
PY
- include: zsh.yml
when: '"zsh" is my_when_test(ansible_run_tags)'
There does not appear to be a way to reference things in the vars
or hostvars
from either a filter or a test. Obviously, if you prefer you can invert the order as when: ansible_run_tags is my_when_test("zsh")
by swapping the order of the test function's arguments, if you feel that reads nicer (and saves you the need for the outer '
in yaml)
Upvotes: 1