0

I have a python script which is returning / print two lists.

test.py

def getHosts():
        Pool1=[x.x.x.x, x.x.x.x]
        Pool2=[x.x.x.x, x.x.x.x]
        Print pool1,pool2
        Return pool1,pool2

getHosts()

My playbook looks like:

     -task:
      name: get the hosts
      command: /test.py
      register: result

Now, is it possible to fetch out the pool1 and pool2 seperately from the registered variable result ? If yes, please show me an example.

Any help or suggestions will be highly appreciated.

Shibankar
  • 806
  • 3
  • 16
  • 40

1 Answers1

5

Produce JSON and feed it to Ansible. It will automatically create an appropriate data structure:

---
- hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - command: 'echo { \"Pool1\": \"[x.x.x.x, x.x.x.x]\", \"Pool2\": \"[x.x.x.x, x.x.x.x]\" }'
      register: my_output
    - set_fact:
        my_variable: "{{ my_output.stdout | from_json }}"
    - debug:
        msg: "Pool1 is {{ my_variable.Pool1 }} and Pool2 is {{ my_variable.Pool2 }}"

Result:

ok: [localhost] => {
    "msg": "Pool1 is [x.x.x.x, x.x.x.x] and Pool2 is [x.x.x.x, x.x.x.x]"
}

Depending on how you later use the variable, you might/might not need to from_json filter (see this).

techraf
  • 64,883
  • 27
  • 193
  • 198