简体   繁体   中英

How do I import List of dictionaries from Python script into Ansible playbook?

I have a python variable that is defined in a seperate python script formatted like so -

site_list = [   {'name': "MyTestSite",
                 'alias': 'site1',
                 'website_url':  ['website1.test.com' ,'website1.othertest.com'],
                 'projectname':'Testsite',
                 'id':'12345678'},

                {'name': '"OtherTestSite"',
                 'alias': 'foobar',
                 'website_url':  ['foobar.test.com' ,'foobar2.test.com'],
                 'projectname':'foobar',
                 'id':'98765432'},

                 ... (lots of other entries)

I'm looking to try get the variable into Ansible and use it there, however it seems like I would have to rewrite the variable to be in a .yml format (based on https://docs.ansible.com/ansible/latest/modules/include_vars_module.html ), rather than be able to just import the python script and use it from there.

Is it possible to just import the python variable as it is, rather than rewriting it using yml and putting it into the group_vars in the Ansible directory?

The only other way I could see retreiving that variable would be to print it inside of the Python script, call the Python script from Ansible, and then store the output as a variable (but that solution seems kinda clunky to me).

Thanks.

I suggest using lookup plugin pipe and python file that dump variable to json:

Python file vars.py:


import json

initial = [{'name': "MyTestSite",
                 'alias': 'site1',
                 'website_url':  ['website1.test.com' ,'website1.othertest.com'],
                 'projectname':'Testsite',
                 'id':'12345678'},

                {'name': '"OtherTestSite"',
                 'alias': 'foobar',
                 'website_url':  ['foobar.test.com' ,'foobar2.test.com'],
                 'projectname':'foobar',
                 'id':'98765432'}]


print(json.dumps(initial))

And playbook code:

---
- name: Test command
  hosts: localhost
  tasks:
  - name: Load variable to fact
    set_fact:
      the_var: "{{ lookup('pipe', 'python vars.py') | from_json }}"
  - name: Test command
    debug:
      msg: "{{ item }}"
    with_list: "{{ the_var }}"

Don't forget upload file to nodes before use it.

Tested with ansible 2.7.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM