1

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'] }}"
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
spark
  • 531
  • 6
  • 17

1 Answers1

2

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
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • Thank you for the answer. I wanted to remove ' ' before something. TASK [set_fact] ************************************************************************************************************************************************************************* ok: [localhost] TASK [debug] **************************************************************************************************************************************************************************** ok: [localhost] => { "minio_list1['test']": " something" } – spark May 12 '22 at 11:55
  • 1
    @spark use an extra [`trim`](https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.trim) filter, then: `minio_list1['test'] | trim` – β.εηοιτ.βε May 12 '22 at 12:44