根据Ansible中的列表检查变量的“正确方法”

时间:2019-04-05 09:22:12

标签: ansible ansible-2.x

下面的Ansible剧本代码可以工作,但是它依赖于egrep的外壳。我想知道为自己的个人成长做这件事的“正确方法”(使用Ansible模块,Jinja2过滤器等,但没有外部二进制文件)。

我尝试了几种方法,但是找不到有效的“本地”解决方案。 (关于我尝试使用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 != ""

1 个答案:

答案 0 :(得分:1)

下面的戏是否正在寻找您想要的?

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