Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show last X output lines

Tags:

ansible

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.

like image 399
user2115050 Avatar asked Aug 31 '25 01:08

user2115050


1 Answers

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
like image 51
β.εηοιτ.βε Avatar answered Sep 02 '25 21:09

β.εηοιτ.βε