I have a ansible playbook that has set a json variable using set_fact
module. 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
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
- 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:
"data": {
"key1": "keyval1",
"key2": "keyval2"
}
Working jq command and expected output: jqPlay
How can I pass the fact variable set using set_fact
to jq pipeline in ansible?
Error seems to be jq complaining about the JSON passed to it. As mentioned by @knittl the json printed in error message isn't valid JSON. Somehow double quotes were replaced by single quote although debug prints valid JSON. Invalid JSON was passed to 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(",")'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.