0

The Ansible playbook code below works, but it relies on a shell out to egrep. I would like to know the "right way" to do this (using Ansible modules, Jinja2 filters, etc., but no external binaries) for my own personal growth.

I tried several things, but couldn't find a "native" solution that worked. (The less said about my attempts to use the ini filter, the better!)

  - 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 != ""
Beam Davis
  • 143
  • 1
  • 7
  • I guess the right way to check a variable against a list is `when: username in exclude_list`. Is the real question about how to go from some arbitrarily formatted and named file in an arbitrary location to an `exclude_list` variable? – Michał Politowski Apr 05 '19 at 11:43

1 Answers1

1

Does the play below do what you're looking for?

- 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)
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Not quite, but you pointed me in the right direction! `- lookup('file', exclude_file) is match(['[ \t]*',username,'[ \t]*']|join)` – Beam Davis Apr 08 '19 at 15:43