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

在GitHub Actions中使用heredoc创建含花括号的文件失败

问题原因
  1. YAML缩进错误:原步骤中shell和run的缩进与name层级不一致,违反YAML语法规范,会导致工作流执行异常。
  2. 模板解析冲突:GitHub Actions会自动将{{ ... }}识别为工作流变量表达式解析,直接写入Go模板的{{ }}会被错误替换;同时bash的here-doc未做正确转义,最终导致生成的模板内容错乱。
正确实现方式

方法一:通过GitHub Actions变量转义保留Go模板语法

用{{ '{{' }}输出{{,{{ '}}' }}输出}},同时修正YAML缩进:

- name: create the template
  shell: bash
  run: |
    cat <<EOF > myfile.tpl
    {{ '{{' }}- if . {{ '}}' }}
    {{ '{{' }}- range . {{ '}}' }}
    <h3>Target <code>{{ '{{' }} escapeXML .Target {{ '}}' }}</code></h3>
    {{ '{{' }}- if (eq (len .Vulnerabilities) 0) {{ '}}' }}
    <h4>No Vulnerabilities found</h4>
    .
    .
    {{ '{{' }}- end {{ '}}' }}
    EOF

方法二:使用bash原始here-doc避免shell解析

通过<<'EOF'定义原始here-doc(bash不会解析其中的变量和转义),同时对GitHub Actions的{{ }}进行转义:

- name: create the template
  shell: bash
  run: |
    cat <<'EOF' > myfile.tpl
    \{\{- if . \}\}
    \{\{- range . \}\}
    <h3>Target <code>\{{ escapeXML .Target }}</code></h3>
    \{\{- if (eq (len .Vulnerabilities) 0) \}\}
    <h4>No Vulnerabilities found</h4>
    .
    .
    \{\{- end \}\}
    EOF

注:此方法中\{会被GitHub Actions解析为{,最终生成的模板会保留正确的Go模板语法。

验证结果

执行上述步骤后,查看myfile.tpl会得到正确的内容:

{{- if . }}
{{- range . }}
<h3>Target <code>{{ escapeXML .Target }}</code></h3>
{{- if (eq (len .Vulnerabilities) 0) }}
<h4>No Vulnerabilities found</h4>
.
.
{{- end }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:43:14