Create the below script for testing
shell> cat run.sh
#!/bin/sh
cat << EOM
1234223 /bin/ksh ./run.sh -f -i 1
4356223 /bin/ksh ./run.sh -f -i 2
887455 /bin/ksh ./run.sh -f -i 3
9934534 /bin/ksh ./run.sh -f -i 4
3245764 /bin/ksh ./run.sh -f -i 5
EOM
Run the script and register the output for testing
- script: run.sh
register: get_pid_and_name
Split the fields
arr: "{{ get_pid_and_name.stdout_lines|map('split') }}"
gives
arr:
- ['1234223', /bin/ksh, ./run.sh, -f, -i, '1']
- ['4356223', /bin/ksh, ./run.sh, -f, -i, '2']
- ['887455', /bin/ksh, ./run.sh, -f, -i, '3']
- ['9934534', /bin/ksh, ./run.sh, -f, -i, '4']
- ['3245764', /bin/ksh, ./run.sh, -f, -i, '5']
Create dictionary
pid_name: |
{% filter from_yaml %}
{% for i in arr %}
{{ i.0 }}: {{ i.1 }}
{% endfor %}
{% endfilter %}
gives
pid_name:
887455: /bin/ksh
1234223: /bin/ksh
3245764: /bin/ksh
4356223: /bin/ksh
9934534: /bin/ksh
Get the lists of PID and name
pids: "{{ pid_name.keys()|list }}"
names: "{{ pid_name.values()|list }}"
gives
pids: [1234223, 4356223, 887455, 9934534, 3245764]
names: [/bin/ksh, /bin/ksh, /bin/ksh, /bin/ksh, /bin/ksh]
Notes:
- There is plenty of other options on how to get the lists. For example,
pids: "{{ arr|map('first')|map('int')|list }}"
pids: "{{ arr|json_query('map(&[0], @)') }}"
names: "{{ arr|json_query('map(&[1], @)') }}"
- Example of a complete playbook for testing
- hosts: localhost
vars:
arr: "{{ get_pid_and_name.stdout_lines|map('split') }}"
pid_name: |
{% filter from_yaml %}
{% for i in arr %}
{{ i.0 }}: {{ i.1 }}
{% endfor %}
{% endfilter %}
pids: "{{ pid_name.keys()|list }}"
names: "{{ pid_name.values()|list }}"
tasks:
- script: run.sh
register: get_pid_and_name
- debug:
var: arr|to_yaml
- debug:
var: pid_name
- debug:
var: pids|to_yaml
- debug:
var: names|to_yaml