Skip to content

Commit

Permalink
Add documentation on dict2items (ansible#38375)
Browse files Browse the repository at this point in the history
dict2items is worth mentioning in the filters and loops pages
(the latter as it's useful to replace `with_dict`)

Update some nearby broken links
  • Loading branch information
willthames authored and dharmabumstead committed Apr 7, 2018
1 parent 785964e commit a8953fc
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
25 changes: 25 additions & 0 deletions docs/docsite/rst/user_guide/playbooks_filters.rst
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,31 @@ To get the symmetric difference of 2 lists (items exclusive to each list)::
{{ list1 | symmetric_difference(list2) }}


.. _dict_filter:

Dict Filter
```````````

.. versionadded:: 2.6


To turn a dictionary into a list of items, suitable for looping, use `dict2items`::

{{ dict | dict2items }}

Which turns::

tags:
Application: payment
Environment: dev

into::

- key: Application
value: payment
- key: Environment
value: dev

.. _random_filter:

Random Number Filter
Expand Down
17 changes: 16 additions & 1 deletion docs/docsite/rst/user_guide/playbooks_loops.rst
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,24 @@ If you have a list of hashes, you can reference subkeys using things like::
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }

Also be aware that when combining :ref:`when: playbooks_conditionals` with a loop, the ``when:`` statement is processed separately for each item.
Also be aware that when combining :doc:`playbooks_conditionals` with a loop, the ``when:`` statement is processed separately for each item.
See :ref:`the_when_statement` for an example.

To loop over a dict, use the ``dict2items`` :ref:`dict_filter`::

- name: create a tag dictionary of non-empty tags
set_fact:
tags_dict: "{{ (tags_dict|default({}))|combine({item.key: item.value}) }}"
with_items: "{{ tags|dict2items }}"
vars:
tags:
Environment: dev
Application: payment
Another: "{{ doesnotexist|default() }}"
when: item.value != ""

Here, we don't want to set empty tags, so we create a dictionary containing only non-empty tags.


.. _complex_loops:

Expand Down

0 comments on commit a8953fc

Please sign in to comment.