Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

jinja2 - Access filter's resulting object fields/properties/items oneliner in ansible

For example have following list of events:

    - id: 11
      message: "Something happened yet again."
    - id: 10
      message: "Oh no, Something happened again."
    - id: 8
      message: "Something happened."

I want to extract latest event id in one line/task. I haven't found the way to do so without using intermediate task for saving fist element of my list to variable. This sollution seems bulky. How can I separate field name from filter name? Is there any way to access field/property after 'first','last' filter. (Other filters that return dictionaries.)?

UPD: Well, my question's phrasing was too confusing. I just needed id of latest event. From Vladimir's answer:

    "{{ list|map(attribute='id')|max }}" 

is quite enough in my case. More so, as events already sorted by id(descending):

    "{{ list|first()['id] }} 

will do.

So to separate filter name from field name in ansible all is needed is a pair of brackets after filter name (I guesss because it's a python function after all).

question from:https://stackoverflow.com/questions/65836374/access-filters-resulting-object-fields-properties-items-oneliner-in-ansible

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Q: "id of the latest event"

A: The task

- debug:
    msg: "{{ l|map(attribute='id')|max }}"

gives

  msg: '11'

In addition to this, the oneliner task

- debug:
    msg: "{{ (l|items2dict(key_name='id', value_name='message'))[l|map(attribute='id')|max] }}"

gives the message of the latest id

  msg: Something happened yet again.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...