From 3ba516ac25ac6e9f60debb8e45e467032c5ff226 Mon Sep 17 00:00:00 2001 From: Michael Peters Date: Thu, 19 Jun 2014 12:25:36 -0400 Subject: [PATCH] adding min() and max() filters for use in Jinja templates --- docsite/rst/playbooks_variables.rst | 14 ++++++++++++++ lib/ansible/runner/filter_plugins/core.py | 10 ++++++++++ test/units/TestFilters.py | 8 ++++++++ 3 files changed, 32 insertions(+) diff --git a/docsite/rst/playbooks_variables.rst b/docsite/rst/playbooks_variables.rst index f072c098969..8e656add6d5 100644 --- a/docsite/rst/playbooks_variables.rst +++ b/docsite/rst/playbooks_variables.rst @@ -180,6 +180,20 @@ Jinja2 provides a useful 'default' filter, that is often a better approach to fa In the above example, if the variable 'some_variable' is not defined, the value used will be 5, rather than an error being raised. +.. _list_filters: + +List Filters +-------------------- +.. versionadded:: 1.7 + +To get the minimum value from list of numbers:: + + {{ list1 | min }} + +To get the maximum value from a list of numbers:: + + {{ [3, 4, 2] | max }} + .. _set_theory_filters: Set Theory Filters diff --git a/lib/ansible/runner/filter_plugins/core.py b/lib/ansible/runner/filter_plugins/core.py index b8eecb03764..7ca0f937420 100644 --- a/lib/ansible/runner/filter_plugins/core.py +++ b/lib/ansible/runner/filter_plugins/core.py @@ -183,6 +183,14 @@ def union(a, b): c = unique(a + b) return c +def min(a): + _min = __builtins__.get('min') + return _min(a); + +def max(a): + _max = __builtins__.get('max') + return _max(a); + def version_compare(value, version, operator='eq', strict=False): ''' Perform a version comparison on a value ''' op_map = { @@ -289,6 +297,8 @@ class FilterModule(object): 'difference': difference, 'symmetric_difference': symmetric_difference, 'union': union, + 'min' : min, + 'max' : max, # version comparison 'version_compare': version_compare, diff --git a/test/units/TestFilters.py b/test/units/TestFilters.py index 9389147516c..7d921a7e375 100644 --- a/test/units/TestFilters.py +++ b/test/units/TestFilters.py @@ -175,3 +175,11 @@ class TestFilters(unittest.TestCase): self.assertTrue(ansible.runner.filter_plugins.core.version_compare(1.0, 1.1, '<=')) self.assertTrue(ansible.runner.filter_plugins.core.version_compare('12.04', 12, 'ge')) + + def test_min(self): + a = ansible.runner.filter_plugins.core.min([3, 2, 5, 4]) + assert a == 2 + + def test_max(self): + a = ansible.runner.filter_plugins.core.max([3, 2, 5, 4]) + assert a == 5