Jinja2 extract single value for key/value pair without looping

I have the following defined in vars or defaults:

fusemq_authentication:

  • { ‘username’:‘admin’, 'password’:‘blah’, ‘groups’:‘admin’ }
  • { ‘username’:‘LOGSTASH’, 'password’:‘bing’, ‘groups’:‘LOGSTASH’ }

I want to know the password for LOGSTASH in a template. Today I loop until I find it. Is there a simpler way?

{% for value in fusemq_authentication %}
{% if value.username==“LOGSTASH” %}
fuseMQ_password={{ value.password }}
{% endif %}
{% endfor %}

You could transform your data definition like this: Then in a template you could access the password for ‘logstash’ user like this: or

jepper <jespmark@gmail.com> napisał:

I have the following defined in vars or defaults:

fusemq_authentication:
- { 'username':'admin', 'password’:'blah', 'groups':'admin'
}
- { 'username':'LOGSTASH', 'password’:'bing', 'groups':'LOGSTASH' }

This should be a dictionary

I want to know the password for LOGSTASH in a template. Today I loop
until
I find it. Is there a simpler way?

{% for value in fusemq_authentication %}
{% if value.username=="LOGSTASH" %}
fuseMQ_password={{ value.password }}
{% endif %}
{% endfor %}

Yes, with fusemq_authentication as a dict it would be:
    fuseMQ_password={{ fusemq_authentication. LOGSTASH.password }}

I’ve hit this before,

The problem is, sometimes it’s nice to have a list to loop over especially if the client code doesn’t know the keys.
Other times it would be nice to have a dict if you have the key since writing loops can be messy.

I think it would be very nice in these cases to have a dict_to_list adapter and list_to_dict adapter as jinja2 plugins, so the original datastructure can be whichever.

I got started on this but never finished.
https://gist.github.com/7a2109be1f0006bae89a.git

​You can already easily use a dict as a list:

dict.keys()
dict.values()
dict.items()

Theoretically in Jinja 2.8 when it's released you could perform this operation with something like this:

{{ fusemq_auth|selectattr('username','equalto','LOGSTASH')|map(attribute='password')|first }}

selectattr and map are new to version 2.7. The 'equalto' test is the problem you'll run in to.

So the map function with an optional selectattr provides the dict_to_list function you are looking for. (Your gist wouldn't load.) I don't see how a general purpose list_to_dict would be possible without some specific logic be written.

<tim/>