我试图通过声明以下变量来动态创建一个条件
in_tags: in ansible_run_tags or "all" in ansible_run_tags
并在类似的情况下使用
- include: zsh.yml
when: '"zsh" {{ in_tags }}'
然而,当我这样做时,Ansible会发出以下警告
[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {%
%}. Found: "zsh" {{ in_tags }}
删除{{ }}
会导致此操作失败。
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 %}nnThe error appears to be in '[REDACTED]/playbook/roles/fzf/tasks/zsh.yml': line 1, column 3, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nnn- name: Ensure zsh integrationn ^ heren"}
有没有更好的方法来避免在条件语句中使用模板?
为了在when
块中实现动态评估,自定义测试是实现的正确方法
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)'
似乎没有办法从过滤器或测试中引用vars
或hostvars
中的内容。显然,如果您愿意,您可以通过交换测试函数参数的顺序来将顺序反转为when: ansible_run_tags is my_when_test("zsh")
,如果您觉得这读起来更好(并省去了对yaml中外部'
的需要(