在GitHub Actions中使用heredoc创建含花括号的文件失败
问题原因
- YAML缩进错误:原步骤中
shell和run的缩进与name层级不一致,违反YAML语法规范,会导致工作流执行异常。 - 模板解析冲突: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
相关产品推荐
相关产品推荐

