How to enforce the order of with_dict in Ansible?

16,235

Solution 1

I don't see an easy way to use dicts as they determine there order from the order of its hashed keys.
You can do the following:

with_dict_test:
  - { key: 'one', value: 1 }
  - { key: 'two', value: 2 }
  - { key: 'three', value: 3 }
  - { key: 'four', value: 4 }
  - { key: 'five', value: 5 }
  - { key: 'six', value: 6 }

and in the playbook just replace with_dict with with_items:

---
- name: with_dict test
  debug: msg="{{item.key}} --> {{item.value}}"
  with_items: with_dict_test

If you find this solution (the declaration of the variable) to ugly, you can do this:

key: ['one', 'two', 'three', 'four', 'five', 'six']
values: [1, 2, 3, 4, 5, 6]

and in the playbook

---
- name: with_dict test
  debug: msg="{{item.0}} --> {{item.1}}"
  with_together:
    - key
    - value

Solution 2

I'm not completely sure, but maybe this will help you along the way:

  - hosts: localhost
    vars:
      dict:
        one: 1
        two: 2
        three: 3
      sorted: "{{ dict|dictsort(false,'value') }}"

    tasks:
      - debug:
          var: sorted
      - debug:
          msg: "good {{item.1}}"
        with_items: sorted

I'm assuming you can use the Jinja filter to somehow sort on complex values. Another thing you might check out is combining dict.values()|list and with_sequence, but anything you milk out of that stone won't exactly scream "maintainable."

Share:
16,235

Related videos on Youtube

dokaspar
Author by

dokaspar

Updated on September 20, 2022

Comments

  • dokaspar
    dokaspar over 1 year

    I have dictionary-type of data that I want to iterate through and keeping the order is important:

    with_dict_test:
      one:   1
      two:   2
      three: 3
      four:  4
      five:  5
      six:   6
    

    Now when I write a task to print the keys and values, they are printed in seemingly random order (6, 3, 1, 4, 5, 2).

    ---
    - name: with_dict test
      debug: msg="{{item.key}} --> {{item.value}}"
      with_dict: with_dict_test
    

    How can I enforce Ansible to iterate in the given order? Or is there anything better suited than with_dict? I really need both the key and the value during task execution...

  • dokaspar
    dokaspar about 9 years
    Interesting approach. However, my example with_dict_test is just for illustration. In reality, I want the entries to be sorted by the given order in the file, neither sorted by the keys nor by the values...
  • nik.shornikov
    nik.shornikov about 9 years
    @dokaspar Sorry about that -- for some reason I assumed you had to deal with a dict (e.g. registered variable from another task)