Ansible:打印将要复制的文件列表



我有一个剧本,可以将文件从不同的本地文件夹复制到不同的远程路径,它可以工作,配置为用备份覆盖文件(带有复制模块(。如何在执行之前获得将被复制和覆盖的文件列表?我想防止复制错误的文件。

副本示例:

name: Copy all
copy:
src: scenarios/all_machines/
dest: /path/to/dest
backup: yes
force: yes
owner: root
group: root
mode: 0644
when: ansible_facts.services['crowdsec.service'] is defined

更新/strong>

使用此本地文件夹:

scenarios/all_machines/
├── wg-sshd-more-logs.yaml
└── wg-x00.yaml

和这个远程目录:

test_ansible/
└── wg-x00.yaml

其中wg-x00.yaml文件具有相同的内容。

有了这个剧本(我把'>'字符改成了'<'(:

- name: TEST
synchronize:
src: scenarios/all_machines/
dest: test_ansible/
rsync_opts:
- --dry-run
register: result
- debug:
var: result.stdout_lines
- name: TEST 2
set_fact:
overwrite: "{{ file_stat|
selectattr('stat', 'match', '<f.*')|
selectattr('stat', 'ne', '<f+++++++++')|
map(attribute='file')|
list }}"
vars:
file_stat: "{{ result.stdout_lines|
map('regex_replace', regex, replace)|
map('from_yaml')|
list }}"
regex: '^(.*?) (.*)$'
replace: '{file: "2", stat: "1"}'
- debug:
var: overwrite

我有这个输出:

"result.stdout_lines": [
".d..tp..... ./", 
"<f+++++++++ wg-sshd-more-logs.yaml", 
"<f..tp..... wg-x00.yaml"
]

"overwrite": [
"wg-x00.yaml"
]

因此:

  • 我更改了'>'带有'<'的字符因为我的输出与您的不同
  • 覆盖变量告诉我文件将被覆盖,但它们是相等的

给定以下目录用于测试

shell> tree scenarios/all_machines/
scenarios/all_machines/
├── file1
├── file2
└── file3
0 directories, 3 files
shell> tree dest/
dest/
└── file1
0 directories, 1 file

位于dest/的文件file1将被替换。问题是如何找到它。

使用同步并设置"rsync_opts:--dr-run">

- synchronize:
src: scenarios/all_machines/
dest: dest
rsync_opts:
- --dry-run
register: result

结果将显示文件的状态

result.stdout_lines:
- .d..t...... ./
- '>f..t...... file1'
- '>f+++++++++ file2'
- '>f+++++++++ file3'

下方的任务

- set_fact:
overwrite: "{{ file_stat|
selectattr('stat', 'match', '>f.*')|
selectattr('stat', 'ne', '>f+++++++++')|
map(attribute='file')|
list }}"
vars:
file_stat: "{{ result.stdout_lines|
map('regex_replace', regex, replace)|
map('from_yaml')|
list }}"
regex: '^(.*?) (.*)$'
replace: '{file: "2", stat: "1"}'

将创建列表

file_stat:
- {file: ./, stat: .d..t......}
- {file: file1, stat: '>f..t......'}
- {file: file2, stat: '>f+++++++++'}
- {file: file3, stat: '>f+++++++++'}

并且将只选择现有文件的名称

overwrite:
- file1

请参阅理解rsync的输出--逐项列出更改。


票据

  • 使用debug显示变量。例如,使用to_yaml/to_nice_yaml过滤器
- debug:
var: file_stat|to_yaml
- debug:
var: overwrite|to_nice_yaml
  • 使用yaml回调。

  • 有关如何配置回调,请参阅DEFAULT_STDOUT_CALLBACK。

最新更新