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 packer

Setting in up#


Operate#

packer [command]> [options] [template_file]

常用指令範例指令說明
initpacker init config.pkr.hcl下載並安裝模板所需的插件(如 AWS, Docker 等)。
fmtpacker fmt .自動格式化 HCL 檔案,確保代碼風格統一。
validatepacker validate example.pkr.hcl檢查模板語法與邏輯配置是否正確。
buildpacker build example.pkr.hcl依照模板定義開始執行映像檔的建置流程。
inspectpacker inspect template.json查看模板結構、變數與使用的組件資訊。
-vpacker -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:

Packer Documentation

Packer Github