如何在Ansible中使用json_query()通过变量键获取JSON链接值?
The main issue with your current code is that you're nesting Jinja2 delimiters ({{ ... }}) inside another Jinja expression, which isn't necessary and breaks the query. Additionally, since your JSON keys contain spaces, you need to properly quote them in the JMESPath query to avoid syntax errors.
Here's how to fix it:
Correct Approach
Use Jinja2 string concatenation to build a valid JMESPath query that quotes the target key, then extract the link and get the first (and only) result from the list:
- name: Set target variable set_fact: target: "c amz" - name: Retrieve the corresponding link debug: msg: "{{ input.json | json_query('\"' ~ target ~ '\".link') | first }}"
Explanation
- String Concatenation: The
~operator joins the escaped quotes (\") with yourtargetvariable, creating a properly quoted key like"c amz"in the JMESPath query. - JMESPath Query: The resulting query becomes
"c amz".link, which correctly references the key with spaces. | firstFilter: The quoted key syntax returns a list containing the link value, so we usefirstto get the actual string instead of a single-element list.
Alternative: Using Bracket Notation
You can also use JMESPath's bracket syntax for more explicit key referencing:
msg: "{{ input.json | json_query('[\"' ~ target ~ '\"] | [0].link') }}"
Full Working Playbook Example
If we include the input JSON as a variable, here's a complete test playbook to verify:
- name: Test JSON query with variable target hosts: localhost vars: input: json: "a goo": { "link": "google.com" } "b ms": { "link": "microsoft.com" } "c amz": { "link": "amazon.com" } target: "c amz" tasks: - debug: msg: "{{ input.json | json_query('\"' ~ target ~ '\".link') | first }}"
This will output exactly what you expect:
msg: "amazon.com"
内容的提问来源于stack exchange,提问作者FErben

