如何将字典列表从Python脚本导入Ansible playbook?

2024-03-29 13:00:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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脚本,然后将输出存储为变量(但这个解决方案对我来说有点笨拙)。在

谢谢。在


Tags: nametest脚本comidurlyml格式
1条回答
网友
1楼 · 发布于 2024-03-29 13:00:55

我建议使用查找插件pipe和将变量转储到json的python文件:

Python文件变量.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))

和剧本代码:

^{pr2}$

在使用之前不要忘记将文件上载到节点。在

用ansible 2.7.6测试

相关问题 更多 >