[英]How do I import List of dictionaries from Python script into Ansible playbook?
我有一个在单独的python脚本中定义的python变量,其格式如下:
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)
我正在尝试将变量放入Ansible并在其中使用它,但是似乎我必须将变量重写为.yml格式(基于https://docs.ansible.com/ansible/latest /modules/include_vars_module.html ),而不是只能导入python脚本并从那里使用它。
是否可以按原样导入python变量,而不是使用yml重写并将其放入Ansible目录中的group_vars中?
我能看到的唯一的其他方法是将该变量打印到Python脚本内,从Ansible调用Python脚本,然后将输出存储为变量(但是这种解决方案在我看来有点笨拙)。
谢谢。
我建议使用将变量转储到json的查找插件管道和python文件:
Python文件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))
和剧本代码:
---
- 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 }}"
使用文件之前,请不要忘记将文件上传到节点。
经过ansible 2.7.6测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.