请求协助使用Ansible循环重构预检查与后检查的差异对比任务
Your idea to use loops to cut down on repetitive code is spot-on—let's fix that loop structure to make it clean and functional. The key issue with your initial attempt was packing multiple checks into a single loop item; instead, we'll create a separate loop entry for each check we want to run. Here's the revised approach:
First, we'll split the header write into its own task (since it only needs to run once), then use a loop to handle each pre/post check comparison individually. We'll also use cmp -s instead of comparing full file contents with cat—it's faster and more efficient, especially for large files like sysctl.log.
# First, write the header to the global report (matches your original behavior) - name: Add header to global report shell: echo -e "PARAMATER\tCHANGES" >> /root/report.txt # Now the looped difference check task - name: Compare pre/post checks and update host-specific report shell: | # Compare pre and post files efficiently if cmp -s "{{ check_dir }}/{{ item.pre_file }}.log" "{{ check_dir }}/{{ item.post_file }}.log"; then change_result="NO" else change_result="YES" fi # Overwrite report file on first check, append for subsequent ones echo -e "{{ item.param_name }} - $change_result" {{ '>' if loop.index == 1 else '>>' }} "{{ report_file }}" vars: # Reusable variables to avoid repeating paths check_dir: "/root/pre_post_check_{{ ansible_date_time.date }}" report_file: "{{ check_dir }}/{{ inventory_hostname }}_report.log" loop: # Each entry represents one check with its human-friendly name and file pairs - param_name: "Mounted Filesystems" pre_file: "pre_df" post_file: "post_df" - param_name: "KERNEL VERSION" pre_file: "pre_uname" post_file: "post_uname" - param_name: "SYSCTL" pre_file: "pre_sysctl" post_file: "post_sysctl" loop_control: # Makes Ansible output cleaner by showing the parameter name instead of full item label: "{{ item.param_name }}"
What this does:
- Clean Loop Structure: Each check gets its own entry in the loop list, making it easy to add/remove checks later (just add another
- param_name: ...block). - Efficient Comparison:
cmp -schecks if files are identical without reading their entire contents, which is better for performance. - Reusable Variables:
check_dirandreport_filereduce path duplication and make the code easier to edit. - Preserves Original Behavior: Uses
loop.indexto overwrite the host report on the first check (like your original>) and append for others (like>>). - Readable Output: The
loop_controllabel shows which parameter is being checked in Ansible's run output, instead of dumping the entire loop item.
This rewrite cuts down on repetitive code and makes your playbook much easier to maintain as you add more pre/post checks in the future.
内容的提问来源于stack exchange,提问作者pugazhendhi_r

