小编典典

Ansible-将环境中的JSON字符串传递给Shell模块

json

我正在尝试在环境中传递JSON字符串。

- name: Start {{service_name}}
  shell: "<<starting springboot jar>> --server.port={{service_port}}\""
  environment:
    - SPRING_APPLICATION_JSON: '{"test-host.1":"{{test_host_1}}","test-host.2":"{{test_host_2}}"}'

test_host_1是172.31.00.00

test_host_2是172.31.00.00

但是在春季日志中,我在打印的地方得到了JSON解析异常

Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
 at [Source: {'test-host.1': '172.31.00.00', 'test-host.2': '172.31.00.00'}; line: 1, column: 3]

如图所示,双引号转换为单引号!!!

我尝试转义双引号,但没有运气。

知道为什么会发生,还是可以解决?


阅读 442

收藏
2020-07-27

共1个答案

小编典典

关于Ansible模板引擎的事情。
如果字符串看起来像对象(以{或开头[),则Ansible会将其转换为对象。参见代码

为防止这种情况,您可以使用STRING_TYPE_FILTERS之一

- SPRING_APPLICATION_JSON: "{{ {'test-host.1':test_host_1,'test-host.2':test_host_2} | to_json }}"

PS这就是为什么@techraf的答案中带有空格符的hack起作用的原因:Ansible错过了startswith("{")比较并且不将字符串转换为对象。

2020-07-27