Using grep commands in Ansible tasks

Grep command is used on Linux/Unix to search for a particular pattern in a list of files. There is no Ansible grep module, but you can use the grep commands along with shell module or command module. We can store the results of the task and use it in various conditional statements, print them or use them for debugging purposes.

Let’s see some examples of using grep commands in Ansible shell and command modules.

Searching for a pattern recursively

I am trying to search all the files for the pattern ‘pattern’. The grep command I am using is ‘grep -ir pattern *’.

The following task will first witch to the path mentioned in ‘chdir’ argument. Then it will run the grep command. All the resulting files will be stored in the grep_output variable. In the next task, I am displaying the output.

- hosts: all
  tasks:
  - name: Ansible grep pattern basic example
    shell: "grep -ir 'Pattern' *"
    args:
      chdir: "/Users/mdtutorials2/Documents/Ansible"
    register: grep_output

  - debug:
      var: grep_output.stdout_lines

The following is given as output.

ok: [localhost] => {
    "grep_output.stdout_lines": [
        "check.txt:Pattern", 
        "check.txt:Pattern2", 
        "check.txt:Pattern3", 
        "variable1.txt:Pattern4"
    ]
}

But what happens if the pattern could not be found. Ansible will throw an error like below.

fatal: [localhost]: FAILED! => {“changed”: true, “cmd”: “grep -ir ‘nvalid_pattern’ *.txt”, “delta”: “0:00:00.007076”, “end”: “2017-09-29 12:51:36.300249”, “failed”: true, “rc”: 1, “start”: “2017-09-29 12:51:36.293173”, “stderr”: “”, “stderr_lines”: [], “stdout”: “”, “stdout_lines”: []}

So to suppress this error, we need to use ignore_errors with the first task. And we also need the second task to run only when the first task has some output. So execute the second task only if the register variable is not empty.

- hosts: all
  tasks:
  - name: Ansible grep pattern with ignore_errors example
    shell: "grep -ir 'pattern' *.txt"
    args:
      chdir: "/Users/mdtutorials2/Documents/Ansible"
    register: grep_output
    ignore_errors: true

  - debug:
      var: grep_output.stdout_lines
    when: grep_output.stdout != "