Aller au contenu

Emballeur

Copier toutes les commandes Générer PDF

HashiCorp complet Commandes d'emballage et workflows pour la construction automatique d'images machine sur plusieurs plateformes.

Installation et configuration

Command Description
packer version Show Packer version
packer -help Show help information
packer -help build Show help for specific command

Commandes de base

Bâtir des opérations

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

Validation et inspection

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

Gestion des greffons

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

Exemples de modèles

Modèle AMI AWS

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
  \\\\}
\\\\}

Modèle d'image 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"
\\\\}
```_

### Modèle d'image Google Cloud
```hcl
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"]
\\\\}
```_

### Modèle d'image Docker
```hcl
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"]
  \\\\}
\\\\}

Modèle 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"
\\\\}

Provisionnaires

Provisionneur Shell

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"
  ]
\\\\}

Provisionneur de fichiers

provisioner "file" \\\\{
  source      = "files/"
  destination = "/tmp/"
\\\\}

provisioner "file" \\\\{
  content     = "Hello World"
  destination = "/tmp/hello.txt"
\\\\}

Provisionnable

provisioner "ansible" \\\\{
  playbook_file = "ansible/playbook.yml"

  extra_arguments = [
    "--extra-vars",
    "ansible_ssh_user=ubuntu"
  ]
\\\\}

Provisionneur PowerShell (Windows)

provisioner "powershell" \\\\{
  inline = [
    "Write-Host 'Installing IIS'",
    "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole",
    "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer"
  ]
\\\\}

Post-processeurs

Étiquette Docker

post-processor "docker-tag" \\\\{
  repository = "myapp"
  tags       = ["latest", "v1.0.0"]
\\\\}

Pousser

post-processor "docker-push" \\\\{
  login          = true
  login_username = var.docker_username
  login_password = var.docker_password
\\\\}

Manifeste

post-processor "manifest" \\\\{
  output = "manifest.json"
  strip_path = true
  custom_data = \\\\{
    build_time = timestamp()
    version    = var.app_version
  \\\\}
\\\\}

Pression

post-processor "compress" \\\\{
  output = "image.tar.gz"
\\\\}

Variables et fonctions

Définitions 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."
  \\\\}
\\\\}

Valeurs locales

locals \\\\{
  timestamp = regex_replace(timestamp(), "[- TZ:]", "")

  common_tags = \\\\{
    Project     = "MyProject"
    Environment = "Production"
    BuildTime   = timestamp()
  \\\\}
\\\\}

Fonctions

# 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)

Constructions multiplateformes

Constructions parallèles

build \\\\{
  sources = [
    "source.amazon-ebs.ubuntu",
    "source.azure-arm.ubuntu",
    "source.googlecompute.ubuntu"
  ]

  provisioner "shell" \\\\{
    inline = [
      "echo 'This runs on all platforms'"
    ]
  \\\\}
\\\\}

Fourniture spécifique à la plate-forme

provisioner "shell" \\\\{
  only = ["amazon-ebs.ubuntu"]
  inline = [
    "echo 'AWS-specific configuration'"
  ]
\\\\}

provisioner "shell" \\\\{
  except = ["virtualbox-iso.ubuntu"]
  inline = [
    "echo 'Cloud-specific configuration'"
  ]
\\\\}

Caractéristiques avancées

Constructions conditionnelles

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"]
      \\\\}
    \\\\}
  \\\\}
\\\\}

Gestion des erreurs

provisioner "shell" \\\\{
  inline = [
    "sudo apt-get update||(sleep 30 && sudo apt-get update)"
  ]

  max_retries = 3
  pause_before = "10s"
\\\\}

Points d'arrêt pour le débogage

provisioner "breakpoint" \\\\{
  disable = false
  note    = "Debug point - check system state"
\\\\}

Meilleures pratiques

Organisation du modèle

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

Pratiques exemplaires en matière de sécurité

  1. Crédits: Utilisez les rôles IAM au lieu des clés d'accès
  2. Secrets: Store secrets dans les systèmes externes (Vault, AWS Secrets Manager)
  3. ** Images de base** : Utiliser des images de base officielles et mises à jour
  4. Scanning : Numériser les images pour détecter les vulnérabilités
  5. ** Images miniatures**: Installer uniquement les paquets nécessaires

Optimisation des performances

  1. Parallel Builds: Construire plusieurs plateformes simultanément
  2. Caching: Utilisez les fonctionnalités de cache des gestionnaires de paquets
  3. ** Optimisation de la méthode** : Minimiser les calques d'image
  4. Taille des ressources: Utiliser les tailles d'instance appropriées
  5. Réseau: Utiliser des connexions réseau rapides

Entretien

  1. Contrôle de la version: Enregistrer les modèles dans le contrôle de la version
  2. Test: Modèles d'essai dans les pipelines CI/CD
  3. Documentation: Objet et utilisation du modèle de document
  4. Mise à jour: Mettre à jour régulièrement les images de base et les dépendances
  5. Surveiller: Surveiller les temps de construction et les taux de réussite