4

我想在 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

4

2 回答 2

5

下面带有 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
于 2019-08-14T12:35:12.070 回答
1

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

- debug:
    msg: "{{ check_objects | json_query(query) }}"
  vars:
    query: "{{ project_environment }}.{{ project_status}}"
于 2019-08-14T16:17:29.770 回答