首页 > 解决方案 > 将键名提取到列表中

问题描述

鉴于以下情况,我想最终得到一个与这些 UID 匹配的用户名列表,例如用户:['u1']

- name: getent
  hosts: all
  tasks:
    - name: getent
      getent:
        database: passwd
        key: "{{ item }}"
        split: ':'
      with_items:
        - 20001
      register: users
    - name: debug
      debug:
        msg: "{{ users.results | map(attribute='ansible_facts.getent_passwd') | list }}"


TASK [debug] *******************************************************************
ok: [localhost] => {
    "users": {
        "changed": false,
        "msg": "All items completed",
        "results": [
            {
                "_ansible_item_result": true,
                "_ansible_no_log": false,
                "_ansible_parsed": true,
                "ansible_facts": {
                    "getent_passwd": {
                        "u1": [ <-- I do not care about anything contained within u1!

就以上而言,我最终得到

[{u'u1': [u'x', u'20001', u'20001', u'', u'/home/u1', u'/sbin/nologin']}]

我怎样才能得到

['u1']

标签: ansible

解决方案


这是使用JMESPath查询的解决方案:

- debug:
    msg: "{{ users.results | json_query('[].ansible_facts.getent_passwd.keys(@)[]') }}"
  • [].ansible_facts.getent_passwd相当于你的过滤器
  • keys(@)函数返回上述列表的键名
  • []展平结果列表

推荐阅读