Zum Inhalt

Packer

generieren

Umfassende HashiCorp Packer-Befehle und Workflows für automatisiertes Maschinenbildgebäude auf mehreren Plattformen.

Installation und Inbetriebnahme

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

Kernkommandos

Betrieben aufbauen

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

Validierung und Inspektion

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

Plugin Management

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

Beispiele für

AWS AMI Template

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

### Azure Bildvorlage
```hcl
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"
\\\\}
```_

### Google Cloud Image Vorlage
```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"]
\\\\}
```_

### Docker Bildvorlage
```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"]
  \\\\}
\\\\}
```_

### VirtualBox Vorlage
```hcl
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"
\\\\}
```_

## Provisionen

### Shell Provisioning
```hcl
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"
  ]
\\\\}
```_

### Datei Provisioner
```hcl
provisioner "file" \\\\{
  source      = "files/"
  destination = "/tmp/"
\\\\}

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

### Anwendbarer Vorsorger
```hcl
provisioner "ansible" \\\\{
  playbook_file = "ansible/playbook.yml"

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

### PowerShell Provisioner (Windows)
```hcl
provisioner "powershell" \\\\{
  inline = [
    "Write-Host 'Installing IIS'",
    "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole",
    "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer"
  ]
\\\\}
```_

## Post-Processors

### Docker Tag
```hcl
post-processor "docker-tag" \\\\{
  repository = "myapp"
  tags       = ["latest", "v1.0.0"]
\\\\}
```_

### Docker Push
```hcl
post-processor "docker-push" \\\\{
  login          = true
  login_username = var.docker_username
  login_password = var.docker_password
\\\\}
```_

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

### Kompressor
```hcl
post-processor "compress" \\\\{
  output = "image.tar.gz"
\\\\}
```_

## Variablen und Funktionen

### Variable Definitionen
```hcl
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."
  \\\\}
\\\\}
```_

### Lokale Werte
```hcl
locals \\\\{
  timestamp = regex_replace(timestamp(), "[- TZ:]", "")

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

### Funktionen
```hcl
# 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)
```_

## Multi-Platform baut

### Parallel baut
```hcl
build \\\\{
  sources = [
    "source.amazon-ebs.ubuntu",
    "source.azure-arm.ubuntu",
    "source.googlecompute.ubuntu"
  ]

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

### Plattform-spezifische Bereitstellung
```hcl
provisioner "shell" \\\\{
  only = ["amazon-ebs.ubuntu"]
  inline = [
    "echo 'AWS-specific configuration'"
  ]
\\\\}

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

## Erweiterte Funktionen

### Bedingte Bauten
```hcl
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"]
      \\\\}
    \\\\}
  \\\\}
\\\\}
```_

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

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

### Breakpoints für Debugging
```hcl
provisioner "breakpoint" \\\\{
  disable = false
  note    = "Debug point - check system state"
\\\\}
```_

## Best Practices

### Vorlagenorganisation

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 ```_

Sicherheit Best Practices

  1. *Credentials: Verwenden Sie IAM-Rollen anstelle von Zugangsschlüsseln
  2. *Secrets: Speichert Geheimnisse in externen Systemen (Vault, AWS Secrets Manager)
  3. *Base Images: Verwenden Sie offizielle, aktualisierte Basisbilder
  4. Scanning: Bilder für Schwachstellen scannen
  5. *Minimal Images: Installieren Sie nur notwendige Pakete

Leistungsoptimierung

  1. *Parallel Builds: Mehrere Plattformen gleichzeitig bauen
  2. Caching: Verwenden Sie die Caching-Funktionen von Paketmanagern
  3. *Layer Optimization: Minimieren von Bildschichten
  4. Resource Sizing: Verwenden Sie entsprechende Instanzgrößen
  5. Network: Schnelle Netzwerkverbindungen verwenden

Wartung

  1. Version Control: Vorlagen in der Versionskontrolle speichern
  2. Test: Testvorlagen in CI/CD-Pipelines
  3. ** Aussprache**: Zweck und Nutzung der Dokumentenvorlage
  4. Updates: Regelmäßig aktualisieren Basisbilder und Abhängigkeiten
  5. Monitoring: Bauzeiten und Erfolgsquoten überwachen