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

如何在调用脚本的SALT State中通过Jinja保留输出空格

问题

编写了一个将在多台服务器运行的Bash脚本,通过Salt State调用执行,脚本功能正常,但Salt State输出会忽略脚本中的所有连续空格。

State文件内容:

{% set theRepo = salt['grains.get']('the_repo-redacted') %}
{% set rootSls = ... redacted ... %}
{% set map = theRepo + '/directory/to/jinja' %}
{% from map import data with context %}

run command that calls my script:
  cmd.script:
    - name: salt://{{ theRepo }}/directory/to/myScript.sh

脚本中的示例行:

echo "Red       Blue       Green"

命令行运行时输出正常,但在Salt输出中显示为:

Red Blue Green

尝试用printf的制表符\t也无效,看到Jinja的ignore_whitespace参数,但不确定如何配置。

解决方案
  1. 排除ignore_whitespace的作用:你看到的ignore_whitespace是针对file.append等文件类State的Jinja模板参数,用于控制模板渲染时的空格处理,和脚本执行后的输出格式化无关,添加{% set ignore_whitespace = False %}解决不了当前问题。

  2. 问题根源:Salt默认会对命令执行的输出做格式化处理,将连续的空白字符(空格、制表符)压缩为单个空格,以优化终端显示效果。

  3. 核心解决方法:在cmd.scriptState中添加raw: True参数,让Salt原样保留脚本的输出格式,不做任何压缩处理。修改后的State如下:

run command that calls my script:
  cmd.script:
    - name: salt://{{ theRepo }}/directory/to/myScript.sh
    - raw: True
  1. 备用方案:如果raw参数无效,可以在脚本中使用printf固定宽度格式化输出,确保列对齐,例如:
printf "%-10s %-10s %-10s\n" "Red" "Blue" "Green"

这种方式即使Salt压缩空格,固定宽度的格式化仍能保证内容的对齐效果。

内容的提问来源于stack exchange,提问作者TorusWithSprinkles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:07:37