Ansible count number of lines in remote file

Viewed 1389

I would like to count the number of lines in a file with playbook, but the playbook should run remotely. It should be the equivalent of the linux command:

cat /etc/passwd |wc -l

Now I use this as workaround:

- name: Count number of users
  shell: 'cat /etc/passwd |wc -l'
  register: usercount

- name: Write the user count
  debug:
    msg: "{{ usercount.stdout }}"

but it will be nice if it should work with an Ansible builtin command.

1 Answers

Lookup of files execute on the controller, so, I would say that your best bet would be to slurp the files then count the lines.

So, with the string representation of the files, you can use the splitlines function of Python to end up with a list you can then feed to a simple length filter.

Here would be an example playbook:

- hosts: node1
  gather_facts: no

  tasks:
    - slurp:
        src: /etc/passwd
      register: passwd
    
    - debug:
        var: (passwd.content | b64decode).splitlines() | length

This would yield the recap:

PLAY [node1] ******************************************************************************************************

TASK [slurp] ******************************************************************************************************
ok: [node1]

TASK [debug] ******************************************************************************************************
ok: [node1] => 
  (passwd.content | b64decode).splitlines() | length: '27'

PLAY RECAP ********************************************************************************************************
node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
Related