selectattr returns 生成器行并且不能将结果用作字典

selectattr returns generator rows and cannot use results as a dict

解决方案: 我不知道 python -m pip install ansibleapt install ansible 之间的确切区别是什么,但是当我安装 python -m pip ansible-core==2.10.4 时它工作正常。


我的 CSV 文件如下所示:

id;env;credentials;path
1;tst;userA;/tmpA
2;dev;userB;/tmpB
3;dev;userB;/tmpC
4;acc;userB;/tmpD
5;prd;userC;/tmpE

我使用 read_csv 模块读取此文件,然后使用 selectattr:

进行过滤
  - name: Read CSV
    read_csv:
      path: "/tmp/example.csv"
      delimiter: ';'
    register: csv_output

  - name: Filter rows
    set_fact:
      new_fact: "{{ csv_output.list | selectattr('env', 'equalto', tst) }}"

过去我只能将这些结果用作字典,例如:

- debug:
    msg: "{{ new_fact }}"

ok: [ansible_main] => {
    "msg": [
        {
            "id": "1",
            "env": "tst",
            "credentials": "userA",
            "path": "/tmpA"
        }
    ]
}

但是当我尝试在本地机器上打印 new_fact 时,我只看到生成器:

ok: [ansible_main] => {
    "msg": "<generator object select_or_reject at 0x7f2e4e8847b0>"
}

我不能使用 new_fact.credentials 变量...你知道我该如何解决吗?我知道我可以在我的过滤器末尾添加 | list 但我也不能使用 new_fact.credentials

我的安装详情:

ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/userA/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.8.10 (default, Nov 26 2021, 20:14:08) [GCC 9.3.0]

关于

In the past I was able to just use these results as a dict ...

它是比 v2.9.6 更新得多的 Ansible 版本吗?

I know I can add | list at the end of my filter but then I also cannot user new_fact.credentials then

因为你也会得到一个列表,所以有必要指定元素

  - name: Filter rows
    set_fact:
      new_fact: "{{ csv_output.list | selectattr('env', 'contains', 'tst') | list }}"

  - debug:
      msg: "{{ new_fact[0].credentials }}"

循环结果,或只选取一个元素。

  - name: Filter rows
    set_fact:
      new_fact: "{{ csv_output.list | selectattr('env', 'contains', 'tst') | first }}"

  - debug:
      msg: "{{ new_fact.credentials }}"