如何加速循环执行的Ansible批量TXT文件备份copy任务?
优化Ansible大批量文件备份的执行效率问题
问题场景
我使用以下Ansible Playbook备份/opt/cusfiles/目录下所有*.txt文件:
--- - name: Backup txt files hosts: remotehost become: true tasks: - name: List txt files in /opt/cusfiles/ find: paths: /opt/cusfiles/ patterns: '*.txt' register: txt_files - name: Backup txt files copy: src: "{{ item.path }}" dest: "{{ item.path }}.bkp" with_items: "{{ txt_files.files }}"
在Ansible Tower上运行时,当待备份文件数量超过500个,任务耗时超25分钟。改用raw模块执行cp命令:
raw: "cp {{ item.path }} {{ item.path }}.bkp"
任务仍需15-20分钟完成,希望找到进一步缩短执行时间的方法。
核心原因
Ansible默认会对每个文件发起一次远程调用,500个文件就产生500次远程交互,这是耗时的主要根源。要提速必须减少远程调用次数,将批量操作合并为单次远程执行。
优化方案
1. 单条shell命令批量备份(最优解)
直接在远程主机上执行批量备份命令,仅需一次远程调用即可完成所有文件备份:
- 基础版(支持递归子目录):
- name: Batch backup all txt files shell: find /opt/cusfiles/ -type f -name '*.txt' -exec cp {} {}.bkp \; become: true
- 高效版(用xargs减少进程创建开销):
- name: Batch backup with xargs shell: find /opt/cusfiles/ -type f -name '*.txt' | xargs -I {} cp {} {}.bkp become: true
- 兼容带空格的文件路径:
- name: Space-safe batch backup shell: find /opt/cusfiles/ -type f -name '*.txt' -print0 | xargs -0 -I {} cp {} {}.bkp become: true
2. 调整Ansible并发参数(多主机场景)
如果是多主机备份,可在Ansible Tower中调整forks参数(默认值为5),提升并行执行的主机数量。但该参数对单主机任务的执行速度无影响。
3. 增量备份场景用sync模块
若后续需要增量备份,sync模块仅复制变化的文件,首次备份速度与copy相当,但后续备份效率会大幅提升:
- name: Incremental sync backup for txt files sync: src: /opt/cusfiles/ dest: /opt/cusfiles_bkp/ rsync_opts: - "--include=*.txt" - "--exclude=*" become: true
注:该方案是将所有*.txt文件同步到单独的备份目录,而非在原文件后添加.bkp后缀,适合目录级备份需求。
内容的提问来源于stack exchange,提问作者Ashar
相关产品推荐
相关产品推荐

