ansible之find module获取某路径下给定文件类型的所有文件名

find - Return a list of files based on specific criteria

官方例子, 例子都比较丰富, 用法就不多介绍了.

1. files - One of the return field

上面的官方文档中仅简单介绍了files是一个列表, 没有其他具体的信息. 下面我们写个例子打印files的值

1.1 show detail value of files

这里以查找上级目录中所有xml的文件名为例子

# get all xml file names
# test.yaml
- name: get all file names
  hosts: localhost
  tasks:
    - name: "Find xml files"
      find:
        paths: "../"
        patterns: "*.xml"
        file_type: "file"
      register: xml_files
    - name: show file names
      debug:
        msg: "{{ xml_files.files }}"

Outputs:

# ansible-playbook test.yaml

TASK [show file names] ******************************
ok: [localhost] => {
    "msg": [
        {
            "atime": 1589590489.4881124,
            "ctime": 1589590478.360112,
            "dev": 64768,
            "gid": 0,
            "gr_name": "root",
            "inode": 34430340,
            "isblk": false,
            "ischr": false,
            "isdir": false,
            "isfifo": false,
            "isgid": false,
            "islnk": false,
            "isreg": true,
            "issock": false,
            "isuid": false,
            "mode": "0644",
            "mtime": 1589590478.360112,
            "nlink": 1,
            "path": "../test.xml",
            "pw_name": "root",
            "rgrp": true,
            "roth": true,
            "rusr": true,
            "size": 0,
            "uid": 0,
            "wgrp": false,
            "woth": false,
            "wusr": true,
            "xgrp": false,
            "xoth": false,
            "xusr": false
        },
        {...}
    ]
}

1.2 How to get file name with find module in ansible

笔者遇上一个需求, 就是在ansible中找出某个目录下所有的xml文件. 从上面的执行结果可以知道, 文件名在files的path里面可以获取. Jinja2中的filter variable可以实现.

# get file name
# test.txt.j2
# xml_files 是之前注册的变量名字
{% for item in xml_files.files %}
  {{ item.path|basename }}
{% endfor %}

# test.yaml
- name: get all file names
  hosts: localhost
  tasks:
    - name: "Find xml files"
      find:
        paths: "../"
        patterns: "*.xml"
        file_type: "file"
      register: xml_files
    - name: show file names
      debug:
        msg: "{{ xml_files.files }}"

    - name: "get file names into file"
      template:
        src: test.txt.j2
        dest: file_names.txt

Outputs:

# ansible-playbook test.yaml
# cat file_names.txt
 test.xml
 xxxx.xml
 ....

1.3 Thinking — 上面获取文件名是带后缀的, 那怎么把后缀去掉仅保留名字呢???

  • linux shell
    • sed
  • ansible filter
    • splitext
    • items2dict
  • python script
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值