Skip to content

Commit

Permalink
base64 filter: Added ability to specify encoding (ansible#39714)
Browse files Browse the repository at this point in the history
* base64 filter: Added ability to specify encoding

* Added unicode chars for further testing

* Removed errors to keep previous behaviour in place

* Removed surrogate pairs due to issues loading YAML in CI
  • Loading branch information
jborean93 authored May 4, 2018
1 parent b5cffe8 commit fc210a4
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 4 deletions.
3 changes: 3 additions & 0 deletions changelogs/fragments/base64_filter_encoding.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
minor_changes:
- Added an ``encoding`` option to the ``b64encode`` and ``b64decode`` filters
to specify the encoding of the string that is base64 encoded.
7 changes: 7 additions & 0 deletions docs/docsite/rst/user_guide/playbooks_filters.rst
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,13 @@ To work with Base64 encoded strings::
{{ encoded | b64decode }}
{{ decoded | b64encode }}

As of version 2.6, you can define the type of encoding to use, the default is ``utf-8``::

{{ encoded | b64decode(encoding='utf-16-le') }}
{{ decoded | b64encode(encoding='utf-16-le') }}

.. versionadded:: 2.6

To create a UUID from a string (new in version 1.9)::

{{ hostname | to_uuid }}
Expand Down
8 changes: 4 additions & 4 deletions lib/ansible/plugins/filter/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,12 +459,12 @@ def do_groupby(environment, value, attribute):
return [tuple(t) for t in _do_groupby(environment, value, attribute)]


def b64encode(string):
return to_text(base64.b64encode(to_bytes(string, errors='surrogate_or_strict')))
def b64encode(string, encoding='utf-8'):
return to_text(base64.b64encode(to_bytes(string, encoding=encoding, errors='surrogate_or_strict')))


def b64decode(string):
return to_text(base64.b64decode(to_bytes(string, errors='surrogate_or_strict')))
def b64decode(string, encoding='utf-8'):
return to_text(base64.b64decode(to_bytes(string, errors='surrogate_or_strict')), encoding=encoding)


def flatten(mylist, levels=None):
Expand Down
8 changes: 8 additions & 0 deletions test/integration/targets/filters/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,11 @@
- flat_two == [1, 2, 3, 4, [5], 6, 7]
vars:
orig_list: [1, 2, [3, [4, [5]], 6], 7]

- name: Test base64 filter
assert:
that:
- "'Ansible - くらとみ\n' | b64encode == 'QW5zaWJsZSAtIOOBj+OCieOBqOOBvwo='"
- "'QW5zaWJsZSAtIOOBj+OCieOBqOOBvwo=' | b64decode == 'Ansible - くらとみ\n'"
- "'Ansible - くらとみ\n' | b64encode(encoding='utf-16-le') == 'QQBuAHMAaQBiAGwAZQAgAC0AIABPMIkwaDB/MAoA'"
- "'QQBuAHMAaQBiAGwAZQAgAC0AIABPMIkwaDB/MAoA' | b64decode(encoding='utf-16-le') == 'Ansible - くらとみ\n'"

0 comments on commit fc210a4

Please sign in to comment.