Ansible parse json 输出,过滤单条记录

Ansbile parse json output, filter single record

lsblk输出我想打印根设备uuid。下面的输出我想在ansible varbile中提取"62144b98-20c7-4e2d-b508-aaf7a9e40d0f"值。

#  lsblk -f  -J /dev/sda
{
   "blockdevices": [
      {"name": "sda", "fstype": null, "label": null, "uuid": null, "mountpoint": null,
         "children": [
            {"name": "sda1", "fstype": "vfat", "label": null, "uuid": "66CD-B12C", "mountpoint": "/boot/efi"},
            {"name": "sda2", "fstype": "xfs", "label": null, "uuid": "92a02a22-f462-4d77-9de5-cde51f5f5b6f", "mountpoint": "/boot"},
            {"name": "sda3", "fstype": "LVM2_member", "label": null, "uuid": "FqbfY7-c5Lt-X7z7-lLqw-mfgd-PrcN-kYL7Pa", "mountpoint": null,
               "children": [
                  {"name": "rhel-root", "fstype": "xfs", "label": null, "uuid": "62144b98-20c7-4e2d-b508-aaf7a9e40d0f", "mountpoint": "/"},
                  {"name": "rhel-swap", "fstype": "swap", "label": null, "uuid": "941e4d11-c659-4b17-897c-900e486b299d", "mountpoint": null},
                  {"name": "rhel-tmp", "fstype": "xfs", "label": null, "uuid": "85c1fb80-22f8-4679-bfd8-d0c1adc96f90", "mountpoint": null},
                  {"name": "rhel-var", "fstype": "xfs", "label": null, "uuid": "c1bdbeb8-7e26-4c07-9f8a-a540cd0f51ea", "mountpoint": "/var"},
                  {"name": "rhel-var_tmp", "fstype": "xfs", "label": null, "uuid": "c75373ce-509e-4d1e-959f-2fe01f8f5ab7", "mountpoint": "/var/tmp"},
                  {"name": "rhel-var_log", "fstype": "xfs", "label": null, "uuid": "aa13efc4-ad4c-4980-a141-8d6acf0c9024", "mountpoint": "/var/log"},
                  {"name": "rhel-var_log_audit", "fstype": "xfs", "label": null, "uuid": "2068d8d6-558e-475f-8f5a-5eea3199390f", "mountpoint": "/var/log/audit"},
                  {"name": "rhel-home", "fstype": "xfs", "label": null, "uuid": "7e544173-4d90-4e38-b3db-fcb407768c43", "mountpoint": "/home"}
               ]
            }
         ]
      }
   ]
}

使用这个 ansible 代码,它不会打印 chalder 输出

- name: get the disk output
  command: lsblk -f  -J /dev/sda
  register: cmdout

- name: dispaly output
  debug:
    msg: "out {{ cmdout.stdout | json_query('entry[*].children') }}" 

如何从上面的输出中获取 root 设备的 uuid?

谢谢

要查找安装在根目录 (/) 的磁盘的 UUID,我们可以有一个 JSON 查询,如:

- name: display output
  debug:
    msg: "out {{ cmdout.stdout | from_json | json_query(jquery) | flatten | first }}"
  vars:
    jquery: "blockdevices[].children[].children[?mountpoint == '/'].uuid"

由于命令的输出是嵌套数组,我使用了 flattenfirst 过滤器来获取字符串值。

如果你gather_facts,你也可以如下使用它:

- name: display output
  debug:
    msg: "out {{ ansible_mounts | json_query(jquery) | first }}"
  vars:
    jquery: "[?mount == '/'].uuid"