Search code examples
ansiblejinja2

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

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