On this entry we will cover how to create an new image in Hetzner Public Cloud by using Packer, as result we willl get a snapshot and then we can generate this new instance by using the snapshot created.

Tools used so far:

  • Ansible
  • Packer
  • hcl2_upgrade

I did not create a repo yet because it will be the first part of a personal project I’m working on, hence I will provide a couple of templates below.

You have to use your token generated from your hetzner cloud and set it up as variable.

At the end you will get something like below:

→ tree
.
├── image.json
├── image.json.pkr.hcl
├── README.md
└── setup.yml

0 directories, 4 files
  • image.json:
{
  "builders": [
    {
      "type": "hcloud",
      "token": "",
      "image": "ubuntu-18.04",
      "location": "nbg1",
      "server_type": "cx11",
      "communicator": "ssh",
      "ssh_username": "root"
    }
  ],
  "provisioners": [
    {
      "type": "shell",
      "inline": ["echo foo"]
    }
  ]
}
  • image.json.pkr.hcl (you have to set the token envariable on your terminal)
$ export PKR_VAR_hcloud_token= 
variable hcloud_token {
description = "Hetzner token"
sensitive = true # Requires terraform >= 0.14
type = string
}

source "hcloud" "autogenerated_1" {
  communicator = "ssh"
  image        = "ubuntu-18.04"
  location     = "nbg1"
  server_type  = "cx11"
  ssh_username = "root"
  token        = var.hcloud_token
}

build {
  sources = ["source.hcloud.autogenerated_1"]

  provisioner "shell" {
    inline = [
      "apt update && apt -y upgrade",
      "apt -y install python3",
      "apt -y install ansible",
      "apt -y install debian-keyring",
      "apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 648ACFD622F3D138",
      "apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 0E98404D386FA1D9",
      "apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 605C66F00D6C9793",
      "apt-get clean"
    ]
  }
  provisioner "ansible" {
    use_proxy     = false
    playbook_file = "./setup.yml"
  }
}
  • setup.yml (as example)
# maintainer: Jose Castrillo
# project: Ubuntu Hetzner

- name: 'provision image'
  hosts: default
  become: yes

  tasks:

# adding new repo to install podman
    - apt_repository:
        repo: deb http://ftp.es.debian.org/debian bullseye main
        state: present

    #
    # basic packages
    #
    - name: basis packages
      ansible.builtin.apt:
        state: latest
        lock_timeout: 300
        name: 
        - lvm2
        - unzip
        - vim 
        - uidmap
        - git
        - buildah
        - podman
        # - ossec-hids-agent

commands sorted:

$ export PKR_VAR_hcloud_token= <your_token>
$ packer hcl2_upgrade -with-annotations image.json
# edit your image.json.pkr.hcl 
$ vim image.json.pkr.hcl
$ packer validate image.json.pkr.hcl
$ packer build image.json.pkr.hcl

Official link

Packer JSON to HCL