如何在多服务器全分区查找指定文件并生成目标服务器列表
使用Ansible批量搜索多分区服务器中的特定文件
要实现遍历服务器所有挂载分区查找目标文件,并汇总存在该文件的服务器列表,可按以下步骤修改Ansible脚本:
1. 获取服务器所有挂载分区
先用command模块执行系统命令获取所有挂载点,可按需过滤掉系统临时挂载(如/dev、/sys等):
- name: 获取所有挂载分区 command: df -P | awk 'NR>1 && $6 !~ /^\/dev|\/sys|\/proc|\/run|\/tmp/ {print $6}' register: mount_points changed_when: false
changed_when: false用于避免Ansible误判此操作产生了变更
2. 遍历所有挂载点搜索目标文件
使用loop遍历所有挂载点,对每个路径下的.file执行存在性检查:
- name: 遍历挂载点搜索目标文件 stat: path: "{{ item }}/.file" register: file_check_results loop: "{{ mount_points.stdout_lines }}"
3. 提取并汇总存在文件的服务器及路径
通过set_fact收集所有符合条件的记录,最后统一输出结果:
- name: 收集存在目标文件的记录 set_fact: found_files: "{{ found_files | default([]) + [{'server': inventory_hostname, 'path': item.item + '/.file'}] }}" when: item.stat.exists loop: "{{ file_check_results.results }}" loop_control: label: "{{ item.item }}" - name: 输出存在目标文件的服务器列表 debug: msg: "{{ found_files }}" when: found_files is defined
完整Playbook示例
- name: 批量搜索多分区服务器中的特定文件 hosts: all gather_facts: false tasks: - name: 获取所有挂载分区 command: df -P | awk 'NR>1 && $6 !~ /^\/dev|\/sys|\/proc|\/run|\/tmp/ {print $6}' register: mount_points changed_when: false - name: 遍历挂载点搜索目标文件 stat: path: "{{ item }}/.file" register: file_check_results loop: "{{ mount_points.stdout_lines }}" - name: 收集存在目标文件的记录 set_fact: found_files: "{{ found_files | default([]) + [{'server': inventory_hostname, 'path': item.item + '/.file'}] }}" when: item.stat.exists loop: "{{ file_check_results.results }}" loop_control: label: "{{ item.item }}" - name: 输出存在目标文件的服务器列表 debug: msg: "{{ found_files }}" when: found_files is defined
说明
- 若需要保留所有系统挂载点,可删除
awk命令中的过滤规则,仅保留NR>1 {print $6} gather_facts: false关闭默认的facts收集以提升执行速度,若需用到系统信息可开启- 最终的
found_files变量会包含所有存在目标文件的服务器名称及对应文件路径,可按需将结果输出到文件或进一步处理
内容的提问来源于stack exchange,提问作者stixu
相关产品推荐
相关产品推荐

