Packer 是開放原始碼工具,可從單一來源設定為多個平台建立相同的虛擬機器 (VM) 映像檔。本頁說明如何使用 Packer 和 Cloud Build 建立可在 Compute Engine 上使用的 VM 映像檔。
事前準備
本頁的操作說明假設您已熟悉 Packer
。此外:
- 請準備好原始碼,包括封裝器範本。
- 如要使用本頁中的
gcloud
指令,請安裝 Google Cloud CLI。 啟用下列 API:
gcloud services enable sourcerepo.googleapis.com gcloud services enable compute.googleapis.com gcloud services enable servicemanagement.googleapis.com gcloud services enable storage-api.googleapis.com
必要的 IAM 權限
如要搭配 Cloud Build 使用 Packer,請將 Compute Engine 執行個體管理員角色 (
roles/compute.instanceAdmin.v1
) 授予建構服務帳戶。如要在 Artifact Registry 中儲存已建構的映像檔,請將 Artifact Registry Writer (
roles/artifactregistry.writer
) 角色授予建構服務帳戶。
建立 Packer 建構工具映像檔
Cloud Build 提供 Packer 社群建構工具映像檔,可用於在 Cloud Build 中叫用 packer
指令。在 Cloud Build 設定檔中使用這個建構工具前,您必須先建構映像檔,並將其推送至 Artifact Registry:
複製 cloud-builders-community 存放區:
git clone https://github.com/GoogleCloudPlatform/cloud-builders-community.git
前往 Packer 建構工具圖片:
cd cloud-builders-community/packer
將建構工具提交至專案:
gcloud builds submit .
使用 Packer 建構工具
請確認您已將 packer.json 檔案與原始碼一併備份。
在專案根目錄中,建立名為
cloudbuild.yaml
或cloudbuild.json
的建構設定檔。在建構設定檔中新增建構步驟,以叫用
packer build
指令:YAML
steps: - name: 'gcr.io/[PROJECT_ID]/packer' args: - build - -var - image_name=[IMAGE_NAME] - -var - project_id=[PROJECT_ID] - -var - image_family=[IMAGE_FAMILY] - -var - image_zone=[IMAGE_ZONE] - packer.json
JSON
{ "steps": [ { "name": "gcr.io/[PROJECT_ID]/packer", "args": [ "build", "-var", "image_name=[IMAGE_NAME]", "-var", "project_id=[PROJECT_ID]", "-var", "image_family=[IMAGE_FAMILY]", "-var", "image_zone=[IMAGE_ZONE]", "packer.json" ] } ] }
其中:
使用建構設定檔展開建構作業:
gcloud builds submit --region=[REGION] --config [CONFIG_FILE_PATH] [SOURCE_DIRECTORY]
其中:
[CONFIG_FILE_PATH]
是建構設定檔的路徑。[SOURCE_DIRECTORY]
是原始碼的路徑或網址。[REGION]
是支援的建構區域之一。
如果您未在
gcloud builds submit
指令中指定[CONFIG_FILE_PATH]
和[SOURCE_DIRECTORY]
,Cloud Build 會假設設定檔和原始碼位於目前的工作目錄中。
建構映像檔後,您可以在 Google Cloud 控制台的「Compute Engine 映像檔」頁面中查看這些映像檔。