Search code examples
ansibleansible-2.x

How can I check if a string exists in a file?


Is it possible to check if a string exists in a file using Ansible?

I want to check is a user has access to a server. This can be done on the server using cat /etc/passwd | grep username, but I want Ansible to stop if the user is not there.
I have tried to use the lineinfile but can't seem to get it to return.

- name: find
  lineinfile: 
    dest: /etc/passwd
    regexp: [user]
    state: present
    line: "user"

The code above adds user to the file if he is not there. All I want to do is check. I don't want to modify the file in any way, is this possible.


Solution

  • I'd probably register and evaluate a variable.

    The following simple playbook works for me:

    - hosts: localhost
      tasks:
    
      - name: read the passwd file
        shell: cat /etc/passwd
        register: user_accts
    
      - name: a task that only happens if the user exists
        when: user_accts.stdout.find('hillsy') != -1
        debug: msg="user hillsy exists"