Skip to content

Commit

Permalink
Avoid Object of type PosixPath is not JSON serializable with jinja2 (#…
Browse files Browse the repository at this point in the history
…2724)

Fixes: #2697
  • Loading branch information
ssbarnea authored Nov 24, 2022
1 parent feafbd7 commit a4b10ad
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
1 change: 1 addition & 0 deletions .config/dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ createfile
darglint
dataclasses
dbservers
deannotate
debops
decryptable
delenv
Expand Down
20 changes: 20 additions & 0 deletions examples/playbooks/rule-jinja-valid.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,23 @@
vars:
ns_vars: {}
x: "{{ lookup('ansible.builtin.template', 'namespace.yaml.j2', template_vars=ns_vars) | from_yaml }}"

# https://github.com/ansible/ansible-lint/issues/2697
- name: Test linter
hosts: localhost
gather_facts: false
tasks:
- name: Passed linter
ansible.builtin.debug:
msg: "{{ test | to_json }}"
vars:
test:
one: two
param: "{{ ansible_host }}"
- name: Failed linter
ansible.builtin.debug:
msg: "{{ test | to_json }}"
vars:
test:
one: two
param: no jinja
20 changes: 19 additions & 1 deletion src/ansiblelint/rules/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,24 @@

Token = namedtuple("Token", "lineno token_type value")

DEANNOTATE_KEYS = ("__file__", "__line__", "__start_line__", "__end_line__")


def deannotate(data: Any) -> Any:
"""Remove our annotations like __file__ and __line__ and return a JSON serializable object."""
if isinstance(data, dict):
result = data.copy()
for key, value in data.items():
if key in DEANNOTATE_KEYS:
del result[key]
elif isinstance(value, list):
for i, item in enumerate(value):
value[i] = deannotate(item)
elif isinstance(value, dict):
result[key] = deannotate(value)
return result
return result


class JinjaRule(AnsibleLintRule):
"""Rule that looks inside jinja2 templates."""
Expand Down Expand Up @@ -62,7 +80,7 @@ def matchtask( # noqa: C901
template(
basedir=file.dir if file else ".",
value=v,
variables=task.get("vars", {}),
variables=deannotate(task.get("vars", {})),
fail_on_error=True, # we later decide which ones to ignore or not
)
# ValueError RepresenterError
Expand Down

0 comments on commit a4b10ad

Please sign in to comment.