搜索 K
主题
这篇文档只讲一件事:在 CNB 流水线里,怎么把前一个 stage 的结果传给后一个 stage。
最常见的场景:
CNB 里“导出环境变量”不是直接写:
export MY_VAR=hello这样 不够。
正确做法是两步:
##[set-output ...] 写入结果exports 里把这个结果映射成后续 stage 可用的环境变量main:
push:
- stages:
- name: prepare
script:
- echo "##[set-output message=hello world]"
exports:
message: MY_MESSAGE
- name: use
script:
- echo "$MY_MESSAGE"执行效果:
message=hello worldexports 把 message 导出成环境变量 MY_MESSAGE$MY_MESSAGEexport 不行 很多人会这样写:
- name: prepare
script:
- export MY_MESSAGE=hello
exports:
MY_MESSAGE: MY_MESSAGE这通常是错的。
原因是:
export MY_MESSAGE=hello 只是当前 shell 进程里的环境变量exports 读取的是当前 Job 的 result 对象result 里默认只有 stdout、stderr、info、code 等字段##[set-output key=value] 写进去所以,exports 左边的 key,应该是:
stdoutstderrinfocodeset-output 生成的字段名推荐你默认这样写:
- name: prepare
script:
- |
value="hello world"
echo "##[set-output message=$value]"
exports:
message: MY_MESSAGE后面直接使用:
- name: use
script:
- echo "$MY_MESSAGE"如果变量里有换行,例如:
不要直接硬塞普通字符串,推荐使用 base64。
示例:
- name: prepare-description
script:
- |
description="$(cat <<EOF
这是标题
这是第二段
EOF
)"
encoded="$(printf '%s' "$description" | base64 -w 0)"
echo "##[set-output release_description=base64,$encoded]"
exports:
release_description: RELEASE_DESCRIPTION
- name: use-description
script:
- echo "$RELEASE_DESCRIPTION"这样做的好处:
git:release 里使用导出的变量 CNB 的内置任务 options 支持变量替换,所以可以这样写:
- name: prepare-release-description
script:
- |
description="发布说明正文"
encoded="$(printf '%s' "$description" | base64 -w 0)"
echo "##[set-output release_description=base64,$encoded]"
exports:
release_description: RELEASE_DESCRIPTION
- name: release
type: git:release
options:
title: v1.0.0
description: "$RELEASE_DESCRIPTION"这就是最常见的“前一个 stage 生成 release 描述,后一个 stage 创建 release”的写法。
export 就够了 错误示例:
export RELEASE_DESCRIPTION=hello这不会自动进入 CNB 的 exports。
如果文本里有换行,建议直接用 base64,不要赌 shell 解析细节。
比如你在 here-doc 里直接写:
```text
hello
```有些 shell 场景下可能把反引号当命令替换处理,导致内容丢失或报错。
更稳妥的方式:
~~~text 代码块CNB 文档里提到:
100 KiB如果内容很大,建议改成:
main:
push:
- stages:
- name: prepare
script:
- |
text="$(cat <<EOF
第一行
第二行
EOF
)"
encoded="$(printf '%s' "$text" | base64 -w 0)"
echo "##[set-output result_text=base64,$encoded]"
exports:
result_text: RESULT_TEXT
- name: use
script:
- echo "$RESULT_TEXT"记住这 3 行就够了:
encoded="$(printf '%s' "$text" | base64 -w 0)"
echo "##[set-output result_text=base64,$encoded]"然后在 YAML 里:
exports:
result_text: RESULT_TEXT在 CNB 里,跨 stage 传值的关键不是 shell 的 export,而是 set-output + exports。
如果是多行文本,优先用:
base64exports$ENV_NAME