我有一个名为test.py
这是:
#!/usr/bin/python
a = "A:2\nB:5"
print a
现在,在我的 Ansible 剧本中,我正在运行此脚本并使用此任务将输出注册到变量
- name: Create variable from the command
command: "python ./test.py"
register: command_output
我想将输出转换为字典Dict
在 ansible 中,以便在后续任务中我可以访问诸如Dict.A
or Dict.B
.
我尝试了所有存在的选项here https://stackoverflow.com/questions/35605603/using-ansible-set-fact-to-create-a-dictionary-from-register-results但没有一个为我工作。
在实现第一个答案时,这是我的剧本:
---
- 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 脚本。