"right way" 根据 Ansible 中的列表检查变量

The "right way" to check a variable against a list in Ansible

下面的 Ansible 剧本代码有效,但它依赖于 shell 输出到 egrep。我想知道 "right way" 为我自己的个人成长做这件事(使用 Ansible 模块、Jinja2 过滤器等,但没有外部二进制文件)。

我尝试了几种方法,但找不到 "native" 有效的解决方案。 (关于我尝试使用 ini 过滤器的说法越少越好!)

  - name: "Check for {{exclude_file}}"
    stat:
          path: "{{playbook_dir}}/{{exclude_file}}"
          follow: yes
    register: exclude_file_stat
    delegate_to: localhost

  - name: "Check if {{username}} is in {{exclude_file}} (if exists)"
    shell: "egrep '^[ \t]*{{username}}[ \t]*$' {{playbook_dir}}/{{exclude_file}} || true"
    changed_when: false
    register: exclude_file_egrep
    delegate_to: localhost
    when: exclude_file_stat.stat.exists == true

  - name: "Fail if {{exclude_file}} exists and {{username}} found"
    fail:
          msg: "{{username}} found in {{exclude_file}}"
    when: exclude_file_stat.stat.exists == true and exclude_file_egrep.stdout != ""

下面的剧本符合您的要求吗?

- name: "Fail if {{ exclude_file }} exists and {{ username }} found"
  fail:
    msg: "{{ username }} found in {{ exclude_file }}"
  when:
    - exclude_file is exists
    - lookup('file', exclude_file) is search(username)