如果格式兼容,Ansible 将字符串解析为列表,如何转义? [英] Ansible parses strings as lists if the format is compatible, how to escape?

查看:23
本文介绍了如果格式兼容,Ansible 将字符串解析为列表,如何转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 ansible,我需要将主机列表放在一个文件中,如下所示:

Using ansible, I need to put a list of hosts in line in a file like so:

["127.0.0.1", "127.0.0.2", "127.0.0.3"]

但是每当我实现这种格式时,ansible 将其解释为一个列表,并且文件的内容是这个 pythonic 版本:

But whenever I achieve this format, ansible interprets it as a list and the content of the file is this pythonic version:

['127.0.0.1', '127.0.0.2', '127.0.0.3']

这是我迄今为止尝试解决的方法:

Here's my attempts to get it out thus far:

---

- hosts: all
  gather_facts: False
  tasks:

  - set_fact:
      myhosts:
        - 127.0.0.1
        - 127.0.0.2
        - 127.0.0.3

  # This comes out as a list, I need a string
  - set_fact:
      var: "[ \"{{ myhosts | join('\", \"')}}\" ]"
  - debug: var=var

  # This comes out as a string, but I need no underscore on it
  - set_fact:
      var: "_[ \"{{ myhosts | join('\", \"')}}\" ]"
  - debug: var=var

  # This also comes out as a list
  - set_fact:
      var: >
        [ "{{ myhosts | join('", "')}}" ]
  - debug: var=var

  # Also parsed as a list
  - set_fact:
      var: "{{ myhosts | to_json }}"
  - debug: var=var

# ansible-playbook -i "localhost," this_file.yml

推荐答案

有一些过滤器会阻止 Ansible 模板引擎进行字符串评估.
此过滤器列表存储在 STRING_TYPE_FILTERS 设置中.
在 Ansible 2.1 中,它包含:stringto_jsonto_nice_jsonto_yamlppretty, json.

There are some filters that prevent Ansible template engine from doing string evaluation.
This list of filters is stored in STRING_TYPE_FILTERS setting.
In Ansible 2.1 it contains: string, to_json, to_nice_json, to_yaml, ppretty, json.

所以,你可以这样做:

- lineinfile: line="{{ myhosts | to_json }}" dest=output.txt

这会将 ["127.0.0.1", "127.0.0.2", "127.0.0.3"] 行添加到文件中.

This will add ["127.0.0.1", "127.0.0.2", "127.0.0.3"] line to the file.

并且在处理精确的字符串格式时不要相信 debug 的输出.
始终使用 copy: content="{{ string_output_to_test | string }}" dest=test.txt 并检查文件内容以确保.

And don't believe debug's output when dealing with exact string formatting.
Always use copy: content="{{ string_output_to_test | string }}" dest=test.txt and check file contents to be sure.

debug: var=myvar 将始终以评估为模板,因此您的字符串将始终打印为列表.
debug: msg="{{ myvar | string }}" 会将 myvar 打印为 JSON 编码的字符串.

debug: var=myvar will always template with evaluation, so your string will always be printed as a list.
debug: msg="{{ myvar | string }}" will print myvar as JSON encoded string.

这篇关于如果格式兼容,Ansible 将字符串解析为列表,如何转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆