首页 > 解决方案 > 如何过滤 Ansible 的“查找”输出

问题描述

我想在终端中查看来自一些远程服务器的符号链接列表,但是当我运行 playbook 时会打印很多信息。

这是在 Ubuntu 服务器上运行的 ansible 2.7.12。我正在使用 'find' 模块和 file_type: link 来获取软链接详细信息。

Find 使用返回值键“文件”返回了很多详细信息,但我只需要终端中的软链接和相应的服务器名称。

---
# tasks file for application
- name: Get the current applications running
  find:
    paths: /path/to/app
    file_type: link
  register: find_result

- name: Print find output
  debug: 
    var: find_result.results

实际结果:

ok: [client3.example.com] => {
    "find_result.files": [
        {
            "atime": 1559027986.555, 
            "ctime": 1559027984.828, 
            "dev": 64768, 
            "gid": 0, 
            "gr_name": "root", 
            "inode": 4284972, 
            "isblk": false, 
            "ischr": false, 
            "isdir": false, 
            "isfifo": false, 
            "isgid": false, 
            "islnk": true, 
            "isreg": false, 
            "issock": false, 
            "isuid": false, 
            "mode": "0777", 
            "mtime": 1559027984.828, 
            "nlink": 1, 
            "path": "/path/to/app/softlink.1", 
            "pw_name": "root", 
            "rgrp": true, 
            ...
            ...

想在终端中获得一些过滤后的输出,例如:

ok: [client3.example.com] => {
    "find_result.files": [
        {
            "path": "/path/to/app/softlink.1",
},

标签: ansible

解决方案


有几种方法可以解决这个问题。您可以使用map过滤器path从结果中仅提取属性:

- name: Print find output
  debug:
    var: results.files|map(attribute='path')|list

鉴于您问题中的示例数据,这将导致:

TASK [Print find output] *****************************************************************************************************************************************************
ok: [localhost] => {
    "results.files|map(attribute='path')|list": [
        "/path/to/app/softlink.1"
    ]
}

您还可以使用过滤器完成类似的操作,该json_query过滤器将JMESPath查询应用于您的数据:

- name: Print find output
  debug:
    var: results.files|json_query('[*].path')

推荐阅读