我正在编写一个剧本,我需要执行mysql查询并以json格式传递输出。 playbook代码正常工作只是我想要在字符串concatenate
部分面临错误。如果我传递样本json字符串它工作正常。
- name: Execute php script with json parameter
command: php -f /path/to/php/test.php "{'colors':{'red','blue','yellow'}}"
register: php_output
output.stdout_lines
是我的playbook中设置的变量,其中包含{'red','blue','yellow'}
格式的输出。
- name: Execute php script with json parameter
command: php -f /path/to/php/test.php '{"stdout_lines": {{output.stdout_lines}} }'
register: php_output
那么如何在output.stdout_lines
中连接'{"stdout_lines": {{output.stdout_lines}} }'
变量?有什么建议
stdout_lines
是为方便起见而创建的。回到那一天,我们只有stdout
。我认为这是你想要的:
command: php -f /path/to/php/test.php '{"stdout_lines": {{output.stdout}} }'
如果你想真正自我连接,说因为你有自己的字符串列表,那么你可以使用Jinja2内置过滤器join
:
- hosts: localhost
gather_facts: False
tags: so9
vars:
- str_list: ['Hello', 'world', '!', ]
tasks:
- debug: msg="orig list={{ str_list }}"
- debug: msg="concated = {{ str_list | join(' ') }}"
- set_fact: concated_str="{{ str_list | join(' ') }}"
- debug: msg="assigned to a variable concated_str = {{ concated_str }}"
这样做
- name: Generate JSON output based on template
template: src=colors.json.j2 dest=/tmp/colors.json
with_items: colors
它会生成一个像
{'colors':
{
'blue',
'red',
'green',
}
}
to_json
过滤器是你想要的。
Ansible不将变量存储为JSON字符串,它将它们存储为Python对象。当你在调试时,例如使用-vvv
,Ansible将这些Python对象显示为JSON字符串,但这是为了您的方便。
要生成所需的命令:
- name: Execute php script with json parameter
vars:
# define my desired object
my_object:
colors: "{{ output.stdout_lines }}"
# my_object contains a dict with a single key
# "colors" who's value is the list contained
# in output.stdoutlines
command: "php -f /path/to/php/test.php {{ my_object | to_json | quote }}"
register: php_output
to_json
获取存储在my_object
中的对象并输出JSON字符串。
quote
自动处理JSON字符串可能需要的任何shell引用。例如如果我的JSON字符串包含双引号,quote
将整个JSON字符串包装在单引号中。