使用Ansible循环修改文件权限

71次阅读
没有评论

问题描述

想要使用Ansible来移除一些Ubuntu motd(每日消息)文件的执行权限,以禁用一些类似广告的Ubuntu新闻。该模块只有在文件存在且权限错误时才会执行操作。但是,当存在文件时,用户遇到了以下错误信息:

failed: [ip] (item={'_ansible_parsed': True, u'stat': {u'isuid': False, u'uid': 0, u'exists': True, u'attr_flags': [... redacted the rest of the file attributes from stat ...]

请问有人可以帮忙解决吗?

解决方案

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

方案

以下是一个使用Ansible循环修改文件权限的任务示例:

- name: Register unwanted motd files
  stat:
    path: "{{motd_path}}/{{item}}"
  register: filecheck
  with_items: "{{ unwanted_motd_files | default([]) }}"
- name: Check if unwanted motd files are executable and remove the executable bit
  file:
    path: "{{motd_path}}/{{item.item}}"
    state: touch
    mode: u-x,g-x,o-x
  with_items: "{{ filecheck.results }}"
  when: item.stat.exists == true and item.stat.executable == True

在上面的示例中,我们首先使用stat模块来检查不需要的motd文件是否存在,并将结果注册到filecheck变量中。然后,我们使用file模块来修改文件权限,将可执行位移除。这里使用了循环with_items来遍历filecheck.results,并使用when条件来过滤只有文件存在且可执行的文件。

请注意,你需要将{{motd_path}}{{unwanted_motd_files}}替换为你实际的路径和文件列表。

希望这个解决方案对你有帮助!

正文完