How to enforce with_dict order in Ansible?

I have a dictionary data type that I want to iterate over and maintain order:

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

Now, when I write a task for printing keys and values, they are printed in 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 force Ansible to iterate in this order? Or is there something better than with_dict ? I really need both the key and the value during the execution of the task ...

+6
source share
2 answers

I do not see a simple way to use dicts, since they determine the order there from the order of the 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 tutorial, 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 (variable declaration) ugly, you can do this:

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

and in the textbook

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

I'm not quite sure, but maybe this will help you with this:

  - 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 assume you can use the Jinja filter to sort by complex values ​​in some way. Another thing you can check out is a combination of dict.values()|list and with_sequence , but all that you milk from this stone will definitely not scream “supported”.

+2
source

Source: https://habr.com/ru/post/982214/


All Articles