title: How to check if lines exist in file using Ansible?
body: <p>I'm creating an Ansible role to create a user and install rbenv to run my Rails application.</p>
  
  <p>As part of the rbenv installation, you need to modify the PATH and add a line initializing rbenv shims to <code>.bash_profile</code>. I would like to make this role idempotent. Thus, I would like to check if the PATH and rbenv shim initializer are already present in <code>.bash_profile</code>.</p>
  
  <p>I have the following:</p>
  
  <pre><code>- name: Clone rbenv repo
    git: repo=https://github.com/rbenv/rbenv.git
      dest=/home/{{ rails_app_user }}/.rbenv
      force=yes
      update=no
  
  - name: Check if rbenv exists in PATH
    shell: grep 'export PATH="$HOME/.rbenv/bin:$PATH"' /home/{{ rails_app_user }}/.bash_profile
    register: rbenv_path_exists
  
  - name: Add rbenv to PATH
    shell: echo 'export PATH="$HOME/.rbenv/bin:$PATH"' &gt;&gt; /home/{{ rails_app_user }}/.bash_profile
    when: rbenv_path_exists.stdout_lines.count == 0
  
  - name: Check if rbenv shims are installed
    shell: grep 'eval "$(rbenv init -)"' /home/{{ rails_app_user }}/.bash_profile
    register: rbenv_shim_exists
  
  - name: Install rbenv shims
    shell: echo 'eval "$(rbenv init -)"' &gt;&gt; /home/{{ rails_app_user }}/.bash_profile
    when: rbenv_shim_exists.stdout_lines.count == 0
  </code></pre>
  
  <p>However, it seems that grep returns 1 when no match is found, causing Ansible to think a fatal error occurred, terminating the playbook. I tried appending <code>ignore_errors: yes</code> below the PATH and shims check. However, that seems to cause the variables to not be properly registered, causing the PATH and shim installation steps to be skipped due to the <code>when</code> clause.</p>
  
  <p>Output when using <code>ignore_errors: yes</code>: </p>
  
  <pre><code>TASK [rails : Check if rbenv exists in PATH] ***********************************
  fatal: [172.16.171.133]: FAILED! =&gt; {"changed": true, "cmd": "grep 'export PATH=\"$HOME/.rbenv/bin:$PATH\"' /home/app/.bash_profile", "delta": "0:00:00.005480", "end": "2016-01-30 04:08:01.971000", "failed": true, "rc": 1, "start": "2016-01-30 04:08:01.965520", "stderr": "", "stdout": "", "stdout_lines": [], "warnings": []}
  ...ignoring
  
  TASK [rails : Add rbenv to PATH] ***********************************************
  skipping: [172.16.171.133]
  </code></pre>
  
  <p>What would an idiomatic way to accomplish this?</p>