HASHICORP Packer使用学习小记 2024-06-18 14:58:20 Steven Xeldax [TOC] ## packer介绍 packer 是 hashicorp 下的一款镜像制作软件 透過 packer 製作 image 可以有以下優點 將 image 製作流程標準化 較容易做版本管理 可以直接看出該 image 裡有哪些設定 較容易在不同格式的 image 裡進行一樣的環境設定 當 image 版本更動時,可以用 “保留 packer 設定檔” 的方式取代 “保留 image”,對於大量已經不再使用的 image 來說,可以節省相當大的空間。 可以在不同平台裡使用一致的 image ,也就是所謂的 golden image,對於安全性方面有很大的幫助 相較於 Infra as Code (IaC) 的概念,packer 可以說是另一種 IaC (Image as Code),在 image 的管理維護上會容易許多。 而 Image as Code 代表的意義是,可以透過 CI/CD 的方式,來達到建立 image 的自動化。例如說,假設今天使用的 linux 版本需要安裝一個安全性的更新,只需要修改 packer 的設定檔,然後 push 到 git,透過 CI/CD pipeline 就自動把相關的所有 image (例如 OVF、qcow2 以及各大雲平台) 都更新到最新版本 ## packer 安装 packer 是golang写的,当然可以二进制安装,具体的安装文档见如下: https://developer.hashicorp.com/packer/tutorials/docker-get-started/get-started-install-cli ## packer Intergration ## 常见使用 使用virtualbox 打包镜像 http://releases.ubuntu.com/22.04/ubuntu-22.04.4-live-server-amd64.iso ISO checksum sha256 ubuntu22_04.json vmware-iso with VMware Player on linux - no display issue linux 一定要加headless(https://groups.google.com/g/packer-tool/c/AZch0El17bU) ``` { "builders": [ { "guest_os_type": "Ubuntu_64", "iso_checksum": "sha256:45f873de9f8cb637345d6e66a583762730bbea30277ef7b32c9c3bd6700a32b2", "iso_url": "http://releases.ubuntu.com/22.04/ubuntu-22.04.4-live-server-amd64.iso", "shutdown_command": "echo 'vagrant'|sudo -S shutdown -P now", "ssh_password": "vagrant-sandbox", "ssh_port": 22, "ssh_timeout": "10000s", "headless": true, "ssh_username": "vagrant", "type": "virtualbox-iso" } ], "post-processors": [ { "output": "ubuntu2204.box", "type": "vagrant" } ], "provisioners": [ { "script": "setup.sh", "type": "shell" } ] } ``` setup.sh ``` #!/bin/bash sudo apt-get update sudo apt-get upgrade -y sudo apt-get install -y vim git sudo apt-get install -y gcc make ```  使用Vagrant Build去创建镜像 ``` { "builders": [ { "communicator": "ssh", "source_path": "hashicorp/precise64", "provider": "virtualbox", "add_force": true, "type": "vagrant" } ], "provisioners": [ { "script": "setup.sh", "type": "shell" } ] } ```