Ansible lineinfile模块添加空行失效,寻求解决方案
Solution
Use Ansible's blockinfile module instead of looping lineinfile—it’s designed for inserting multi-line blocks (including empty lines) in one go, which avoids the ordering and empty line issues you’re facing.
Here’s the corrected playbook:
- name: Add security hardening settings to sshd_config blockinfile: path: /etc/ssh/sshd_config insertafter: 'ForceCommand cvs server' block: | ### Remove vulnerabilities Ciphers aes128-ctr,aes192-ctr,aes256-ctr KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256 MACs hmac-sha2-256,hmac-sha2-512 marker: "" # Disable default BEGIN/END markers backup: yes
Why Your Original Approach Failed
- Ordering Issues: When looping
lineinfile, each iteration inserts the line directly after the originalForceCommand cvs serverline—not after lines added in previous loop runs. This reversed your intended line order and buried empty lines. - Empty Line Handling:
lineinfileisn’t optimized for managing whitespace-only lines in looped scenarios, leading to missing empty lines in the final output.
Key Details of the Fix
blockinfile: Inserts the entire multi-line block as a single unit, preserving line order and empty lines exactly as defined.- YAML Literal Scalar (
|): Ensures newlines and empty lines in the block are retained when written to the file. marker: "": Disables the default# BEGIN/# ENDmarkers thatblockinfileadds by default (matching your expected output).- Corrected Line Order: Adjusted the sequence to place the heading first, followed by config lines, as shown in your expected result.
内容的提问来源于stack exchange,提问作者gotothesky
相关产品推荐
相关产品推荐

