尝试动态形成条件时替代在 `when` 中进行模板化

Alternative to templating inside `when` when trying to dynamically form a conditional

我正在尝试通过声明以下变量来动态创建条件

in_tags: in ansible_run_tags or "all" in ansible_run_tags

并像这样在 when 条件下使用它

- 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 块中实现动态评估,a custom test 是正确的方法

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)'

似乎没有办法从过滤器或测试中引用 varshostvars 中的内容。显然,如果您愿意,可以通过交换测试函数参数的顺序来将顺序反转为 when: ansible_run_tags is my_when_test("zsh"),如果您觉得这样读起来更好(并且省去了 yaml 中外部 ' 的需要)