如何使用ansible排除文件系统

How to exclude filesystems with ansible

我正在编写一个剧本来更改 Linux 服务器上的文件和文件夹权限。 直到知道它正在工作并且看起来像这样:

-
  name: Playbook to change file and directory permissions
  hosts: all
  become: yes
  vars:
    DIR: '{{ target_dir }}'
    FILE: '{{ target_file }}'
    PERMISSIONS: '{{ number }}'
    OWNER: '{{ target_owner }}'
    GROUP: '{{ target_group }}'

  tasks:

    - name: Checking if the directory exists
      stat:
        path: '{{ DIR }}'
      register: dir_status

    - name: Checking if the file exists
      stat:
        path: '{{ FILE }}'
      register: file_status

    - name: Report if directory exists
      debug:
        msg: "Directory {{ DIR }} is present on the server"
      when: dir_status.stat.exists and dir_status.stat.isdir

    - name: Report if file exists
      debug:
        msg: "File {{ FILE }} is present on the server"
      when: file_status.stat.exists

    - name: Applying new permissions
      file:
          path: '{{ DIR }}/{{ FILE }}'
          state: file
          mode: '0{{ PERMISSIONS }}'
          owner: '{{ OWNER }}'
          group: '{{ GROUP }}'

但我需要的是,如果要在 rundeck 中执行剧本的用户想要更改 (/boot /var /etc /tmp /usr) 目录的权限,告诉 ansible 不要尝试这样做并抛出错误消息.

我该怎么做?

我理解你的问题,你想 fail with custom message when 变量 DIR 包含值 /boot/var/etc/tmp/usr.

为此,您可以使用

- name: You can't work on {{ DIR }}
  fail:
    msg: The system may not work on {{ DIR }} according ...
   when: '"/boot" or "/var" or "/etc" or "/tmp" or "/usr" in DIR'

还有一个meta_module,当条件满足时可以end_play

  tasks:
  - meta: end_play
    when: '"/boot" or "/var" or "/etc" or "/tmp" or "/usr" in DIR'

failend_play,您可以针对某些用例结合不同的变量。

when: "'download' or 'unpack' in ansible_run_tags"
when: ( "DMZ" not in group_names )

感谢

  • Run an Ansible task only when the variable contains a specific string
  • Ansible - Execute task when variable contains specific string

请注意,您正在通过在末尾连接 {{ DIR }}/{{ FILE }} 来构建完整路径。上面提到的简单方法不会处理包含路径的空 DIRFILEname。测试用例可以是

DIR: ""
FILE "/tmp/test"

DIR: "/"
FILE: "tmp/test"

也许您想在完整文件路径或 .

上执行测试

关于 Zeitounator and seshadri-c you may also try the approach of the assert_module

的评论
- name: Check for allowed directories
  assert:
    that:
      -  DIR in ["/boot", "/etc", "/var", "/tmp", "/usr"]
    quiet: true
    fail_msg: "The system may not work on {{ DIR }} according ..."
    success_msg: "Path is OK."