Score:2

Ansible: How to convert shell command output into items or variables

vn flag

I am running shell command in my playbook to extract the results of a command. The output of

- debug: msg="{{ dblist.stdout_lines }}"

is

ok: [host] => {
    "msg": [
"inst1:db1"
"inst1:db2"
"inst1:db3"
"inst2:db4"
"inst2:db3"
  ]
}

I need to store this value in a format that allows me to run my next playbook considering the value of item.0 as inst1 and item.1 as db2 and so on.

Currently

- debug: msg="{{ item.0 }} has  a value {{ item.1 }}"
  with_items: "{{ dblist.stdout_lines }}"

is giving values like

ok: [host] => (item=inst1:db1) => {
    "msg": "i has  a value n"
}
ok: [host] => (item=inst1:db2) => {
    "msg": "i has  a value n"

Thanks.

Score:3
br flag

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
Score:2
th flag

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(':') }}"
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.