本文介绍了Ansible - 将环境中的 JSON 字符串传递给 shell 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to pass JSON string in environment.

- 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_1 is 172.31.00.00

test_host_2 是 172.31.00.00

test_host_2 is 172.31.00.00

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

But in spring logs, I get JSON parse exception where it prints

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]

正如所见,双引号被转换为单引号!!!

As seen, double quotes are converted to single quotes !!!

我尝试转义双引号,但没有成功.

I tried escaping double quotes but with no luck.

知道为什么会发生这种情况,或者有什么解决办法吗?

Any idea why it happens, or any work around?

推荐答案

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

There is a thing about Ansible template engine.
If a string seems like an object (starts with { or [) Ansible converts it into object. See code.

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

To prevent this, you may use one of STRING_TYPE_FILTERS:

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

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

P.S. this is why hack with space character from @techraf's answer works: Ansible misses startswith("{") comparison and don't convert string to object.

这篇关于Ansible - 将环境中的 JSON 字符串传递给 shell 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:44