简体   繁体   中英

Compare two files with Ansible

I am struggling to find out how to compare two files. Tried several methods including this one which errors out with:

FAILED! => {"msg": "The module diff was not found in configured module paths. Additionally, core modules are missing. If this is a checkout, run 'git pull --rebase' to correct this problem."}

Is this the best practice to compare two files and ensure the contents are the same or is there a better way?

Thanks in advance.

My playbook:

- 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 }}"

Why not using stat to compare the two files? Just a simple example:

- 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:  mf2sha1 != mf1sha1

your "diff" task is missing the shell keyword, Ansible thinks you want to use the diff module instead.

also i think diff (as name of the variable to register the tasks result) leads ansible to confusion, change to diff_result or something.

code (example):

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

  - debug:
      var: diff_output

hope it helps

A slightly shortened version of 'imjoseangel' answer which avoids setting facts:

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM