Browse code

complex data example using value and default from list of dicts (#73937)

Brian Coca authored on 2021/03/19 04:31:33
Showing 1 changed files
... ...
@@ -122,6 +122,7 @@ In this case, we want to find the mount point for a given path across our machin
122 122
         msg: "{{(ansible_facts.mounts | selectattr('mount', 'in', path) | list | sort(attribute='mount'))[-1]['mount']}}"
123 123
 
124 124
 
125
+.. _omit_elements_from_list:
125 126
 
126 127
 Omit elements from a list
127 128
 -------------------------
... ...
@@ -158,6 +159,30 @@ Another way is to avoid adding elements to the list in the first place, so you c
158 158
           - "bar"
159 159
 
160 160
 
161
+
162
+.. _combine_optional_values:
163
+
164
+Combine values from same list of dicts
165
+---------------------------------------
166
+Combining positive and negative filters from examples above, you can get a 'value when it exists' and a 'fallback' when it doesn't.
167
+
168
+.. code-block:: YAML+Jinja
169
+ :caption: Use selectattr and rejectattr to get the ansible_host or inventory_hostname as needed
170
+
171
+    - hosts: localhost
172
+      tasks:
173
+        - name: Check hosts in inventory that respond to ssh port
174
+          wait_for:
175
+            host: "{{ item }}"
176
+            port: 22
177
+          loop: '{{ has_ah + no_ah }}'
178
+          vars:
179
+            has_ah: '{{ hostvars|dictsort|selectattr("1.ansible_host", "defined")|map(attribute="1.ansible_host")|list }}'
180
+            no_ah: '{{ hostvars|dictsort|rejectattr("1.ansible_host", "defined")|map(attribute="0")|list }}'
181
+
182
+
183
+.. _custom_fileglob_variable:
184
+
161 185
 Custom Fileglob Based on a Variable
162 186
 -----------------------------------
163 187