3
votes

I can't get my head around this, although it should be a trivial problem.

I'm using Ansible (and Jinja templating) to build a template and I have a list of dictionaries like (here displayed as JSON):

"datacenters": [{
    "description": "Main Datacenter", 
    "name": "main"
}, {
    "description": "Secondaty Datacenter", 
    "name": "secondary"
}]

And I want to filter by name an print the description. In my template I could get up to here:

{{ datacenters | selectattr("name", "equalto", "main") | list | first | to_nice_json }}

with output:

{
    "description": "Main Datacenter",
    "name": "main"           
}

But I can't get just description. For instance when I use:

{{ datacenters | selectattr("name", "equalto", "main") | list | first | attr("description") }}

I get:

AnsibleUndefinedVariable: 'unicode object' has no attribute 'description'

I have found this link https://github.com/ansible/ansible/issues/19356 googling the error, but I'm not loading the variable from the inventory. Any idea how to solve this?

2

2 Answers

3
votes

You can group pipe's result:

{{ (datacenters | selectattr("name", "equalto", "main") | list | first).description }}
0
votes

I made it working, but using a workaround, so anyone who can provide a one-line solution is much more welcome.

Here is the workaround. In the template I used a set like:

{% set temp = datacenters | selectattr("name", "equalto", "main") | list | first %}
{{ temp["description"] }}

Which works, but I don't see why it shouldn't work in one line using attr