Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.12: Keep pre Python 3.10 literal_eval behavior (#76261) #76287

Merged
merged 1 commit into from
Nov 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelogs/fragments/jinja2_native-literal_eval-py310.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
minor_changes:
- jinja2_native - keep same behavior on Python 3.10.
7 changes: 1 addition & 6 deletions lib/ansible/playbook/conditional.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,12 +184,7 @@ def generic_visit(self, node, inside_call=False, inside_yield=False):
# NOTE The spaces around True and False are intentional to short-circuit safe_eval and avoid
# its expensive calls.
presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional
# NOTE Convert the result to text to account for both native and non-native jinja.
# NOTE The templated result of `presented` is string on native jinja as well prior to Python 3.10.
# ast.literal_eval on Python 3.10 removes leading whitespaces so " True " becomes bool True
# as opposed to Python 3.9 and lower where the same would result in IndentationError and
# string " True " would be returned by Templar.
val = to_text(templar.template(presented, disable_lookups=disable_lookups)).strip()
val = templar.template(presented, disable_lookups=disable_lookups).strip()
if val == "True":
return True
elif val == "False":
Expand Down
12 changes: 8 additions & 4 deletions lib/ansible/template/native_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
__metaclass__ = type


from ast import literal_eval
from itertools import islice, chain
import ast
import types
from itertools import islice, chain

from jinja2.runtime import StrictUndefined

Expand Down Expand Up @@ -83,7 +83,11 @@ def ansible_native_concat(nodes):
out = u''.join([to_text(_fail_on_undefined(v)) for v in nodes])

try:
out = literal_eval(out)
return out
return ast.literal_eval(
# In Python 3.10+ ast.literal_eval removes leading spaces/tabs
# from the given string. For backwards compatibility we need to
# parse the string ourselves without removing leading spaces/tabs.
ast.parse(out, mode='eval')
)
except (ValueError, SyntaxError, MemoryError):
return out