这里有一些根据某些条件查找文件的代码(在本示例中,文件大于 >=40k)。
---
- hosts: nodes
become: true
vars_files: my_vars.yml
vars:
where: "/etc"
what: "*.conf"
tasks:
- name: Find all files greater than 40k
ansible.builtin.find:
paths: "{{where}}"
size: 40k
recurse: yes
register: output
- name: Output the above
ansible.builtin.shell:
"echo {{item.path}} >> testfile3"
loop: "{{output['files']|flatten(1)}}"
现在,它“成功”运行,但它会抛出一堆“已更改:[host1] => ...”橙色文本,并且剧本输出是一堵文本墙。是否有适当的方法来控制和限制输出?或者有更好的方法来编写剧本吗?
根据我猜测您正在寻找的内容,以下内容应该符合您(猜测的)要求:
- name: Find all files greater than 40k
ansible.builtin.find:
paths: "{{where}}"
size: 40k
recurse: yes
register: output
- name: "Print the paths to a text file on the target node
(replacing previous output) from the above register"
ansible.builtin.copy:
content: "{{ output.files | map(attribute='path') | join('\n') }}"
dest: /path/to/testfile3
- name: If you're only looking for an output, just debug the list
ansible..builtin.debug:
var: output.files | map(attribute='path')
进一步解决您帖子中提出的一些问题:
ansible.builtin.shell
。ansible.builtin.shell
,正如@4snok已经提出的那样,默认情况下它不是幂等的。您必须自己管理幂等性。请参阅定义已更改loop
的输出(这里绝对不需要)。如果由于某种原因您在最终代码中仍然需要循环,有几种方法可以限制其输出:
- name: Loop on files path in registered result
ansible.builtin.debug:
var: item
loop: "{{ output.files | map(attribute='path') }}"
label
限制循环输出。例子:
- name: Limit loop output
ansible.builtin.debug:
msg: "Checksum of {{ item.path }} is {{ item.checksum }}"
loop: "{{ output.files }}"
loop_control:
label: "{{ item.path }}"
shell 模块不是幂等的。多次执行并不一定每次执行都会产生相同的结果。在您的情况下,每次运行 playbook 时 testfile3 文件的内容都会更改。 您可以使用
changed_when
选项控制此行为。
要抑制任务的输出,请使用“no_log: true”。
tasks:
- name: Find all files greater than 40k
ansible.builtin.find:
paths: "{{where}}"
size: 40k
recurse: yes
register: output
no_log: true
- name: Output the above
ansible.builtin.shell:
"echo {{item.path}} >> testfile3"
loop: "{{output['files']|flatten(1)}}"
changed_when: false