Search code examples
ansibleansible-tower

Use list of dictionaries variable on Ansible Tower textare survey


I'm trying to develop a playbook were I have the following variable.

disk_vars:
 - { Unit: C, Size: 50 }
 - { Unit: D, Size: 50 }

With the variables defined on the playbook there is no problem but when I try to use a texarea survey on Ansible Tower I cannot manage to parse them as list of dictionaries.

I tried adding to the survey the following two lines which are already on yaml format.

 - { Unit: C, Size: 50 }
 - { Unit: D, Size: 50 }

And on my vars section I use test_var: "{{ test_var1.split('\n') }} which converts the output into a two line string. Without the split is just a single line string.

I could make my playbook work with a simple dictionary like

dict1: {{ Unit: C, Size: 50 }} 

but I'm having issues parsing it as well.

EDIT

Changing it to the following as suggested by mdaniels works.

- set_fact:
   test_var: "{{ test_var1 | from_yaml }}"
- name: test
 debug: msg=" hostname is {{ item.Unit }} and {{ item.Size }}"
 with_items:
  - "{{ test_var }}"   

I'm trying to figure a way to clear-up the data input as asking users to respect the format is not a very good idea.

tried changing the input date to the following but I could not figure out how to format that into a list of dictionaries.

disk_vars:
 Unit: C, Size: 50
 Unit: D, Size: 50

I tried with the following piece of code

- set_fact:
db_list: >-
  {{ test_var1.split("\n") | select | 
     map("regex_replace", "^", "- {") | 
     map("regex_replace", "$", "}") | 
     join("\n") }}

But is putting it all on a single line.

"db_list": "- {dbid: 1, dbname: abc\ndbid: 2, dbname: xyz} "

I have tried to play with it but could not manage to make it work.


Solution

  • I believe you were very close; instead of "{{ test_var1.split('\n') }}" I believe you can just feed it to the from_yaml filter:

    - set_fact:
         test_var1: '{{ test_var1 | from_yaml }}'
      # this is just to simulate the **str** that you will receive from the textarea
      vars:
         test_var1: "- { Unit: C, Size: 50 }\n- { Unit: D, Size: 50 }\n"
    - debug:
         msg: and now test_var1[0].Unit is {{ test_var1[0].Unit }}