本頁面說明如何在建構步驟之間傳遞資料。如果您是 Cloud Build 新手,請先參閱建構快速入門和建構設定總覽。
Cloud Build 會以一系列建構步驟執行工作,這些步驟會在隔離和容器化環境中執行。每完成一個步驟後,容器就會遭到捨棄。這樣一來,您就可以為每個步驟使用完全不同的工具和環境,而且根據預設,在一個步驟中建立的任何資料都不會影響下一個步驟。不過,有時您可能需要將建構作業的某個步驟狀態保留起來,以便在後續步驟中使用。
在這種情況下,Cloud Build 會提供磁碟區,這是可讀寫檔案路徑,可附加至任何建構步驟。磁碟區會在整個建構期間保留內容。您可以自行定義磁碟,也可以使用 /workspace,這是 Cloud Build 提供的預設磁碟。在執行建構作業前,Cloud Build 會將原始碼擷取至 /workspace。任何步驟寫入使用者定義的磁碟區和 /workspace 的內容,都會提供給後續步驟。
使用工作區傳遞資料
如要在建構步驟之間傳遞資料,請在 /workspace
中儲存建構步驟產生的資產,這些資產可供後續的任何建構步驟使用。
在以下建構設定檔範例中,第一個建構步驟會將字串「First Value」儲存在 /workspace/first.txt
中,並將 2
值儲存在 /workspace/second.txt
中。第二個建構步驟會讀取並列印 /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
中。第二個建構步驟會列印儲存在 /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 指令碼。
- 瞭解如何設定建構步驟順序。