find 总是会返回一个文件列表。
如果您确定您的find 只会匹配单个文件,您可以复制您的文件以获取第一个元素(因此在files 数组中的位置0),然后获取它的path。
- copy:
src: "{{ file_name.files.0.path }}"
dest: /home/usr/Desktop/myinfo/new.txt
remote_src: yes
为了进一步调试,您可以这样做:
- debug:
msg: "{{ file_name }}"
为了查看变量file_name 的结构并更正您的剧本。
在你的情况下,这会产生你:
ok: [localhost] => {
"msg": {
"changed": false,
"examined": 0,
"failed": false,
"files": [],
"matched": 0,
"msg": "/home/usr/Desktop/files/info.txt was skipped as it does not seem to be a valid directory or it cannot be accessed\n"
}
}
因为,/home/usr/Desktop/files/info.txt 不是路径,而是文件。
所以你也应该更正你的find 任务:
- find:
paths: '/home/usr/Desktop/files/'
use_regex: yes
pattern: (info)
file_type: file
register: file_name
这次调试会产生:
ok: [localhost] => {
"msg": {
"changed": false,
"examined": 1,
"failed": false,
"files": [
{
"atime": 1593535103.2879748,
"ctime": 1593535103.2879748,
"dev": 112,
"gid": 0,
"gr_name": "root",
"inode": 2360831,
"isblk": false,
"ischr": false,
"isdir": false,
"isfifo": false,
"isgid": false,
"islnk": false,
"isreg": true,
"issock": false,
"isuid": false,
"mode": "0644",
"mtime": 1593535103.2879748,
"nlink": 1,
"path": "/home/usr/Desktop/files/info.txt",
"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
}
],
"matched": 1,
"msg": ""
}
}
然后调试file_name.files.0.path
- debug:
msg: "{{ file_name.files.0.path }}"
会成功
ok: [localhost] => {
"msg": "/home/usr/Desktop/files/info.txt"
}
这就是说,正如您的问题所写,您不需要查找,您可以这样做:
- copy:
src: home/usr/Desktop/files/info.txt
dest: /home/usr/Desktop/myinfo/new.txt
remote_src: yes