Ansible-将环境中的JSON字符串传递到Shell模块 [英] Ansible - passing JSON string in environment to shell module

查看:420
本文介绍了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

但是在春季日志中,我在打印的地方得到了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 }}"

P.S.这就是为什么@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模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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