How to convert a string to dict in Ansible?

I want to convert the simple output of python, and I tried to follow the post here.
But it doesn't seem to work in my sample code. data is a string coming from the output of a shell task.

How do I make minio_list1['test'] legitimate?

---
- name: data test hosts: localhost vars: data: "test: something" tasks: - name: get the list set_fact: minio_list1: "{{ minio_list1 | default({}) | combine ( { item.split(':')[0]: item.split(':')[1] } ) }}" with_items: - data - name: print debug: msg: "{{ minio_list1 }}" - name: print debug: msg: "{{ minio_list1['test'] }}"

1 Answer

Since test: something is a valid YAML snippet, why not using the YAML capabilities of Ansible, and so the filter from_yaml?

Given the playbook:

- hosts: localhost gather_facts: no vars: data: "test: something" tasks: - set_fact: minio_list1: "{{ data | from_yaml }}" - debug: var: minio_list1['test'] # or minio_list1.test

This yields:

TASK [set_fact] *************************************************************
ok: [localhost]
TASK [debug] ****************************************************************
ok: [localhost] => minio_list1['test']: something
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like