如何在Ansible剧本中阻止修改指定系统目录权限并抛出错误提示
Got it, let's fix your playbook to prevent accidental changes to those sensitive system directories. The core idea is to add a safeguard check that runs before any other tasks—if the target directory matches one of your forbidden paths, the playbook will immediately fail with a clear error message.
Step-by-Step Modifications
First, we'll add a list of forbidden system directories to your vars section, then add a task that validates if the provided target_dir is in that list.
Here's the updated playbook with the safeguard included:
- name: Playbook to change file and directory permissions hosts: all become: yes vars: # Define forbidden system directories here forbidden_dirs: - "/boot" - "/var" - "/etc" - "/tmp" - "/usr" DIR: '{{ target_dir }}' FILE: '{{ target_file }}' PERMISSIONS: '{{ number }}' OWNER: '{{ target_owner }}' GROUP: '{{ target_group }}' tasks: # Critical safeguard: Block forbidden system directories first - name: Validate target directory is not a restricted system path fail: msg: "❌ ERROR: Modifying permissions on restricted system directory '{{ DIR }}' is strictly prohibited!" when: DIR in forbidden_dirs # Your existing tasks follow below - 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 }}'
How This Works
- Forbidden List Definition: We added
forbidden_dirsto your variables, listing all the system paths you want to protect. You can easily add/remove paths here later if needed. - Early Validation Task: The first task checks if the user-provided
target_dir(passed via Rundeck) is in the forbidden list. If it matches, thefailmodule triggers immediately, stopping the playbook and printing a clear error message. - Preserves Existing Functionality: All your original tasks remain intact—they'll only run if the target directory passes the safeguard check.
Testing This Safeguard
If someone tries to run the playbook with target_dir=/etc via Rundeck, Ansible will output something like this and exit:
TASK [Validate target directory is not a restricted system path] **************** fatal: [your-server]: FAILED! => {"changed": false, "msg": "❌ ERROR: Modifying permissions on restricted system directory '/etc' is strictly prohibited!"}
This ensures no accidental changes to those critical system directories.
内容的提问来源于stack exchange,提问作者Fede Berbara

