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

Nir*_*dia 4 json ansible

我试图在环境中传递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}}"}'
Run Code Online (Sandbox Code Playgroud)

test_host_1是172.31.00.00

test_host_2是172.31.00.00

但是在spring日志中,我会在打印时获得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]
Run Code Online (Sandbox Code Playgroud)

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

我试图逃避双引号但没有运气.

知道为什么会这样,或者任何解决方法吗?

Kon*_*rov 10

Ansible模板引擎有一个问题.
如果字符串看起来像一个对象(以{或开头[)Ansible将其转换为对象.见代码.

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

- SPRING_APPLICATION_JSON: "{{ {'test-host.1':test_host_1,'test-host.2':test_host_2} | to_json }}"
Run Code Online (Sandbox Code Playgroud)

PS这就是为什么来自@ techraf的答案有空间特征的黑客行为:Ansible错过了startswith("{")比较并且没有将字符串转换为对象.


tec*_*raf 6

快速技巧:在变量定义中添加一个空格(在第一个单引号之后)-单个空格不会影响实际的变量值(空格将被忽略):

- 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}}"}'
Run Code Online (Sandbox Code Playgroud)

使用Ansible传递给shell的空间(test1test2是我设置的值):

SPRING_APPLICATION_JSON='"'"' {"test-host.1":"test1","test-host.2":"test2"}'"'"'
Run Code Online (Sandbox Code Playgroud)

没有空格:

SPRING_APPLICATION_JSON='"'"'{'"'"'"'"'"'"'"'"'test-host.2'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'test2'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'test-host.1'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'test1'"'"'"'"'"'"'"'"'}'"'"'
Run Code Online (Sandbox Code Playgroud)

顺序也相反。好像没有空格一样,它用空格作为字符串解释JSON。

我真的不明白为什么会这样...