I'm trying to get the name and is_encrypted attributes of a JSON object based on condition.
I.e.:
is_encrypted == YES if data_encryption.drive_protection_enabled == true or data_encryption.software_encryption_enabled == true else NO
This is how the facts variable looks like:
{
"facts": {
"changed": true,
"failed": false,
"response": {
"num_records": 1,
"records": [
{
"data_encryption": {
"drive_protection_enabled": false,
"software_encryption_enabled": false
},
"name": "egg",
"uuid": "xxx-xxx"
}
]
},
"status_code": 200
}
}
Output like list of name and is_encrypted:
{
"aggregate_name": "egg",
"is_encrypted": "NO"
},
I'm trying below format with json_query
egg_info: "{{ egg_info | default ([]) + facts | json_query(\"response.records[*].{name: name, is_encrypted: 'YES' if (data_encryption.software_encryption_enabled == 'true' || data_encryption.drive_protection_enabled == 'true') else 'NO' }\") }}"
Ending up the error
{"msg": "JMESPathError in json_query filter plugin:\nExpecting: colon, got: lparen: Parse error at column 66, token "(" (LPAREN), for expression:\n"response.records[*].{name: name, is_encrypted: 'YES' if (data_encryption.software_encryption_enabled == 'true' || data_encryption.drive_protection_enabled == 'true') else 'NO' }"\n ^"}
Q: "Use If Else condition in single JMESPath query."
A: There is no
If Elsecondition in JMESPath. As a result, it is not possible to convert a boolean to an arbitrary string in json_query. A single query nearest to what you want would begives (see the below data for testing)
Given the below data for testing
Workaround: If you for whatever reason need strings ('YES', 'NO') instead of booleans (true, false) use json_query and create a dictionary
gives
Convert it to a list if you want to
gives
If you need strings instead of booleans create a dictionary
gives
and convert it to a list if you want to
gives
Example of a complete playbook for testing