我如何在 Ansible json_query 中使用变量?

How I can use Variables in Ansible json_query?

我想在 json 查询过滤器中使用一个 ansible 变量。 这是我的代码:

剧本执行:

ansible-playbook debug.yml -e "project_environment=live"
- debug:
    msg: "{{ project_environment }}"

- debug:
    msg: "{{ check_objects | json_query('`{{project_environment}}`.current') }}"

这是我的词典:

check_objects:
  live:
    current:
    - example.com
    next:
    - next.example.com

这是我得到的:

TASK [debug : debug] 
ok: [sample-hostname] => {
    "msg": "live"
}

TASK [debug  : debug]
ok: [sample-hostname] => {
    "msg": ""
}

当我使用预期值替换变量时,输出工作正常:

- debug:
    msg: "{{ check_objects | json_query('live.current') }}"
TASK [typo3-deployment/check : debug] 
ok: [sbk-test-ntly01] => {
    "msg": [
        "example.com"
    ]
}

我认为它在插入变量时遇到了麻烦。

我已经尝试过这个解决方案,但它也不起作用:Ansible : pass a variable in a json_query filter

下面json_query的任务

  vars:
    project_environment: live
  tasks:
    - debug:
        msg: "{{ check_objects|
                 dict2items|
                 json_query(query)|
                 flatten }}"
      vars:
        query: "[?key=='{{ project_environment }}'].value.current"

给予

"msg": [
    "example.com"
]

任务

也可以达到同样的效果
- debug:
    var: check_objects[project_environment].current

对于两个变量,这对我来说很好。

- debug:
    msg: "{{ check_objects | json_query(query) }}"
  vars:
    query: "{{ project_environment }}.{{ project_status}}"