如何在Ansible中比较多个文件

问题描述 投票:0回答:1

我正在尝试找到一种方法,可以将一个目录中的多个文件与另一个目录中的文件进行比较。例如-目录/ home / ansible / properties /中有10个文件,而远程主机(如/ opt / apps / properties /)中的另一个目录中有类似的文件集。我想比较每个可能使用校验和的方法,即使其中一个文件被更改,也要执行一些任务-

在我的剧本下面,可以比较一个文件,但是有没有办法比较所有文件或与此相关的目录?

- name: Get checksum of my First file
  stat:
    path : "/home/ansible/properties/my.properties"
  register: myfirstfile

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

- name: Get checksum of my Second File
  stat:
    path : "/opt/aaps/properties/my.properties"
  register: mysecondfile

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

- name: Comparing 2 files
  debug:
    msg: "Do Something....."
  when:  1stFilechecksum != 2ndFilechecksum
ansible ansible-inventory
1个回答
0
投票

根据您的描述测试文件树

...或至少我从中了解。

/tmp/test/a          /tmp/test/b
├── file10.txt       ├── file10.txt
├── file1.txt        ├── file1.txt
├── file2.txt        ├── file2.txt
├── file3.txt        ├── file3.txt
├── file4.txt        ├── file4.txt
├── file5.txt        ├── file5.txt
├── file6.txt        ├── file6.txt
├── file7.txt        ├── file7.txt
├── file8.txt        ├── file8.txt
├── file9.txt        ├── file9.txt
└── toto.txt         └── titi.txt

您可以看到,除了每个目录中的文件以外,所有文件都是公用的。这些将被排除在比较之外。对于通用文件,除了file2.txtfile5.txt具有相同的内容之外,所有其他文件都是不同的。

用于解决方案的基础

  • 我们以find循环搜索两个目录中的所有文件。 find中的所有文件都在a中,results[0]中的b中的文件都在。 results[1]选项收集我们所需的信息。
  • 在下一个任务中:
    • 我们循环搜索get_checksum中找到的文件。
    • [在每次迭代中,我们通过替换[dir]路径后仅用a选择具有相同b名称的列表元素来计算selectattr中的相应文件。保留结果的第一个元素将得到我们的文件。如果结果为空(不是通用文件),则默认为空对象
    • when子句检查文件是否存在(常见的是我们跳过)并且它们是否不同(校验和不相等)
    • selectattr用于自定义循环变量名称以提高可读性(即item => file1),并将循环项的输出限制为易于理解的形式。

剧本

path

结果

loop_control
© www.soinside.com 2019 - 2024. All rights reserved.