Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading