Ansible Find模块如何使用

48次阅读
没有评论

问题描述

想要使用Ansible的find模块创建一个文件列表,然后将该列表传递给file模块,以更改特定用户拥有的目录中的文件的文件权限。然而,Ansible的find模块似乎不允许使用所有者或组作为搜索条件。除了所有者之外,文件没有其他可以区分的特征。用户想知道是否有可能实现这个需求,或者是否必须使用shell模块来实现。

解决方案

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

方案1

你可以尝试使用Ansible的stat模块与find模块的文件列表进行循环。stat模块将为你提供pw_name键,该键可以用于有条件地运行file模块。
以下是一个示例的Ansible Playbook:

- name: Change file permissions
  hosts: your_hosts
  tasks:
    - name: Find files owned by specific user
      find:
        paths: /path/to/directory
        file_type: file
        owner: specific_user
      register: found_files

    - name: Change file permissions
      file:
        path: "{{ item.path }}"
        owner: specific_user
        group: specific_group
        mode: specific_mode
      loop: "{{ found_files.files }}"
      when: item.stat.pw_name == 'specific_user'

在上面的示例中,我们首先使用find模块查找特定用户拥有的文件,并将结果存储在found_files变量中。然后,我们使用file模块循环遍历found_files.files列表,并根据条件item.stat.pw_name == 'specific_user'来更改文件的权限。
请注意,你需要将your_hosts替换为你的目标主机,将/path/to/directory替换为目标目录的路径,将specific_user替换为特定用户的用户名,将specific_group替换为特定组的组名,将specific_mode替换为特定的文件权限模式。

方案2

使用command模块运行find命令来确定哪些文件属于所需用户,将它们放入一个寄存器,并使用with_items将该寄存器传递给file模块。
另一种方法是使用command模块运行find命令来确定哪些文件属于所需用户,将它们放入一个寄存器,并使用with_items将该寄存器传递给file模块。
以下是一个示例的Ansible Playbook:

- name: Change file permissions
  hosts: your_hosts
  tasks:
    - name: Find files owned by specific user
      command: find /path/to/directory -type f -user specific_user
      register: found_files

    - name: Change file permissions
      file:
        path: "{{ item }}"
        owner: specific_user
        group: specific_group
        mode: specific_mode
      with_items: "{{ found_files.stdout_lines }}"

在上面的示例中,我们使用command模块运行find命令来查找特定用户拥有的文件,并将结果存储在found_files变量中。然后,我们使用file模块循环遍历found_files.stdout_lines列表,并根据需要更改文件的权限。
请注意,你需要将your_hosts替换为你的目标主机,将/path/to/directory替换为目标目录的路径,将specific_user替换为特定用户的用户名,将specific_group替换为特定组的组名,将specific_mode替换为特定的文件权限模式。

正文完