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...
Ansible's syntax also supports the idea of nested looping. Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task.
To use this loop in task you essentially need to add 3 arguments to your task arguments: until - condition that must be met for loop to stop. That is Ansible will continue executing the task until expression used here evaluates to true. retry - specifies how many times we want to run the task before Ansible gives up.
The loop keyword was recently added to Ansible 2.5. The loop keyword is usually used to create simple and standard loops that iterate through several items. The with_* keyword is used with a number of lookup plugins when iterating through values.
What is Ansible with_items? The Ansible with_items is a handy plugin to perform loop operations in a playbook. The plugin accepts items and then passes them to the calling module. For example, you can pass a list of packages to install and then give each item in the list to the install task.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With