selectattr with ansible

Hi,

I have a list like below, and I need to select the sequence which has “name” attribute equal to “lo0”. I use this selectattr statement {% set lo0 = interfaces|selectattr(“name”, “equalto”, lo0) | first%}

But while running the playbook throws me an error {‘msg’: “TemplateRuntimeError: no test named ‘equalto’”, ‘failed’: True}

interfaces:

  • name: lo0
    unit0:
    ip_primary: 1.1.1.1
    ip_secondary: 2.2.2.2
    unit1:
    ip_primary: 3.3.3.3
    ip_secondary: 4.4.4.4
  • name: xyz
    unit0:
    ip_primary: 9.9.9.9

Jinja2 version 2.7.3.

Any pointer what am I missing?

Vishal

I think the 'equalto' test is only available in the 2.8+ version of jinja2

Hmmm…

so if have to select the list based on the value one of its key, is it possible?

I am trying something like this:

{% for interfaces in interfaces if interfaces.name == “lo0” %}
{{ interfaces.unit0.ip_primary }}
{% endfor %}

But throws an error {‘msg’: “AnsibleUndefinedVariable: One or more undefined variables: ‘list object’ has no attribute ‘lo0’”, ‘failed’: True}

Any ideas?

Vishal

In your example, the loop variable is named identical to your list variable.

Try doing:

{% for interface in interfaces if interface.name == “lo0” %}
{{ interface.unit0.ip_primary }}
{% endfor %}

This works for me: