我目前正在尝试比较一堆文件,然后记录已更改文件之间的差异。我首先参考了这篇文章:Compare two files with Ansible,并省略了任务的最后一部分,就像这样:
- name: Get cksum of the first file
stat:
path: "baselinedFiles/{{ inventory_hostname }}/file"
checksum_algorithm: sha1
get_checksum: yes
register: myfristfile
delegate_to: localhost
- name: Current SHA1 p1
set_fact:
mf1sha1: "{{ myfristfile.stat.checksum }}"
delegate_to: localhost
- name: Get cksum of second file
stat:
path: "tmpFiles/{{ inventory_hostname }}/file"
checksum_algorithm: sha1
get_checksum: yes
register: mysecondfile
delegate_to: localhost
- name: Current SHA1 p2
set_fact:
mf2sha1: "{{ mysecondfile.stat.checksum }}"
delegate_to: localhost
以上只是获取SHA1,因此我们将来在将diff写入文件时可以轻松比较它们(我只想在文件不同的情况下写diff)。这按预期工作。
接下来,我跟随difference in two file using ansible module,在这里我使用check_mode
和diff
来显示我要检查的文件之间的差异。
- name: "Show diff if the hashes are different"
copy:
src: "baselinedFiles/{{ inventory_hostname }}/file"
dest: "tmpFiles/{{ inventory_hostname }}/file"
check_mode: yes
diff: yes
register: diffOutput
delegate_to: localhost
这可行,并给出如下输出:
TASK [diffNlog : Show diff if the hashes are different] *******************************************************************************************************************
ok: [a -> localhost]
ok: [b -> localhost]
ok: [c -> localhost]
ok: [d -> localhost]
--- before: tmpFiles/e/file
+++ after: /home/me/someDir/baselinedFiles/e/file
@@ -78,5 +78,4 @@
#
# End of: blah
#
-#######################
-#THIS IS A CHANGE THAT MIGHT HAVE BEEN MADE
+#######################
\ No newline at end of file
changed: [e -> localhost]
ok: [f -> localhost]
这很好,因为它表明存在变化,变化是什么,这就是我想要的。不幸的是,问题出现在下一步中,实际上,我只是想获得粘贴的上述输出并将其输出到文件中,以便可以轻松查看。我尝试通过这种方式做到这一点:
- local_action: shell echo "{{ diffOutput }}" > logs/mytestlog
when: mf1sha1 != mf2sha1
delegate_to: localhost
become: true
become_user: me
这是我遇到逻辑问题的地方。它可以很好地完成工作,但是会将文件1和2的全部内容放入日志文件,然后显示更改。这是我不需要的过多不必要的输出。然后,我尝试了以下解决方案:Ansible playbook shell output,在其中使用调试的地方,但不幸的是,我继续遇到此错误:
"The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout_lines'
似乎我从diff
的输出中保存的变量没有stdout_lines
属性。就像我之前说的,我只想将ansible在运行剧本时显示的输出记录到您的控制台中,但是我被困在这里。
任何帮助将不胜感激。 谢谢
答案 0 :(得分:1)
可以使用文件 before
和 after
- set_fact:
my_diff: "{{ diffOutput.diff.0.before|list|
difference(diffOutput.diff.0.after|list) }}"
要获取 diffOutput.stdout_lines
,请使用command
- command: "diff {{ file1 }} {{ file2 }}"
register: diffOutput
ignore_errors: yes