Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ansible将字符串解析为列表如果格式兼容,如何转义?_Ansible - Fatal编程技术网

Ansible将字符串解析为列表如果格式兼容,如何转义?

Ansible将字符串解析为列表如果格式兼容,如何转义?,ansible,Ansible,使用ansible,我需要将主机列表放入一个文件中,如下所示: ["127.0.0.1", "127.0.0.2", "127.0.0.3"] 但每当我实现这种格式时,ansible就会将其解释为一个列表,文件的内容就是这个pythonic版本: ['127.0.0.1', '127.0.0.2', '127.0.0.3'] 以下是我到目前为止的尝试: --- - hosts: all gather_facts: False tasks: - set_fact:

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

["127.0.0.1", "127.0.0.2", "127.0.0.3"]
但每当我实现这种格式时,ansible就会将其解释为一个列表,文件的内容就是这个pythonic版本:

['127.0.0.1', '127.0.0.2', '127.0.0.3']
以下是我到目前为止的尝试:

---

- 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模板引擎执行字符串计算。
此筛选器列表存储在设置中。
在Ansible 2.1中,它包含:
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”]

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

debug:var=myvar
将始终使用评估模板,因此您的字符串将始终作为列表打印。
debug:msg=“{myvar | string}}”
myvar
打印为JSON编码的字符串