10

I'm new to using python and flask and really like it. I'm returning a query to be displayed in a jinja template and one of my columns being returned has base64 data. How do I decode that data and display it.

skellington
  • 149
  • 1
  • 1
  • 7
  • this is not a duplicate of https://stackoverflow.com/questions/3470546/how-do-you-decode-base64-data-in-python, as that is about b64decoding in python, whereas this is about jinja – Neil McGuigan Apr 15 '23 at 06:41

2 Answers2

14

In jinja To work with Base64 encoded strings:

{{ encoded | b64decode }}
{{ decoded | b64encode }}

For more http://docs.ansible.com/ansible/playbooks_filters.html

Ruhul Amin
  • 1,751
  • 15
  • 18
  • 5
    It work only in ansible jinja2 implementation https://github.com/ansible/ansible/blob/ed7623ecdec8585282ce91f1534d02e6a38c22a4/lib/ansible/plugins/filter/core.py#L377 – Maks Skorokhod Aug 19 '16 at 21:18
  • 2
    Be advised that the result must be a valid UTF-8 string or you will get U+FFFE replacement characters in there. (E.g. you can't safely handle base64-encoded public keys this way.) – Ulrich Schwarz Mar 25 '19 at 07:49
  • With StaltStack, I had to use `{{ encoded_text | base64_decode }}`, see [SaltStack Jinja docs](https://docs.saltproject.io/en/latest/topics/jinja/index.html#base64-decode) – mihca Mar 16 '22 at 13:03
9

You can try to write custom filter

# add filter to jinja2 env
environment.filters['b64decode'] = base64.b64decode

# in template use
{{ value|b64decode }}
Maks Skorokhod
  • 615
  • 1
  • 7
  • 14
  • No need for that as it is in the default filters https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#manipulating-strings – XenGi Sep 23 '20 at 23:43
  • 7
    It's default filter only for ansible, not for jinja https://jinja.palletsprojects.com/en/2.10.x/templates/#list-of-builtin-filters – Maks Skorokhod Sep 24 '20 at 11:48
  • b64decode returns bytes but you probably want a string: `environment.filters['b64decode'] = lambda s: base64.b64decode(s).decode()` – dashingdove Jun 20 '23 at 16:01