You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Ordering Issues: When looping lineinfile, each iteration inserts the line directly after the original ForceCommand cvs server line—not after lines added in previous loop runs. This reversed your intended line order and buried empty lines.
  2. Empty Line Handling: lineinfile isn’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/# END markers that blockinfile adds 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 07:55:36