Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible list of dicts - accessing keys after a list filter

Taking this playbook YAML:

---
- hosts: localhost
  become: false
  vars:
    list_of_dicts:
      - { key1: "cccc", key2: "dddd" }
      - { key1: "aaaa", key2: "bbbb" }
  tasks:
    - name: debug list
      debug:
        msg: "{{ list_of_dicts|sort(attribute='key1')|first }}"

How can I access the dict keys as a result of the filter chain? The filter produces a dict that looks like this:

ok: [localhost] => {
    "msg": {
        "key1": "aaaa",
        "key2": "bbbb"
    }
}

I just want to access key2 in the filter chain - I pictured something like ...|first.key2 but that infers first is an object which it isn't (and similarly fails for first['key2'])

like image 362
AndyC Avatar asked May 22 '17 09:05

AndyC


1 Answers

This is for sure a duplicate, but I can't find corresponding answer. I wish SO had a better search engine.

You can group expressions in Jinja2, like follows:

(list_of_dicts|sort(attribute='key1')|first).key2
like image 85
Konstantin Suvorov Avatar answered Sep 21 '22 11:09

Konstantin Suvorov