You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

  1. String Concatenation: The ~ operator joins the escaped quotes (\") with your target variable, creating a properly quoted key like "c amz" in the JMESPath query.
  2. JMESPath Query: The resulting query becomes "c amz".link, which correctly references the key with spaces.
  3. | first Filter: The quoted key syntax returns a list containing the link value, so we use first to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:04:10