如何在Ansible中对比远程主机的两个配置文件?
报错根本原因
你使用的<()是Bash进程替换语法,但Ansible的shell模块默认调用远程主机的/bin/sh执行命令,绝大多数Linux发行版的/bin/sh为精简的dash或busybox shell,不支持进程替换特性,因此会抛出括号语法错误。
解决方案
方案1:显式指定Bash执行(最便捷)
给shell模块新增executable: /bin/bash参数,强制用Bash运行命令即可兼容进程替换语法,修改后任务代码如下:
- name: compare files shell: diff -u -bB <(grep -vE '^@\s*(@#|$)' /tmp/{{myloopfile_list | basename }}) <(grep -vE '^@\s*(@#|$)' {{myloopfile_list}}) | awk '{if ($1 ~ /^-|+/ ) print $0;}' executable: /bin/bash failed_when: "diff_output.rc > 1" register: diff_output
方案2:兼容sh的改写方式(无Bash依赖)
如果远程主机没有安装Bash,可以先把两个文件过滤后的内容存到临时文件再做对比:
- name: 过滤第一个文件内容 shell: grep -vE '^@\s*(@#|$)' /tmp/{{myloopfile_list | basename }} > /tmp/filter_file1.tmp - name: 过滤第二个文件内容 shell: grep -vE '^@\s*(@#|$)' {{myloopfile_list}} > /tmp/filter_file2.tmp - name: 对比过滤后的文件 shell: diff -u -bB /tmp/filter_file1.tmp /tmp/filter_file2.tmp | awk '{if ($1 ~ /^-|+/ ) print $0;}' failed_when: "diff_output.rc > 1" register: diff_output - name: 清理临时文件 shell: rm -f /tmp/filter_file1.tmp /tmp/filter_file2.tmp always: true
内容的提问来源于stack exchange,提问作者Tumentsatsral Badraa
相关产品推荐
相关产品推荐

