cli-tool
intermediate
utility
Packer
"Clase de la hoja"
########################################################################################################################################################################################################################################################## Copiar todos los comandos
■/div titulada
HashiCorp Empaque comandos y flujos de trabajo para la construcción automatizada de imagen de máquina a través de múltiples plataformas.
Instalación
Command
Description
packer version
Show Packer version
packer -help
Show help information
packer -help build
Show help for specific command
Comandos básicos
Operaciones de construcción
Command
Description
packer build template.pkr.hcl
Build image from template
packer build -var 'region=us-west-2' template.pkr.hcl
Build with variables
packer build -var-file=vars.pkrvars.hcl template.pkr.hcl
Build with variable file
packer build -only=amazon-ebs template.pkr.hcl
Build specific builder only
packer build -except=virtualbox-iso template.pkr.hcl
Exclude specific builder
Validación e Inspección
Command
Description
packer validate template.pkr.hcl
Validate template
packer inspect template.pkr.hcl
Inspect template
packer fmt template.pkr.hcl
Format template
packer fmt -diff template.pkr.hcl
Show formatting differences
Gestión de plugins
Command
Description
packer init template.pkr.hcl
Initialize and install plugins
packer plugins install github.com/hashicorp/amazon
Install specific plugin
packer plugins installed
List installed plugins
Ejemplos de plantilla
Plantilla AWS AMI
packer \\\\{
required_plugins \\\\{
amazon = \\\\{
version = ">= 1.0.0"
source = "github.com/hashicorp/amazon"
\\\\}
\\\\}
\\\\}
variable "region" \\\\{
type = string
default = "us-west-2"
\\\\}
variable "instance_type" \\\\{
type = string
default = "t2.micro"
\\\\}
locals \\\\{
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
\\\\}
source "amazon-ebs" "ubuntu" \\\\{
ami_name = "my-ubuntu-$\\\\{local.timestamp\\\\}"
instance_type = var.instance_type
region = var.region
source_ami_filter \\\\{
filters = \\\\{
name = "ubuntu/images/*ubuntu-jammy-22.04-amd64-server-*"
root-device-type = "ebs"
virtualization-type = "hvm"
\\\\}
most_recent = true
owners = ["099720109477"]
\\\\}
ssh_username = "ubuntu"
tags = \\\\{
Name = "MyUbuntuImage"
Environment = "production"
\\\\}
\\\\}
build \\\\{
name = "ubuntu-build"
sources = [
"source.amazon-ebs.ubuntu"
]
provisioner "shell" \\\\{
inline = [
"echo 'Updating system packages'",
"sudo apt-get update",
"sudo apt-get upgrade -y",
"sudo apt-get install -y nginx docker.io",
"sudo systemctl enable nginx",
"sudo systemctl enable docker"
]
\\\\}
provisioner "file" \\\\{
source = "files/nginx.conf"
destination = "/tmp/nginx.conf"
\\\\}
provisioner "shell" \\\\{
inline = [
"sudo mv /tmp/nginx.conf /etc/nginx/nginx.conf",
"sudo nginx -t"
]
\\\\}
post-processor "manifest" \\\\{
output = "manifest.json"
strip_path = true
\\\\}
\\\\}
Plantilla de imagen de Azure
source "azure-arm" "ubuntu" \\\\{
client_id = var.client_id
client_secret = var.client_secret
subscription_id = var.subscription_id
tenant_id = var.tenant_id
managed_image_resource_group_name = "myResourceGroup"
managed_image_name = "myUbuntuImage"
os_type = "Linux"
image_publisher = "Canonical"
image_offer = "0001-com-ubuntu-server-jammy"
image_sku = "22_04-lts"
location = "East US"
vm_size = "Standard_B2s"
\\\\}
Plantilla de imagen de Google Cloud
source "googlecompute" "ubuntu" \\\\{
project_id = var.project_id
source_image = "ubuntu-2204-jammy-v20230114"
zone = "us-central1-a"
image_name = "my-ubuntu-image"
image_description = "Custom Ubuntu image with applications"
ssh_username = "packer"
tags = ["packer", "ubuntu"]
\\\\}
Plantilla de imagen de Docker
source "docker" "ubuntu" \\\\{
image = "ubuntu:22.04"
commit = true
changes = [
"EXPOSE 80",
"ENTRYPOINT [\"/usr/sbin/nginx\", \"-g\", \"daemon off;\"]"
]
\\\\}
build \\\\{
sources = ["source.docker.ubuntu"]
provisioner "shell" \\\\{
inline = [
"apt-get update",
"apt-get install -y nginx",
"rm -rf /var/lib/apt/lists/*"
]
\\\\}
post-processor "docker-tag" \\\\{
repository = "my-nginx"
tags = ["latest", "1.0"]
\\\\}
\\\\}
Plantilla VirtualBox
source "virtualbox-iso" "ubuntu" \\\\{
iso_url = "https://releases.ubuntu.com/22.04/ubuntu-22.04.1-desktop-amd64.iso"
iso_checksum = "sha256:10f19c5b2b8d6db711582e0e27f5116296c34fe4b313ba45f9b201a5007056cb"
guest_os_type = "Ubuntu_64"
disk_size = 40000
memory = 2048
cpus = 2
ssh_username = "packer"
ssh_password = "packer"
ssh_timeout = "20m"
boot_command = [
"<enter><wait><f6><wait><esc><wait>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs><bs><bs><bs><bs><bs><bs><bs>",
"<bs><bs><bs>",
"/install/vmlinuz",
" initrd=/install/initrd.gz",
" priority=critical",
" locale=en_US",
" file=/media/preseed.cfg",
"<enter>"
]
shutdown_command = "echo 'packer'|sudo -S shutdown -P now"
\\\\}
Proveedores
Shell Provisioner
provisioner "shell" \\\\{
inline = [
"sudo apt-get update",
"sudo apt-get install -y nginx"
]
\\\\}
provisioner "shell" \\\\{
script = "scripts/install-docker.sh"
\\\\}
provisioner "shell" \\\\{
scripts = [
"scripts/update-system.sh",
"scripts/install-apps.sh",
"scripts/configure-services.sh"
]
\\\\}
File Provisioner
provisioner "file" \\\\{
source = "files/"
destination = "/tmp/"
\\\\}
provisioner "file" \\\\{
content = "Hello World"
destination = "/tmp/hello.txt"
\\\\}
Ansible Provisioner
provisioner "ansible" \\\\{
playbook_file = "ansible/playbook.yml"
extra_arguments = [
"--extra-vars",
"ansible_ssh_user=ubuntu"
]
\\\\}
PowerShell Provisioner (Windows)
provisioner "powershell" \\\\{
inline = [
"Write-Host 'Installing IIS'",
"Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole",
"Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer"
]
\\\\}
Puestos de procesamiento
Docker Tag
post-processor "docker-tag" \\\\{
repository = "myapp"
tags = ["latest", "v1.0.0"]
\\\\}
Docker Push
post-processor "docker-push" \\\\{
login = true
login_username = var.docker_username
login_password = var.docker_password
\\\\}
Manifest
post-processor "manifest" \\\\{
output = "manifest.json"
strip_path = true
custom_data = \\\\{
build_time = timestamp()
version = var.app_version
\\\\}
\\\\}
Compresores
post-processor "compress" \\\\{
output = "image.tar.gz"
\\\\}
Variables y Funciones
Definiciones variables
variable "region" \\\\{
type = string
description = "AWS region"
default = "us-west-2"
\\\\}
variable "instance_type" \\\\{
type = string
validation \\\\{
condition = contains([
"t2.micro",
"t2.small",
"t2.medium"
], var.instance_type)
error_message = "Instance type must be t2.micro, t2.small, or t2.medium."
\\\\}
\\\\}
Valores locales
locals \\\\{
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
common_tags = \\\\{
Project = "MyProject"
Environment = "Production"
BuildTime = timestamp()
\\\\}
\\\\}
Funciones
# String functions
ami_name = "myapp-$\\\\{formatdate("YYYY-MM-DD-hhmm", timestamp())\\\\}"
# File functions
user_data = base64encode(file("scripts/user-data.sh"))
# Collection functions
security_groups = concat(var.base_security_groups, var.additional_security_groups)
Construcciones paralelas
build \\\\{
sources = [
"source.amazon-ebs.ubuntu",
"source.azure-arm.ubuntu",
"source.googlecompute.ubuntu"
]
provisioner "shell" \\\\{
inline = [
"echo 'This runs on all platforms'"
]
\\\\}
\\\\}
provisioner "shell" \\\\{
only = ["amazon-ebs.ubuntu"]
inline = [
"echo 'AWS-specific configuration'"
]
\\\\}
provisioner "shell" \\\\{
except = ["virtualbox-iso.ubuntu"]
inline = [
"echo 'Cloud-specific configuration'"
]
\\\\}
Características avanzadas
Construidos condicionales
build \\\\{
sources = var.build_aws ? ["source.amazon-ebs.ubuntu"] : []
dynamic "provisioner" \\\\{
for_each = var.install_docker ? [1] : []
content \\\\{
shell \\\\{
inline = ["curl -fsSL https://get.docker.com|sh"]
\\\\}
\\\\}
\\\\}
\\\\}
Manejo de errores
provisioner "shell" \\\\{
inline = [
"sudo apt-get update||(sleep 30 && sudo apt-get update)"
]
max_retries = 3
pause_before = "10s"
\\\\}
Puntos de ruptura para depurar
provisioner "breakpoint" \\\\{
disable = false
note = "Debug point - check system state"
\\\\}
Buenas prácticas
Plantilla Organización
project/
├── templates/
│ ├── aws.pkr.hcl
│ ├── azure.pkr.hcl
│ └── variables.pkr.hcl
├── scripts/
│ ├── install-docker.sh
│ └── configure-nginx.sh
├── files/
│ └── nginx.conf
└── variables/
├── dev.pkrvars.hcl
└── prod.pkrvars.hcl
Prácticas óptimas de seguridad
Credentials : Use roles de IAM en lugar de claves de acceso
Secrets : Guardar secretos en sistemas externos (Vault, AWS Secrets Manager)
** Imágenes básicas**: Utilizar imágenes de base oficiales y actualizadas
Scanning : Escanear imágenes para vulnerabilidades
Minimal Images : Instalar sólo los paquetes necesarios
Optimización del rendimiento
Construye Parallel : Construye múltiples plataformas simultáneamente
Caching : Use las características de caché de los administradores de paquetes
** Optimización de capas**: Minimizar capas de imagen
Resource Sizing : Use tamaños de instancia adecuados
Network : Use conexiones de red rápidas
Mantenimiento
Version Control : Almacenar plantillas en el control de versiones
Testing : Plantillas de prueba en tuberías CI/CD
Documentación : propósito y uso de la plantilla de documentos
Actualizaciones : Actualizar regularmente las imágenes de base y las dependencias
Monitoring : Monitorear tiempos de construcción y tasas de éxito