本页介绍了如何在构建步骤之间传递数据。如果您刚接触 Cloud Build,请先阅读构建快速入门和构建配置概览。
Cloud Build 会将任务作为一系列构建步骤运行,这些构建步骤会在隔离的容器化环境中执行。在每个步骤之后,系统都会舍弃该容器。这样,您就可以为每个步骤使用完全不同的工具和环境,并且默认情况下,在某个步骤中创建的任何数据都不会污染下一步。但有时,您可能需要保留 build 的某个步骤的状态,以便在后续步骤中使用。
对于此类情况,Cloud Build 提供了卷,它们是可读写的文件路径,可附加到任何构建步骤。卷会在整个 build 期间保留其内容。您可以定义自己的卷,也可以使用 /workspace,这是 Cloud Build 为您提供的默认卷。在执行构建之前,Cloud Build 会将源代码提取到 /workspace。任何步骤写入用户定义的卷和 /workspace 的内容都将可供后续步骤使用。
使用工作区传递数据
如需在构建步骤之间传递数据,请将构建步骤生成的资源存储在 /workspace
中,这些资源将可供任何后续构建步骤使用。
在以下构建配置文件示例中,第一个构建步骤会将字符串“First Value”存储在 /workspace/first.txt
中,并将值 2
存储在 /workspace/second.txt
中。第二个 build 步骤会读取并输出 /workspace/first.txt
和 /workspace/second.txt
中的值。
YAML
steps:
- id: "Store Values"
name: ubuntu
entrypoint: bash
args:
- -c
- |
# Save a value to persistent volume mount: "/workspace"
echo "First Value" > /workspace/first.txt &&
# Save another
expr 1 + 1 > /workspace/second.txt
# In the next step, everything in the environment is discarded
# EXCEPT items in "/workspace"
- id: "Read Values"
name: ubuntu
entrypoint: bash
args:
- -c
- |
# Read from "/workspace"
echo "First we saved " $(cat /workspace/first.txt) &&
echo "Then we saved " $(cat /workspace/second.txt)
JSON
{
"steps": [
{
"id": "Store Values",
"name": "ubuntu",
"entrypoint": "bash",
"args": [
"-c",
"echo \"First Value\" > /workspace/first.txt &&\nexpr 1 + 1 > /workspace/second.txt\n"
]
},
{
"id": "Read Values",
"name": "ubuntu",
"entrypoint": "bash",
"args": [
"-c",
"echo \"First we saved \" $(cat /workspace/first.txt) &&\necho \"Then we saved \" $(cat /workspace/second.txt)\n"
]
}
]
}
使用用户指定的卷传递数据
您可以定义自己的卷,以便在构建步骤之间保留数据,而不是使用 Cloud Build 提供的默认 /workspace
卷。
如需定义和使用您自己的音量,请执行以下操作:
- 在您要存储数据的构建步骤中:
- 添加
volumes
块,然后设置以下字段:name
:将此字段的值设置为所需的卷名称。path
:将此字段的值设置为用于存储数据的文件路径。
- 将数据存储在
path
中指定的文件路径中。
- 添加
- 在您要使用数据的构建步骤中:
- 添加一个
volumes
块,其中包含name
和path
的值。 - 使用
path
中指定的文件路径中的数据。
- 添加一个
在以下构建配置文件示例中,第一个构建步骤定义了一个名为 myvolume
的卷,并将数据存储在 /persistent_volume/file
中。第二个 build 步会输出存储在 /persistent_volume/file
中的值。
YAML
steps:
- name: 'ubuntu'
entrypoint: 'bash'
args:
- '-c'
- |
echo "Hello, world!" > /persistent_volume/file
volumes:
- name: 'myvolume'
path: '/persistent_volume'
- name: 'ubuntu'
entrypoint: 'bash'
args:
- '-c'
- |
cat /persistent_volume/file
volumes:
- name: 'myvolume'
path: '/persistent_volume'
JSON
{
"steps": [
{
"name": "ubuntu",
"entrypoint": "bash",
"args": [
"-c",
"echo \"Hello, world!\" > /persistent_volume/file\n"
],
"volumes": [
{
"name": "myvolume",
"path": "/persistent_volume"
}
]
},
{
"name": "ubuntu",
"entrypoint": "bash",
"args": [
"-c",
"cat /persistent_volume/file\n"
],
"volumes": [
{
"name": "myvolume",
"path": "/persistent_volume"
}
]
}
]
}
后续步骤
- 了解如何手动启动构建。
- 了解如何使用触发器自动执行构建。
- 了解如何在构建步骤中运行 bash 脚本。
- 了解如何配置构建步骤顺序。