在Ansible中的字典列表中搜索值

时间:2019-01-24 12:06:12

标签: ansible jinja2

首先,我知道这是一个重复的问题:我在这里找到了类似的话题: Searching for key in a list of dicts in AnsibleAnsible lookup values from complex structure?

我不知道我是否必须直接在这些主题中问我的问题,如果是的话,我真诚的道歉。

无论如何,在Ansible中,我需要从Web应用程序中提取API查询中的特定ID。 我有此代码:

- name: API query
  uri:
    method: GET
    url: "{{ apiquery }}"
    headers:
      Content-Type: application/json
      App-Token: "{{ appToken }}"
      Session-Token: "{{ currentSessionToken.json.session_token }}"
  register: wantedState

- name: DEBUG | wantedState output
  debug:
    msg: "{{ wantedState }}"

消息是这样的:

ok: [localhost] => {
    "msg": {
        "accept_range": "State 1000",
        "access_control_expose_headers": "content-type, content-range, accept-range",
        "cache_control": "no-store, no-cache, must-revalidate",
        "changed": false,
        "connection": "close",
        "content_length": "138",
        "content_range": "0-1/2",
        "content_type": "application/json; charset=UTF-8",
        "cookies": {},
        "cookies_string": "",
        "date": "Thu, 24 Jan 2019 11:51:42 GMT",
        "expires": "Mon, 26 Jul 1997 05:00:00 GMT",
        "failed": false,
        "json": {
            "content-range": "0-1/2",
            "count": 2,
            "data": [
                {
                    "1": "state1",
                    "2": 12
                },
                {
                    "1": "state11",
                    "2": 10
                }
            ],
            "order": "ASC",
            "sort": 1,
            "totalcount": 2
        },
        "msg": "OK (138 bytes)",
        "pragma": "no-cache",
        "redirected": false,
        "server": "Apache/2.4.18 (Ubuntu)",
        "status": 200,
        "url": "..."
    }
}

我需要获取与stateName变量关联的正确ID。

我遵循了另外两个主题中的建议,我的语法是:

- name: DEBUG | Displaying ID
  debug:
    msg: "{{ (wantedState.json.data | selectattr('1', 'equalto', stateName) | list | first).2 }}"

我收到以下错误消息:

"msg": "The task includes an option with an undefined variable. The error was: dict object has no element 1"

我不知道为什么我的查询无法正常运行,以致于……

预先感谢

西蒙(Simon)

1 个答案:

答案 0 :(得分:0)

Jinja2将类似整数的字符串转换为数字。
因此,'1''2'用于引用列表的第一和第二个元素。
我不知道有什么方法可以在Jinja2中禁用此行为。

您通常使用正确的语法。如果您的数据项具有键ab而不是12,那么就可以了。

对于您的情况,可以使用JMESPath过滤项目:

- name: DEBUG | Displaying ID
  debug:
    msg: "{{ (wantedState.json.data | json_query('[?\"1\"==`'+stateName+'`]') | first)['2'] }}"

请注意:

    1周围的
  • 双引号被转义了,因为我们在YAML引号字符串msg: "..."
  • 在stateName值周围有JMESPath文字引号(反引号)
  • 通过['2'](字符串)而不是.2(int)访问结果值
相关问题