4

Is there a way to output only the last five lines of an Ansible shell output, for example?
Maybe using loops?

Example:

  - name: Running Migrations
    ansible.builtin.shell: /some-script-produces-lot-of-output.sh
    register: ps
  - debug: var=ps.stdout_lines

The debug task should only output the last five lines.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83

1 Answers1

4

You can use Python's slicing notation for this:

- debug: 
    var: ps.stdout_lines[-5:]

Will output the 5 lines from the end of the list (hence the negative value) up until the end of the list.


Given the tasks

- shell: |-
    for idx in $(seq 1 10)
    do
      printf "line%d\n" "${idx}"
    done
  register: ps

- debug:
    var: ps.stdout_lines[-5:]

This yields:

TASK [shell] ******************************************************
changed: [localhost]

TASK [debug] ******************************************************
ok: [localhost] => 
  ps.stdout_lines[-5:]:
  - line6
  - line7
  - line8
  - line9
  - line10
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83