1

New to Ansible. There has to be a simpler way to do this: I need to issue a command (e.g. ps), and go through the return elements one by one, skipping the first element which has the column headings (e.g. PID, etc. in this case). I am only interested in the process names, not the other column values.

What's the easiest way of doing this? Below is my approach (which may not be the best way). I finally whittled down the list to omit the first element. Do I read into a separate array, loop through each item, and use awk or sed to filter on the process name?

  name: Get process
  hosts: localhost

  tasks:
    - name: Get process
      command: "ps"
      register: ps_output

    - name: Set list length
      set_fact:
        array_end_index: "{{ ps_output.stdout_lines | length - 1 }}"
      
    - name: List all but last item
      debug: 
        msg: "{{ ps_output.stdout_lines[item] }}"
      loop: "{{ range(1, (array_end_index | int)) | list }}"
dan_linder
  • 881
  • 1
  • 9
  • 30
TCJR
  • 39
  • 2
  • I'd bet the [`ps_output.stdout_lines | reject("match", ...)` filter](https://jinja.palletsprojects.com/en/2.11.x/templates/#reject) (with that ["match"](https://docs.ansible.com/ansible/2.10/user_guide/playbooks_tests.html#testing-strings) bit being the test having that name) will get you pretty close – mdaniel Apr 18 '21 at 01:10

1 Answers1

0

Your text says to skip the "first element which has the column headings", but when I run your example it skips the first AND last lines. Not sure which you want, but since you already have a list in the ps_output.stdout_lines variable, so use the Python slice notation to return entries to easily remove from either or both ends of the list. (Note that the list is a zero-indexed list.)

To drop both the first and last list entries:

- name: Get process
  hosts: localhost

  tasks:
    - name: Get process
      command: "ps"
      register: ps_output

    - name: List all but last item
      debug: 
        msg: "{{ item }}"
      loop: "{{ ps_output.stdout_lines[1:-1] }}"

If you just want to drop the first line, change the loop: slice to [1:]. If you want to drop just the last line, use [:-1].

See Understanding Slice Notation for more information.

dan_linder
  • 881
  • 1
  • 9
  • 30