首页 > 解决方案 > 如何将 Python 脚本中的字典列表导入 Ansible 剧本?

问题描述

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

谢谢。

标签: pythonansible

解决方案


我建议使用将变量转储到 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 测试


推荐阅读