I’m faced with a corner case where some devices are expected to return a list of dictionaries but instead return a single dictionary. This creates an error later on in ansible when a list is expected.
For instance, the device returns the file:
var:
key_1: value_11
key_2: value_21
key_3: value_31
instead of for instance:
var:
key_1: value_11
key_2: value_21
key_3: value_31
key_1: value_12
key_2: value_22
key_3: value_32
…
So the goal is to transform the first var into:
var:
key_1: value_11
key_2: value_21
key_3: value_31
AFAIK, there is no ansible filters to accomplish that; for instance, ‘list’ does not give the expected result.
Also, we cannot count on the name or number of keys as they may change.
I suppose the solution may revolve around something like that:
set_fact:
list_var: >-
{% for key, value in var.items() %}
{{ [{key: value}] }}
{% endfor %}
when: >
(var | type_debug != ‘list’)
This works, but if the original var is already a list, you get a list
of a list, which is probably not what the OP wants.
In cases like this I tend to use the "to_array" function of jmespath: