Skip to main content
ereta
Explorer III
March 27, 2024
Question

Variable inside json_query

  • March 27, 2024
  • 2 replies
  • 1949 views

Hello!

 

I've been having issues trying to make the json_query function to be able to parse a variable within its query. Wondering if that's actually possible. I've tried multiple solutions given in the web for the ansible "json_query", but none have worked so far.

 

In my script, the unique_policy_id has a list of id's - ["123", "453", "234"]. What I am trying to do is to pull FAZ logs (contained in policy_violation_logs) that match with the given policyid in each iteration, using the variable "id" within json_query.

 

{% for id in unique_policy_id -%}
{% set log = policy_violation_logs | json_query("[?policyid==`" ~ id ~ "`]") -%}
{{ log }}
{% endfor -%}

 

I would appreciate your help on this.

 

Thanks!

FortiSOAR 

2 replies

Contributor III
March 27, 2024

 

Hi,

You are close here - change the ticks to single quotes and it should work:

 

 

{% for id in unique_policy_id -%} {% set log = policy_violation_logs | json_query("[?policyid=='" ~ id ~ "']") -%} {{ log }} {% endfor -%}

 

For more information, check out jmespath's documentation on string literals: https://jmespath.org/proposals/raw-string-literals.html

 

Regards,

ereta
eretaAuthor
Explorer III
March 27, 2024

Thought I had tried that before and didn't worked, perhaps I was missing/adding extra character/s.

 

That seems to do the trick, thank you!:D

roshan_bangera
Explorer
July 26, 2024

I believe this should serve your purpose.

{% for id in unique_policy_id %}
{% set query = '[?policyid==`' ~ id ~ '`]' %}
{% set log = policy_violation_logs | json_query(query) %}
{{ log }}
{% endfor %}

Thank You