Use packer to create a VM image on Hetzner cloud

Learn how to use packer to create a VM image to use it as a base template.

What do you need to complete this tutorial?

  • packer
  • A Hetzner cloud account and a Hetzner API token
  • Basic knowledge about cloud-init

What is packer?

Hashicorp packer is a tool to automatically create VM images. You can start from a base image, configure it (e.g. installing software or hardening) and store it in the Hetzner cloud for further usage. By using template scripts to automatically create images, it provides a reproducible and versionable way of creating base images for your cloud infrastructure.

A simple packer template

Here is a very simple template script starts from a Ubuntu 18.04 base image and uses a cloud-init script to install some packages and create a user.

Create a cloud-init script:

name: raphael
groups: ninjaturtles
lock_passwd: false
# created with 'openssl passwd -1 -salt 12345 test'
# password=test
passwd: $1$12345$CQruoOSylf9ItA76Hhqh2.
package_upgrade: true
package_update: true
view raw cloud_config.yaml hosted with ❤ by GitHub

Create a packer template:

"variables": {
"hcloud_token": "{{env `HCLOUD_TOKEN`}}"
"sensitive-variables": ["hcloud_token"],
"builders": [{
"type": "hcloud",
"token": "{{user `hcloud_token`}}",
"image": "ubuntu-18.04",
"location": "nbg1",
"server_type": "cx11",
"ssh_username": "root",
"user_data_file": "cloud_config.yaml",
"snapshot_name": "basetemplate_ubuntu_18_04",
"snapshot_labels": { "name": "packer_ubuntu_18_04_docker" }
view raw base_template.json hosted with ❤ by GitHub

Setting your API token:

export HCLOUD_TOKEN="your_Hetzner_cloud_token"

Run packer:

packer build base_template.json