From 1e68881c40a7395c9e2f88bdbb1f9dabbd7524b1 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Mon, 24 Sep 2018 18:57:19 -0400 Subject: [PATCH] adds support for null values to the ternary filter (#45303) * adds support for null values to the ternary filter This change adds a third optional argument to the ternary filter to handle a null value. If the third option is specified null and false are treated differently. For instance, take the following example: {{ enabled | ternary('no shutdown', 'shutdown') }} If enabled == True, then 'no shutdown' is used. If enabled in (False, None), then 'shutdown' is used. With this change the following is possible: {{ enabled | ternary('no shutdown', 'shutdown', omit) }} If enabled == True, then 'no shutdown' If enabled == False, then 'shutdown' If enabled == None, then omit * update documentation with example of filter * update filter documentation example per comments * fix logic error in user_guide example --- docs/docsite/rst/user_guide/playbooks_filters.rst | 4 ++++ lib/ansible/plugins/filter/core.py | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/docsite/rst/user_guide/playbooks_filters.rst b/docs/docsite/rst/user_guide/playbooks_filters.rst index 37adc0f3e14..5134a02ef4c 100644 --- a/docs/docsite/rst/user_guide/playbooks_filters.rst +++ b/docs/docsite/rst/user_guide/playbooks_filters.rst @@ -1081,6 +1081,10 @@ To use one value on true and another on false (new in version 1.9):: {{ (name == "John") | ternary('Mr','Ms') }} +To use one value on true, one value on false and a third value on null (new in version 2.8):: + + {{ enabled | ternary('no shutdown', 'shutdown', omit) }} + To concatenate a list into a string:: {{ list | join(" ") }} diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py index 26489864328..00837d6d17f 100644 --- a/lib/ansible/plugins/filter/core.py +++ b/lib/ansible/plugins/filter/core.py @@ -178,9 +178,11 @@ def regex_search(value, regex, *args, **kwargs): return items -def ternary(value, true_val, false_val): +def ternary(value, true_val, false_val, none_val=None): ''' value ? true_val : false_val ''' - if bool(value): + if value is None and none_val is not None: + return none_val + elif bool(value): return true_val else: return false_val