Ansible pass dictionary from python script

ansible

I am running a Ansible script that calls a python script, which manipulates some data and turns it into a dictionary. I want to redirect the python dictionary to a register and then use it replace sections of a json file. My script fails without any messages. I can run the python script by itself and it prints out the dictionary.

What am I doing wrong?
Is this the best way to do this?
Is it better to use shell, command or script to call python scripts?

pyscript.py
pydict[pykey] = pyvalue
print (pydict)


ansiblescript.yml
---
- hosts: 10.215.237.238
  tasks:  

  - name : Gather info
    shell: '/usr/bin/python /home/devoper/scripts/pyscript.py'
    register: pydict


  - name: Insert Info
    replace:
      destfile: /home/devoper/scripts/template.json
      regexp: "KEY1"
      replace: "{{ pydict.pykey }}"
      backup: yes

Thank you for your time.

Best Answer

Registered Variables have its own key, which you can see if you execute ansible-playbook with -vvv option. You cannot store the dictionary into regitered variables directly.

It depends on what you need to achieve, but my suggestion would be as follows:

  1. Create custom ansible module.
  2. Execute custom module and store returned values.
  3. Use those values as a dictionary.

Create custom ansible module

ansiblescript.yml
|_library
|_customized_pyscript.py

#!/usr/bin/python

from ansible.module_utils.basic import *

def main():

    module = AnsibleModule(argument_spec={})
    pydict = {"key1": "result1"}
    module.exit_json(changed=False, meta=pydict)

if __name__ == '__main__':  
    main()

Execute custom module and store returned values

ansiblescript.yml

---
- hosts: 10.215.237.238
  tasks:
- name: Gather info
  customized_pyscript:
  register: pydict

Use those values as a dictionary

ansiblescript.yml

- name: Insert Info
  replace:
    destfile: /home/devoper/scripts/template.json
    regexp: "KEY1"
    replace: "{{ pydict.meta.KEY1 }}"
    backup: yes