Skip to content




Check if a line is present in a file

Use this recipe in a molecule verify playbook to check if a certain line is present or absent in a file. Keep state:absent and work with the failed_when option using a not, when the should not be present.

- name: "Ensure /tmp/my.conf contains"
    path: /tmp/my.conf
    regexp: '^127\.0\.0\.1.*whatever'
    state: absent
  check_mode: yes
  register: out
  changed_when: false
  # failed_when: not out.found

- debug:
    msg: "Yes, line exists."
  when: out.found

- debug:
    msg: "Line does NOT exist."
  when: not out.found

See this stackoverflow post for a discussion.

Last update: October 9, 2023