more set/list stuff

This commit is contained in:
Brian Coca 2017-02-23 16:32:43 -05:00 committed by Brian Coca
parent 4ba131d442
commit bfb3467d52
2 changed files with 56 additions and 1 deletions

View file

@ -609,6 +609,41 @@ To get date object from string use the `to_datetime` filter, (new in version in
# get amount of seconds between two dates, default date format is %Y-%d-%m %H:%M:%S but you can pass your own one
{{ (("2016-08-04 20:00:12"|to_datetime) - ("2015-10-06"|to_datetime('%Y-%d-%m'))).seconds }}
Combination Filters
````````````````````
.. versionadded:: 2.3
This set of filters returns a list of combined lists.
To get permutations of a list::
- name: give me largest permutations (order matters)
debug: msg="{{ [1,2,3,4,5]|permutations|list }}"
- name: give me permutations of sets of 3
debug: msg="{{ [1,2,3,4,5]|permutations(3)|list }}"
Combinations always require a set size::
- name: give me combinations for sets of 2
debug: msg="{{ [1,2,3,4,5]|combinations(2)|list }}"
To get a list combining the elements of other lists use ``zip``::
- name: give me list combo of 2 lists
debug: msg="{{ [1,2,3,4,5]|zip(['a','b','c','d','e','f'])|list }}"
- name: give me shortest combo of 2 lists
debug: msg="{{ [1,2,3]|zip(['a','b','c','d','e','f'])|list }}"
To always exhaust all list use ``zip_longest``::
- name: give me longest combo of 3 lists , fill with X
debug: msg="{{ [1,2,3]|zip_longest(['a','b','c','d','e','f'], [21, 22, 23], fillvalue='X')|list }}"
Debugging Filters
`````````````````

View file

@ -22,9 +22,12 @@ __metaclass__ = type
import math
import collections
import itertools
from ansible import errors
from ansible.module_utils import basic
def unique(a):
if isinstance(a,collections.Hashable):
c = set(a)
@ -117,7 +120,7 @@ class FilterModule(object):
''' Ansible math jinja2 filters '''
def filters(self):
return {
filters = {
# general math
'min' : min,
'max' : max,
@ -134,8 +137,25 @@ class FilterModule(object):
'symmetric_difference': symmetric_difference,
'union': union,
# combinatorial
'permutations': itertools.permutations,
'combinations': itertools.combinations,
# computer theory
'human_readable' : human_readable,
'human_to_bytes' : human_to_bytes,
}
# py2 vs py3, reverse when py3 is predominant version
try:
filters['zip'] = itertools.izip
filters['zip_longest'] = itertools.izip_longest
except AttributeError:
try:
filters['zip'] = itertools.zip
filters['zip_longest'] = itertools.zip_longest
except:
pass
return filters