I’m having trouble with a jquery statement in Ansible. My host name has "-" in its name which I need to specify to bring back the results I need. I have tried various ways to escape the "-" but with no joy. As it stands below is my current task:
- name: Query with hyphen
debug:
msg: "{{ results.json.list | json_query(querystr) }}"
vars:
querystr: "[?hostname=={{ host }}].{hostname: hostname, status: status}"
host: '["server-bbbv-14"]'
I get no error but this is the result I receive:
"msg": []
Here is my json result I’m querying:
"json": {
"list": [
{
"status": "1",
"hostname": "server-bbbv-10"
},
{
"status": "3",
"hostname": "server-bbbv-14"
},
{
"status": "3",
"hostname": "server-bbbv-17"
},
{
"status": "1",
"hostname": "server-bbbv-11"
}
[
}
I have also tried ‘"server-bbbv-14"’ which give me the same output.
I tried "server-bbbv-14" and ‘server-bbbv-14’ and got below error:
"msg": "Error in jmespath.search in json_query filter plugin:ninvalid literal for int() with base 10: '-'"
I tried [‘server-bbbv-14’] and recevied:
"msg": "Error in jmespath.search in json_query filter plugin:n'literal'"
For sanity I tried searching on the status and it works as expected bringing back results that match the given status I put in.
Please note, the vars of host is actually going to be the built in Ansible variable inventory_hostname but as that did not work I have tried setting this manually to get it working first.
Please help.
2
Answers
Below is the correct query
gives
Note: It’s not necessary to use json_query. You can use selectattr instead. The below expression gives the same result
A simpler solution would be to create a dictionary first
gives
This makes the above query trivial.
Example of a complete playbook for testing
There is no need to escape hyphens. Your jmespath query is incorrect. Moreover, using jmespath here is not really the best option. In a nutshell, the following
playbook.yml
meets your expectations:Running that playbook with the task profiler shows both method return the same result and that using the stock filters in this specific case is twice as fast on my machine