Packer#
Packer 是由 HashiCorp 開發的開源工具,用於從單一原始碼為多個平台建立一致的機器映像檔 (Machine Images)。
Packer 自動化了建立映像檔的過程,讓你可以將作業系統安裝、軟體配置與安全性更新直接打包進映像檔中(即「黃金映像檔」Golden Image)。它支援多種平台,包括 AWS (AMI)、Azure、Google Cloud、VMware、VirtualBox 與 Docker 等。透過 HCL (Hashicorp Configuration Language) 語法,開發者可以實現「基礎設施即代碼」(IaC) 的映像檔管理。
Install#
$ wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
$ echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
$ sudo apt update && sudo apt install packerSetting in up#
Operate#
packer [command]> [options] [template_file]
| 常用指令 | 範例指令 | 說明 |
|---|---|---|
init | packer init config.pkr.hcl | 下載並安裝模板所需的插件(如 AWS, Docker 等)。 |
fmt | packer fmt . | 自動格式化 HCL 檔案,確保代碼風格統一。 |
validate | packer validate example.pkr.hcl | 檢查模板語法與邏輯配置是否正確。 |
build | packer build example.pkr.hcl | 依照模板定義開始執行映像檔的建置流程。 |
inspect | packer inspect template.json | 查看模板結構、變數與使用的組件資訊。 |
-v | packer -v | 顯示 Packer 的版本資訊。 |
核心組件說明 (HCL 結構)#
| 組件名稱 | 功能 | 詳細解釋 |
|---|---|---|
packer | 插件宣告 | 規定建置此映像檔所需的插件版本 (Required Plugins)。 |
source | 來源配置 | 定義基礎映像檔(如 Ubuntu 版本)、硬體規格與雲端平台設定。 |
build | 建置流程 | 定義映像檔生成的步驟,並連結特定的 source。 |
provisioner | 環境部署 | 在映像檔中安裝軟體的工具(如 shell, ansible, file 等)。 |
post-processor | 後置處理 | 建置完成後的動作,如壓縮映像檔、上傳雲端或標記 Tag。 |
variable | 變數定義 | 定義可重複使用的參數,例如 API Key 或 Region。 |
Example (Basic Template)#
packer {
required_plugins {
amazon = {
version = ">= 1.2.8"
source = "github.com/hashicorp/amazon"
}
}
}
source "amazon-ebs" "ubuntu" {
ami_name = "packer-example-{{timestamp}}"
instance_type = "t2.micro"
region = "us-west-2"
source_ami = "ami-0efcece6bed30fd98"
ssh_username = "ubuntu"
}
build {
sources = ["source.amazon-ebs.ubuntu"]
provisioner "shell" {
inline = [
"sudo apt-get update",
"sudo apt-get install -y nginx",
]
}
}Reference#
Official docs: