2

我正在尝试使用 json_query 过滤器从字典列表中提取键、值,但出现错误。下面是剧本

  1
  2 - name: test
  3   hosts: localhost
  4   vars:
  5           testList: [ { "key1": "value11", "key2": "value12", "key3": "value13" },
  6                       { "key1": "value21", "key2": "value22", "key3": "value23" },
  7                       { "key1": "value31", "key2": "value32", "key3": "value33" } ]
  8   tasks:
  9        - name: Getting keys
 10          debug:
 11            msg: "{{ testList | json_query('[*].{key1: key1 , key2: key2}')}}"

这是输出

 [WARNING]: No inventory was parsed, only implicit localhost is available

 [WARNING]: Could not match supplied host pattern, ignoring: all

 [WARNING]: provided hosts list is empty, only localhost is available


PLAY [test] ****************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [localhost]

TASK [Getting keys] ********************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'module' object has no attribute 'exceptions'
fatal: [localhost]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""}


PLAY RECAP *****************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1

用一个键它工作正常"{{ testList | json_query('[*].key1')}}"

参考文档http://docs.ansible.com/ansible/latest/playbooks_filters.html#json-query-filter

是否有任何其他过滤器可以从字典列表中获取多个键、值?

4

1 回答 1

1

升级到最新的 Ansible 版本。

例如,此错误发生在 2.1.3.0 上(尽管根据其中一个警告中的短语判断,您可能使用了不同的版本)。

这是当前版本 2.4.1.0 的结果:

TASK [Getting keys] *****************************************************************************************************
Unaltered: {'msg': [{'key2': u'value12', 'key1': u'value11'}, {'key2': u'value22', 'key1': u'value21'}, {'key2': u'value32', 'key1': u'value31'}]}
ok: [localhost] => {
    "msg": [
        {
            "key1": "value11",
            "key2": "value12"
        },
        {
            "key1": "value21",
            "key2": "value22"
        },
        {
            "key1": "value31",
            "key2": "value32"
        }
    ]
}
于 2017-11-15T12:20:14.660 回答