Reputation: 123
I am using ansible to parse a jinja2 template. The jinja2 template has a piece of code which should iterate over a variable which is a list of dicts. However it is treating the list of dict as string and printing the individual characters. Please note the variable is set_fact in the ansible playbook.
Code to loop on the list of dicts in the j2 template:
{% for subscriber in subscribers %}
{% for dict_item in subscriber['filter_policy'] %}
{{dict_item.name}}
{% endfor %}
{% endfor %}
Variable as output in the debug module of ansible:
subscribers": [
{
"filter_policy": "[ { \"name\": \"Severity\", \"type\": \"CommaDelimitedList\", \"value\": \"critical\" }, { \"name\": \"Environment\", \"type\": \"CommaDelimitedList\", \"value\": \"nonprod\" }]",
"id": "[email protected]"
}
]
Ansible gives me an error saying: "msg": "AnsibleUndefinedVariable: 'str object' has no attribute 'name'"
However if I use set in the jinja2 template to assign the same value to the variable and use for loop over it, it works fine.
{% set policies = [{"name": "Severity","type": "CommaDelimitedList","value": "critical"},{"name": "Environment","type": "CommaDelimitedList","value": "nonprod"}] %}
I have no clue, how to resolve it.
ansible 2.7.2
python version = 3.7.3 (default, Mar 27 2019, 09:23:39) [Clang 10.0.0 (clang-1000.11.45.5)]
Upvotes: 0
Views: 5093
Reputation: 44615
Your filter_policy
variable effectively contains a string which happens to be a json representation of a list of dicts. You just have to decode that json string to an effective list of dicts with the from_json
filter
{% for subscriber in subscribers %}
{% for dict_item in (subscriber['filter_policy'] | from_json) %}
{{dict_item.name}}
{% endfor %}
{% endfor %}
Upvotes: 2