[英]How can I pass a json variable set by set_fact to jq pipeline in ansible shell task?
I have a ansible playbook that has set a json variable using set_fact
module.我有一个 ansible 剧本,它使用set_fact
模块设置了一个 json 变量。 I'm trying to use jq command in ansible playbook, to transform that json to a particular format, but got parse error: Invalid numeric literal at line, column
我正在尝试在 ansible 剧本中使用 jq 命令,将 json 转换为特定格式,但出现解析错误: Invalid numeric literal at line, column
My Playbook:我的剧本:
- name: get data
set_fact:
data: "{{ value.stdout | from_json }}"
- name: get key value pairs
shell: echo "{{ data }}" | jq 'to_entries | map((.key) + "=" + .value)|join(",")'
register: key_value
Error:错误:
TASK [utils : debug] *************************************************************************************
ok: [localhost] => {
"data": {
"key1": "keyval1",
"key2": "keyval2"
}
}
TASK [utils : get key value pairs] ***************************************************************
FAILED! => {"changed": true, "cmd": "echo \"{'key1': 'keyval1', 'key2': 'keyval2'}\" | jq 'to_entries | map((.key) + \"=\" + .value)|join(\",\")'", "stderr": "parse error: Invalid numeric literal at line , column", "stderr_lines": ["parse error: Invalid numeric literal at line , column"], "stdout": "", "stdout_lines": []}
PS: I had tried using > YAML construct specified in How to use jq in ansible shell tasks but got same error PS:我曾尝试使用在如何在 ansible shell 任务中使用 jq 中指定的 > YAML 构造,但得到相同的错误
- name: get key value pairs
shell: >
echo "{{ data }}"
| jq 'to_entries | map((.key) + "=" + .value)|join(",")'
register: key_value
My data
variable set using set_fact
module:我使用set_fact
模块设置的data
变量:
"data": {
"key1": "keyval1",
"key2": "keyval2"
}
Working jq command and expected output: jqPlay工作 jq 命令和预期 output: jqPlay
How can I pass the fact variable set using set_fact
to jq pipeline in ansible?如何将使用set_fact
设置的事实变量集传递给 ansible 中的 jq 管道?
Error seems to be jq complaining about the JSON passed to it.错误似乎是 jq 抱怨传递给它的 JSON。 As mentioned by @knittl the json printed in error message isn't valid JSON.正如@knittl 所述,错误消息中打印的 json 无效 JSON。 Somehow double quotes were replaced by single quote although debug prints valid JSON.尽管调试打印出有效的 JSON,但不知何故双引号被单引号取代。 Invalid JSON was passed to jq.无效的 JSON 被传递给 jq。
Replacing the single quote with double quote solved the issue.用双引号替换单引号解决了这个问题。
shell: echo "{{ data }}" | sed "s/'/\"/g" | jq 'to_entries | map((.key) + "=" + .value)|join(",")'
or或者
shell: echo "{{ data | to_json }}"| jq 'to_entries | map((.key) + "=" + .value)|join(",")'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.