Packer Quick Start

[x] template user variable [x] builder google cloud, authentication, etc. [x] provisioner ansible

Build Images for cloud and on-premise, Packer template is JSON format (easily source control).

  • variables
  • builders: can have multiple builders run parallelly.
  • provisioners: run in order, need only to specify where to run.
  • post-processors: auto post-build tasks, eg: compression.

A machine image is a single static unit that contains a pre-configured operating system and installed software which is used to quickly create new running machines. Machine image formats change for each platform. Some examples include AMIs for EC2, VMDK/VMX files for VMware, OVF exports for VirtualBox, etc.

-debug flag in build can help run steps one by one, parallel build in debug mode is running sequentially.

To build Ubuntu VirtualBox image VOF, ISO is download from Ubuntu web site then Packer will launch it to run provisioner. Then use post-processor to compress VOF to tar.gz, or convert to Vagrant box.

What are the differences between Packer and Docker?

Transition from Packer to Docker is easy, but the docker builder may not efficient as the docker native tool.

Example of packer json file, use ansibe as provisioner on google cloud:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
"variables": {
"project_id": "xxxxxx",
"source_image": "xxxxxx",
"subnetwork": "xxxxxx",
"zone": "xxxxxx",
"image_name": "xxxxxx"
},
"builders": [
{
"type": "googlecompute",
"project_id": "{{user `project_id`}}",
"source_image": "{{user `source_image`}}",
"subnetwork": "{{user `subnetwork`}}",
"ssh_username": "xxxxxx",
"zone": "{{user `zone`}}",
"use_internal_ip": true,
"omit_external_ip": true,
"image_description": "xxxxxx",
"image_name": "{{user `image_name`}}"
}
],
"provisioners": [
{
"type": "ansible",
"max_retries": 0,
"pause_before": "5s",
"playbook_file": "setup.yml",
// acts on target instance
"extra_arguments": ["--become", "-e ansible_python_interpreter=/usr/bin/python3", "-v"],
"user": "xxxxxx"
}
]
}

Some useful commands:

1
2
3
4
5
6
7
8
9
10
11
# illustrate packer.json file
packer inspect

# validate packer.json syntax
packer validate <file.json>

# build image
# -debug: pause for each step, clear
packer build [-debug] <file.json>
# -force: delete existing artifact then build
packer build -force [-debug] <file.json>

When using -debug flag, Packer will show you the private pem file in current directory, you can use that pem file ssh to running VM, for example, in google cloud:

1
2
# jenkins is the ssh_username you set in template
ssh -i gce_googlecompute.pem jenkins@172.16.160.49