在Ansible中如何让find模块正常工作

36次阅读
没有评论

问题描述

在使用Ansible时遇到了问题,他的playbook没有创建预期的/tmp/results.txt文件,但他希望playbook能够使用find模块的结果来生成该文件。以下是他的playbook示例:

- name: Do stuff
  become: yes
  hosts: fun
  tasks:
  - name: Delete directory
    find:
      paths: /home/jdoe/subdir
      patterns: "jj*jj"
      use_regex: yes
    register: find_results
  - shell: "echo {{ item.path }} > /tmp/results.txt"
    with_items: "{{ find_results.files }}"

用户希望在标记为”fun”的托管节点上操作位于/home/jdoe/subdir/jj3jj/目录下的文件。但是他的playbook似乎有问题,导致无法如预期地生成文件。我们来看一下这个问题的解决方案。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

在你的playbook中,问题出在use_regex: yes这一行。根据Ansible文档,如果将use_regex设置为true,则模式将被解释为Python正则表达式,而不是文件通配符。如果你希望使用文件通配符,则应该将use_regex设置为false

另外,你可能希望使用>>来将内容附加到文件而不是覆盖它。以下是经过修正的playbook:

- name: Do stuff
  become: yes
  hosts: fun
  tasks:
  - name: Delete directory
    find:
      paths: /home/jdoe/subdir
      patterns: "jj*jj"
      use_regex: false  # 将use_regex设置为false
    register: find_results
  - shell: "echo {{ item.path }} >> /tmp/results.txt"  # 使用>>来附加内容到文件
    with_items: "{{ find_results.files }}"

通过将use_regex设置为false,模式将被解释为文件通配符,而不是Python正则表达式。并且使用>>将每个文件的路径附加到/tmp/results.txt文件中。

方案2

如果你确实想使用Python正则表达式,那么你需要正确编写正则表达式。假设你的目标是匹配以jj开头和以jj结尾的文件,可以使用以下正则表达式:'[j]{2}.*[j]{2}$'。你的playbook将需要相应地调整:

- name: Do stuff
  become: yes
  hosts: fun
  tasks:
  - name: Delete directory
    find:
      paths: /home/jdoe/subdir
      patterns: "[j]{2}.*[j]{2}$"  # 使用Python正则表达式匹配文件
      use_regex: true
    register: find_results
  - shell: "echo {{ item.path }} >> /tmp/results.txt"
    with_items: "{{ find_results.files }}"

请注意,使用Python正则表达式需要正确的语法,你需要根据你的需求编写合适的正则表达式模式。

方案3

如果你需要确保/tmp/results.txt文件所在的目录存在,可以在任务中添加创建目录的步骤:

- name: Do stuff
  become: yes
  hosts: fun
  tasks:
  - name: Ensure directory exists
    file:
      path: /tmp
      state: directory
  - name: Delete directory
    find:
      paths: /home/jdoe/subdir
      patterns: "jj*jj"
      use_regex: false
    register: find_results
  - shell: "echo {{ item.path }} >> /tmp/results.txt"
    with_items: "{{ find_results.files }}"

在这个示例中,我们首先确保/tmp目录存在,然后继续执行其他任务。

通过以上方案的修正,你应该能够使你的playbook正常工作,生成预期的/tmp/results.txt文件。

在执行任何更改之前,请确保备份你的数据和配置,以免出现意外情况。

正文完