ansible - 尝试动态形成条件时,替代在“when”中进行模板化
问题描述
我试图通过声明以下变量来动态创建条件
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 %}\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"}
有没有更好的方法来编写它以避免在条件语句中进行模板化?
解决方案
为了实现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 中外部的需要)