Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Use of Diff command using Ansible

Tags:

ansible

I am trying to one simple task which is find out the difference between the two files and store it in notepad. I am not able to do it with command as well as shell. Please suggest where i am going wrong-

---
- hosts: myserver
  tasks:
   - name: get the difference
     command: diff hosts.new hosts.mod
     register: diff
   - debug: var=diff.cmd

Error -

fatal: [zlp12037]: FAILED! => {"changed": true, "cmd": ["diff", "hosts.new", "hosts.mod"], "delta": "0:00:00.003102", "end": "2017-03-29 10:17:34.448063", "failed": true, "rc": 1, "start": "2017-03-29 10:17:34.444961", "stderr": "", "stdout":
like image 218
nishant Avatar asked Mar 29 '17 14:03

nishant


2 Answers

I'm not quite sure what your input play looks like with your formatting. But the following should be a solution:

- name: "Get difference from two files"
  command: diff filea fileb
  args:
    chdir: "/home/user/"
  failed_when: "diff.rc > 1"
  register: diff
- name: debug output
  debug: msg="{{ diff.stdout }}"

Some explanation:

  • If something fails with the diff command, the return code is > 1. We evaluate this by the "failed_when".
  • To get the output of the command, we print the ".stdout" element.
  • To make sure we're in the folder where the files are, we use "chdir".
like image 105
iptizer Avatar answered Nov 11 '22 21:11

iptizer


I would move the hosts.new or hosts.mod to the ansible control machine.

Run the copy module with the src as hosts.new and the dest as hosts.mod with --check and --diff. I find this method most useful to spot differences in files across a large enterprise.

Run:

ansible all -m copy -a "src=hosts.new dest=/tmp/hosts.mod" --check --diff -i hosts

Output:

--- before: /tmp/hosts.mod
+++ after: /home/ansible/hosts.new
@@ -1,5 +1,5 @@
 host1
+host2
 host3
 host4
-host6
-host99
+host5

test10 | SUCCESS => {
    "changed": true, 
    "failed": false
}
like image 34
ToughKernel Avatar answered Nov 11 '22 22:11

ToughKernel