用Ansible比较两个文件

时间:2018-05-30 16:17:05

标签: ansible

我正在努力找出如何比较两个文件。尝试了几种方法,包括错误输出的方法:

  

失败! => {“msg”:“在配置的模块路径中找不到模块差异。此外,缺少核心模块。如果是这样的话   结帐,运行'git pull --rebase'来解决此问题。“}

这是比较两个文件并确保内容相同或有更好方法的最佳做法吗?

提前致谢。

我的剧本:

- name: Find out if cluster management protocol is in use
      ios_command:
        commands:
          - show running-config | include ^line vty|transport input
      register: showcmpstatus
 - local_action: copy content="{{ showcmpstatus.stdout_lines[0] }}" dest=/poc/files/{{ inventory_hostname }}.result
    - local_action: diff /poc/files/{{ inventory_hostname }}.result /poc/files/transport.results
      failed_when: "diff.rc > 1"
      register: diff
 - name: debug output
      debug: msg="{{ diff.stdout }}"

3 个答案:

答案 0 :(得分:4)

为什么不使用stat来比较这两个文件? 只是一个简单的例子:

- name: Get cksum of my First file
  stat:
    path : "/poc/files/{{ inventory_hostname }}.result"
  register: myfirstfile

- name: Current SHA1
  set_fact:
    mf1sha1: "{{ myfirstfile.stat.checksum }}"

- name: Get cksum of my Second File (If needed you can jump this)
  stat:
    path : "/poc/files/transport.results"
  register: mysecondfile

- name: Current SHA1
  set_fact:
    mf2sha1: "{{ mysecondfile.stat.checksum }}"

- name: Compilation Changed
  debug:
    msg: "File Compare"
  failed_when:  mp2sha1 != mp1sha1

答案 1 :(得分:2)

您的“差异”任务缺少shell关键字,Ansible认为您想要使用diff模块。

我认为diff(作为注册任务结果的变量的名称)导致混淆,变为diff_result或其他东西。

代码(示例):

  tasks:
  - local_action: shell diff /etc/hosts /etc/fstab
    failed_when: "diff_output.rc > 1"
    register: diff_output

  - debug:
      var: diff_output

希望有所帮助

答案 2 :(得分:0)

'imjoseangel' 答案的略微缩短版本,可避免设定事实:

  vars:
    file_1: cats.txt
    file_2: dogs.txt

  tasks:
  - name: register the first file
    stat:
      path: "{{ file_1 }}"
      checksum: sha1
      get_checksum: yes
    register: file_1_checksum

  - name: register the second file
    stat:
      path: "{{ file_2 }}"
      checksum: sha1
      get_checksum: yes
    register: file_2_checksum

  - name: Check if the files are the same
    debug: msg="The {{ file_1 }} and {{ file_2 }} are identical"
    failed_when: file_1_checksum.stat.checksum != file_2_checksum.stat.checksum
    ignore_errors: true