Ansible: How to convert shell command output into items or variables
Solution 1:
For example
- debug:
msg: "{{ _key }} has a value {{ _val }}"
loop: "{{ dblist.stdout_lines }}"
vars:
_arr: "{{ item.split(':') }}"
_key: "{{ _arr.0 }}"
_val: "{{ _arr.1 }}"
gives
msg: inst1 has a value db1
msg: inst1 has a value db2
msg: inst1 has a value db3
msg: inst2 has a value db4
msg: inst2 has a value db3
Solution 2:
If you're on a new enough version (ansible-core>=2.11), you can use the split
filter:
- debug:
msg: "{{ item.0 }} has a value {{ item.1 }}"
loop: "{{ dblist.stdout_lines | map('split', ':') }}"
It's possible to achieve a similar result on older versions, but it's uglier:
- debug:
msg: "{{ item.0 }} has a value {{ item.1 }}"
loop: "{{ dblist.stdout_lines }}"
loop_control:
loop_var: _item
vars:
item: "{{ _item.split(':') }}"