我正在尝试循环遍历目录中的所有文件,这些文件的名称不同,但内容应该相同。有没有办法使用 ansible 循环遍历所有这些文件,然后将唯一文件移动到不同的目录中。
提前致谢
答案1
您可以询问寻找模块来计算校验和。例如,给定文件
shell> tree dir1
dir1
├── a.txt
├── b.txt
├── c.txt
├── d.txt
├── e.txt
└── f.txt
及其内容
shell> find dir1 -type f | sort | xargs cat
123
123
456
789
789
789
下面的剧本
- hosts: localhost
vars:
dir1: "{{ playbook_dir }}/dir1"
dir2: "{{ playbook_dir }}/dir2"
files_unique: "{{ out.files|groupby('checksum')|
map(attribute='1.0.path')|
list }}"
tasks:
- find:
paths: "{{ dir1 }}"
file_type: file
get_checksum: true
register: out
- debug:
var: files_unique
- copy:
src: "{{ item }}"
dest: "{{ dir2 }}"
loop: "{{ files_unique }}"
从目录中复制唯一文件目录1到目录目录2
shell> ansible-playbook pb.yml
PLAY [localhost] *****************************************************************************
TASK [find] **********************************************************************************
ok: [localhost]
TASK [debug] *********************************************************************************
ok: [localhost] =>
files_unique:
- /export/scratch/tmp7/test-033/dir1/a.txt
- /export/scratch/tmp7/test-033/dir1/d.txt
- /export/scratch/tmp7/test-033/dir1/c.txt
TASK [copy] **********************************************************************************
changed: [localhost] => (item=/export/scratch/tmp7/test-033/dir1/a.txt)
changed: [localhost] => (item=/export/scratch/tmp7/test-033/dir1/d.txt)
changed: [localhost] => (item=/export/scratch/tmp7/test-033/dir1/c.txt)
PLAY RECAP ***********************************************************************************
localhost: ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
shell> tree dir2
dir2
├── a.txt
├── c.txt
└── d.txt