Ansible模板中如何使用Jinja2检查列表是否为空(附示例)
Let's break down what's going wrong here and fix it:
Your current approach uses trim|length on the studInfo list, but that's the root of the issue. The trim filter is designed for strings—it removes leading/trailing whitespace from text. When you apply it to a list, Jinja2 converts the list to a string first:
- An empty list
[]becomes the string"[]", which after trimming is still"[]"—solengthreturns 2 instead of 0. - A non-empty list like
[{'name':'John','id':'123'},{'name':'Jack','id':'112'}]gets converted to a longer string, andtrimdoes nothing useful here either.
The Fix: Use length Directly on the List
Jinja2's length filter works natively on lists—it returns the number of elements, including 0 for empty lists. Just remove the trim filter entirely:
list length is {{ item.studInfo | length }}
This will give you exactly what you want:
- For Jack's entry (empty
studInfo), it outputslist length is 0 - For Aaron's entry (2 elements in
studInfo), it outputslist length is 2
Bonus: Adding Empty List Checks (If Needed)
If you want to add custom messaging for empty lists, you can use a Jinja2 conditional:
{% if item.studInfo | length == 0 %} list length is 0 (no student info available) {% else %} list length is {{ item.studInfo | length }} {% endif %}
Or use the ternary filter for a more concise one-liner:
list length is {{ item.studInfo | length | ternary(item.studInfo | length, "0 (empty)") }}
Your Ansible playbook loop configuration is already correct—no changes needed there.
内容的提问来源于stack exchange,提问作者josh

