Skip to content

Commit be7b4f4

Browse files
committed
Add example of unintentional None to 2.19 porting guide.
1 parent 4dfeda4 commit be7b4f4

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

docs/docsite/rst/porting_guides/porting_guide_core_2.19.rst

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,53 @@ The result of the corrected template remains a list:
407407
}
408408
409409
410+
Example - unintentional ``None``
411+
""""""""""""""""""""""""""""""""
412+
413+
If a part of a template evaluated to ``None``, it was implicitly converted to an empty string in previous versions of ansible-core.
414+
This can now result in the template evaluating to the *value* ``None``, or can result in the templated string containing the character sequence ``None``.
415+
416+
The following example shows two cases where this happens:
417+
418+
.. code-block:: yaml+jinja
419+
420+
- set_fact:
421+
# If 'foo' is not defined, the else branch basically evaluates to None.
422+
# So value_none will not be an empty string, but None:
423+
value_none: |-
424+
{% if foo is defined %}foo is defined{% endif %}
425+
426+
# The expression 'items.append(x)' evaluates to None, so the resulting string
427+
# will be "NoneNoneNone['a', 'b', 'c']" instead of the array ['a', 'b', 'c']:
428+
string_with_none: |-
429+
{% set items = [] %}
430+
{% for x in ['a', 'b', 'c'] %}
431+
{{- items.append(x) -}}
432+
{% endfor %}
433+
{{ items }}
434+
435+
These examples can be fixed as follows:
436+
437+
.. code-block:: yaml+jinja
438+
439+
- set_fact:
440+
# Explicitly return an empty string in the 'else' branch.
441+
# The value is always a string: either "foo is defined" or "".
442+
value_none: |-
443+
{% if foo is defined %}foo is defined{% else %}{{ "" }}{% endif %}
444+
445+
# Use {% set _ = expression %} instead of {{ expression }} eats the
446+
# return value. The template evalutes to the array ['a', 'b', 'c'].
447+
string_with_none: |-
448+
{% set items = [] %}
449+
{% for x in ['a', 'b', 'c'] %}
450+
{%- set _ = items.append(x) -%}
451+
{% endfor %}
452+
{{ items }}
453+
454+
These adjustments also work fine with older ansible-core versions.
455+
456+
410457
Lazy templating
411458
^^^^^^^^^^^^^^^
412459

0 commit comments

Comments
 (0)