限制“已更改”输出或优化剧本输出

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

这里有一些根据某些条件查找文件的代码(在本示例中,文件大于 >=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] => ...”橙色文本,并且剧本输出是一堵文本墙。是否有适当的方法来控制和限制输出?或者有更好的方法来编写剧本吗?

ansible ansible-2.x
2个回答
2
投票

根据我猜测您正在寻找的内容,以下内容应该符合您(猜测的)要求:

    - 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')

进一步解决您帖子中提出的一些问题:

  1. 当有模块已经完成您期望的工作时,您不应该使用
    ansible.builtin.shell
  2. 如果您仍然需要使用
    ansible.builtin.shell
    ,正如@4snok已经提出的那样,默认情况下它不是幂等的。您必须自己管理幂等性。请参阅定义已更改
  3. 你原来的剧本中的基本问题是(我猜)
    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 }}"
      

1
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.