python - 如何将 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 脚本,然后将输出存储为变量(但该解决方案对我来说似乎有点笨拙)。
谢谢。
解决方案
我建议使用将变量转储到 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 测试
推荐阅读
- node.js - MongoDB如何对数组进行排序
符合我的要求吗? - c# - 错误:与 C# 代码中先前错误相关的符号位置
- regex - 删除记事本++中特定列中的特定千位分隔符
- ios - 在呈现键盘时将特定视图绑定到屏幕顶部
- javascript - 如何使用 Chakra-UI 将 API 信息排序到网格中
- java - Spark:从 http 响应的结果中读取 sparkSession
- python - 提醒命令问题
- python - 将字符串的 CLA 传递到 Docker 映像中 - Python
- python - 如果在列表的一个实例中缺少 xpath 时忽略它的条件
- python - 通过 curl 向烧瓶发送文件,烧瓶在 request.files 中没有显示 FileStorage 对象