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