首页 > 解决方案 > 带有 output_encoding 的 Ansible 任务模板:base64 抛出未知编码

问题描述

以下是ansible任务

- name: copy file
  template:
    src: app.properties.j2
    dest: "{{ installDir }}/app.properties"
    output_encoding: base64

在执行上述任务时,ansible 抛出以下错误 An exception occurred during task execution. To see the full traceback, use -vvv. The error was: LookupError: unknown encoding: base64,详细的堆栈跟踪是


The full traceback is:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/ansible/executor/task_executor.py", line 140, in run
    res = self._execute()
  File "/usr/lib/python3/dist-packages/ansible/executor/task_executor.py", line 612, in _execute
    result = self._handler.run(task_vars=variables)
  File "/usr/lib/python3/dist-packages/ansible/plugins/action/template.py", line 187, in run
    f.write(to_bytes(resultant, encoding=output_encoding, errors='surrogate_or_strict'))
  File "/usr/lib/python3/dist-packages/ansible/module_utils/_text.py", line 133, in to_bytes
    return obj.encode(encoding, errors)
LookupError: unknown encoding: base64

这是 ansible version 命令的输出

ansible 2.7.7
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.7.3 (default, Jul 25 2020, 13:03:44) [GCC 8.3.0]

所有这些库都打包在 dockerfile 中。请帮助/建议。

标签: pythonansible

解决方案


您在哪里找到表明这base64是有效值的文档output_encoding

Ansible文档说“它默认为 utf-8,但可以使用 python 支持的任何编码。”。

在 Python 中,输出编码由codecs模块提供,用于控制字节字符串和语言特定字符之间的转换。utf-8它支持and之类的东西latin1,但不支持base64

如果您想base64在 Ansible 中编码某些内容,请使用b64encode过滤器。

您可以执行以下操作:

- name: render template to variable
  set_fact:
    template_value: "{{ lookup('template', 'app.properties.j2') }}"

- name: write base64 encoded file
  copy:
    dest: "{{ installDir }}/app.properties"
    content: "{{ template_value | b64encode }}"

推荐阅读