Converting output of Python script to dict in Ansible

梦想与她 提交于 2019-12-23 04:48:36

问题


I have a Python script called test.py which is:

#!/usr/bin/python
a = "A:2\nB:5"
print a

Now in my Ansible playbook, I am running this script and registering the output to a variable using this task

- name: Create variable from the command
  command: "python ./test.py"
  register: command_output

I want to convert the output to a dictionary Dict in ansible so that in subsequent tasks I can access values like Dict.A or Dict.B.

I tried all the options present here but none are working for me.

While implementing the first answer this is my playbook:

---
- 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}}"

For this, I am getting error:

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'"}

For second answer I wrote this script

---
- 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}}"

In this case, I am getting this error

fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ dict([item.partition(':')[::2]|map('trim')]) }}): <lambda>() takes exactly 0 arguments (1 given)"}

I am clueless what I can do to convert the output of my python script to a dictionary in Ansible. I can send the output as the list, string or dictionary itself from python but in any case, it registers as a string in Ansible and after that, I am not able to convert it back to the dictionary in Ansible.

If there is any other way to implement this please help. I am thinking about writing ansible module for this but even there I am not sure how will ansible handle the output of module as in essence that is also a python script.


回答1:


Explanation

This is a problem with YAML interpretation. You explicitly define a string with " following block scalar definition > which means after the first iteration parameter variable is defined as string.

Then the second iteration fails, because you pass that string to the combine filter (instead of a dictionary, which it expects).


Solution

Either write this in a single line instead of using YAML block scalar definition (>):

parameter: "{{ parameter | default({}) | combine ( { item.split(':')[0]: item.split(':')[1] } ) }}"

Or remove the quotation marks:

parameter: >
  {{ parameter | default({}) | combine ( { item.split(':')[0]: item.split(':')[1] } ) }}

The output:

TASK [Create variable from the command] *************************************************************************************
changed: [localhost]

TASK [set parameter values as fact] *****************************************************************************************
ok: [localhost] => (item=A:2)
ok: [localhost] => (item=B:5)

TASK [debug] ****************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "A": "2",
        "B": "5"
    }
}


来源:https://stackoverflow.com/questions/48703650/converting-output-of-python-script-to-dict-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!