From a8953fcac4ee8c1978f6f3592345c7d163cde5ee Mon Sep 17 00:00:00 2001 From: Will Thames Date: Sat, 7 Apr 2018 19:13:19 +1000 Subject: [PATCH] Add documentation on dict2items (#38375) 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 --- .../rst/user_guide/playbooks_filters.rst | 25 +++++++++++++++++++ .../rst/user_guide/playbooks_loops.rst | 17 ++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/docs/docsite/rst/user_guide/playbooks_filters.rst b/docs/docsite/rst/user_guide/playbooks_filters.rst index a4ea6217c92..e28bfce0d39 100644 --- a/docs/docsite/rst/user_guide/playbooks_filters.rst +++ b/docs/docsite/rst/user_guide/playbooks_filters.rst @@ -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 diff --git a/docs/docsite/rst/user_guide/playbooks_loops.rst b/docs/docsite/rst/user_guide/playbooks_loops.rst index 9d21733ff71..5f88fbf7d5f 100644 --- a/docs/docsite/rst/user_guide/playbooks_loops.rst +++ b/docs/docsite/rst/user_guide/playbooks_loops.rst @@ -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: