如何以正确的方式在 ansible 剧本中转义字符?

How to escape chars in an ansible playbook the proper way?

我的剧本打算通过上传架构文件来扩展 LDAP 架构。该命令如下所示:

- name: LDAP extend schema
  copy: src={{ 'cn={10}subs.ldif' }} dest={{ '/opt/data/ldap/config/cn=config/cn=schema/cn={10}subs.ldif }} owner=joe group=joe mode=0600
  ignore_errors: True

如您所见,我 {{eval}} \escaping 路径不起作用。架构已正确上传,但剧本停止了,我想它无法进行校验和测试,因为它无法解析路径。我得到的错误如下:

fatal: [xx.domain.com] => failed to parse: Exception OSError: (2, 'No such file or directory', '/opt/data/ldap/config/cn=config/cn=schema/.ansible_tmp6XkGOucn={10}subs.ldif') in <bound method _TemporaryFileWrapper.__del__ of <closed file '<fdopen>', mode 'w+b' at 0x813660>> ignored
{"src": "/root/.ansible/tmp/ansible-tmp-1457985747.12-41932258379232/source", "md5sum": "651e7b60ebdcad75a95a5ff8e91695a8", "group": "joe", "uid": 498, "dest": "/opt/data/ldap/config/cn=config/cn=schema/cn={11}subs.ldif", "changed": true, "state": "file", "gid": 498, "secontext": "system_u:object_r:usr_t:s0", "mode": "0600", "owner": "joe", "size": 2481}

FATAL: all hosts have already failed -- aborting

我进行了一些谷歌搜索,看来这不是错误,这是一个类似的问题:https://github.com/ansible/ansible/issues/8032

我想我做错了,有一些简单的方法可以将可转义字符作为 srcdest 传递给 anisble 的复制模块,但我没能找出那是什么。

我不确定您到底想转义哪些字符,但我想是等号。

您发布的任务在 Ansible 2 中抛出解析器错误所以我也假设您 运行 Ansible 1.x 因为您得到了一些不同的东西。

Unexpected Exception: error while splitting arguments, either an unbalanced jinja2 block or quotes

鉴于我的第一个假设是正确的,您可以通过不使用 key=value 表示法而是使用正确的 YAML 语法轻松解决转义问题。

- name: LDAP extend schema
  copy:
    src: cn={10}subs.ldif
    dest: /opt/data/ldap/config/cn=config/cn=schema/cn={10}subs.ldif
    owner: joe
    group: joe

还有一个小副作用,它实际上是可读的。 ;-)

这适用于 Ansible 2。如果这不适用于您的 Ansible 版本,我不知道如果不升级 Ansible 是否能为您提供帮助。因为这部分错误信息:

/opt/data/ldap/config/cn=config/cn=schema/.ansible_tmp6XkGOucn={10}subs.ldif

表明它正在向文件名中注入一个唯一的字符串,这通常不会发生在中间。所以我猜它在文件名中有一些特殊字符有问题。无论您如何定义任务(YAML 或 k=v),这对于 Ansible 1 可能都是正确的

解决方法是使用不同的名称将文件复制到某个位置,然后使用 shell 任务将其简单地移动到所需位置。这应该独立于 Ansible 版本工作。

- name: LDAP extend schema
  copy:
    src: cn={10}subs.ldif
    dest: /tmp/ldap.extension
    owner: joe
    group: joe
  register: extension

- shell: "mv /tmp/ldap.extension /opt/data/ldap/config/cn=config/cn=schema/cn={10}subs.ldif"
  when: extension | changed
  creates: /opt/data/ldap/config/cn=config/cn=schema/cn={10}subs.ldif
  removes: /tmp/ldap.extension

但它也很丑...