【发布时间】:2018-02-09 10:21:48
【问题描述】:
我有一个名为 test.py 的 Python 脚本:
#!/usr/bin/python
a = "A:2\nB:5"
print a
现在在我的 Ansible 剧本中,我正在运行此脚本并使用此任务将输出注册到变量
- name: Create variable from the command
command: "python ./test.py"
register: command_output
我想将输出转换为 ansible 中的字典 Dict,以便在后续任务中可以访问 Dict.A 或 Dict.B 等值。
我尝试了here 提供的所有选项,但没有一个对我有用。
在实现第一个答案时,这是我的剧本:
---
- hosts: localhost
gather_facts: no
become: yes
tasks:
- name: Create variable from command
command: "python ./test.py"
register: command_output
- name: set parameter values as fact
set_fact:
parameter: >
"{{ parameter | default({}) | combine ( { item.split(':')[0]: item.split(':')[1] } ) }}"
with_items: "{{command_output.stdout_lines}}"
- debug:
msg: "{{parameter}}"
为此,我收到错误:
TASK [set parameter values as fact] **************************************************************************************************************************************************************
ok: [localhost] => (item=A:2)
fatal: [localhost]: FAILED! => {"msg": "|combine expects dictionaries, got u'\"{u\\'A\\': u\\'2\\'}\"\\n'"}
第二个答案我写了这个脚本
---
- hosts: localhost
gather_facts: no
become: yes
tasks:
- name: Create variable from command
command: "python ./test.py"
register: command_output
- name: set parameter values as fact
set_fact:
parameter: >
{{
parameter | default({})|
combine(
dict([item.partition(':')[::2]|map('trim')])
)
}}
with_items: "{{command_output.stdout_lines}}"
- debug:
msg: "{{parameter.B}}"
在这种情况下,我收到此错误
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ dict([item.partition(':')[::2]|map('trim')]) }}): <lambda>() takes exactly 0 arguments (1 given)"}
我不知道如何将 python 脚本的输出转换为 Ansible 中的字典。我可以将输出作为列表、字符串或字典本身从 python 发送,但无论如何,它在 Ansible 中注册为字符串,之后,我无法将其转换回 Ansible 中的字典。
如果有任何其他方法可以实现这一点,请提供帮助。我正在考虑为此编写 ansible 模块,但即使在那里我也不确定 ansible 将如何处理模块的输出,因为本质上它也是一个 python 脚本。
【问题讨论】:
标签: python dictionary ansible ansible-2.x