Skip to content

Automate the Cluster

First PublishedLast UpdatedByAtif Alam

Alternate path for the HA Kubernetes on Two Proxmox Hosts series. Finish Proxmox Cluster by hand, then use this page instead of pasting the commands on pages 2–5. Every Terraform and Ansible file is printed in The Files. Save those blocks into one folder on your machine. The heading is the path inside that folder.

The host-loss drills were not run through this path. After Ansible finishes, run the power-off drills and the VIP check from the command pages.

Terraform (bpg/proxmox 0.123.1) creates two Ubuntu 24.04 templates and the six guests. Ansible then matches the command pages: node prep, external etcd, kube-vip, kubeadm, Cilium, and Longhorn. Tags stop at the same page boundaries, in order:

TagCommand page
node-prepProvision the Six VMs, step 3
etcdExternal etcd and kubeadm, steps 1–2
control-planeThat page, steps 3–6
workers-cniWorkers, CNI, and VIP Failover, steps 1–2
longhornLonghorn and Failure Drills, steps 1–2. Step 3 is kubectl apply -f apps/drill/ after the tag.

Versions are the ones already pinned on those pages: Kubernetes v1.33.4, etcd v3.5.24, kube-vip v0.8.10, Cilium 1.17.6, Longhorn 1.8.2.

The SSH public key in Terraform is your operator key. Ansible uses the matching private key from the machine where you run the playbook. That differs from the command page, which installs each Proxmox host’s root key because you SSH from that host.

On the operator machine: Terraform 1.5 or newer, Ansible, an SSH key, HTTPS to port 8006 on one Proxmox host, and SSH to the six guests and the tiebreaker. On a Mac with Homebrew:

Terminal window
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
brew install ansible

In the Proxmox UI, Datacenter → Storage → local → Edit, add the Import content type. local-zfs holds the VM disks in this lab. It cannot hold the downloaded cloud image. On an LVM-thin host, set vm_datastore = "local-lvm" in terraform.tfvars instead.

Create an API token (Datacenter → Permissions → API Tokens) for a user in the Administrator group. Leave Privilege Separation unchecked. A separated token has none of the user’s privileges. Pass it as TF_VAR_proxmox_api_token in the form user@pam!name=secret. Do not write the secret into terraform.tfvars.

Apply only when VMIDs 9000, 9001, 101–103, and 111–113 are free. Do not run terraform destroy against a cluster that has already been bootstrapped.

The tiebreaker is not a Terraform VM. Docker is already installed there. tiebreaker_user needs passwordless sudo; the etcd play uses become: true and runs docker as root. The account does not need to run docker itself. The etcd play does not upgrade packages on that host. Do not apt full-upgrade that NAS.

Before the control-plane tag, create /volume1/etcd-backup and /volume1/longhorn-backup on the tiebreaker, grant the lab subnet (sample 10.0.0.0/24) read/write on each folder over NFS, and turn the NAS NFS service on. A folder permission alone leaves port 2049 closed — on UGOS the switch is File Service → NFS. Confirm with nc -vz 10.0.0.91 2049. Connection refused means nfsd is not listening. An SSH public key is not NFS write access. etcd-backup is mounted at /mnt/backup on both control planes. longhorn-backup is only the Longhorn backup URL.

The sample addresses under the heading terraform/terraform.tfvars.example in The Files are one 10.0.0.0/24 subnet. Replace every value, including the Proxmox node names (pve-a and pve-b are placeholders).

Make a new folder on the machine that will run Terraform. Call it whatever you like. Inside it, save every terraform/... block from The Files. The heading terraform/versions.tf means a file named versions.tf in a terraform directory.

The heading terraform/terraform.tfvars.example is the sample variable file. Save a second copy of that block as terraform/terraform.tfvars and put your addresses, node names, and SSH public key in it. There is no file to copy from disk. The example exists only on this page.

From that terraform directory:

Terminal window
export TF_VAR_proxmox_api_token='lab@pam!ha=replace-with-the-token-secret'
terraform init
terraform apply

Apply writes ansible/inventory/hosts.yml in the Ansible directory next to terraform. That inventory is generated. Change terraform.tfvars and apply again rather than editing the inventory.

Each template stays on its own host (ubuntu-2404-a is VMID 9000, ubuntu-2404-b is 9001). Clones do not cross hosts, because a cross-node clone of a non-shared local datastore (local-zfs in this lab) migrates the disk and would place both etcd members on one machine. Guest names become the hostnames kubeadm uses as node names. Memory ballooning is off (floating = 0). The QEMU guest agent is left disabled.

If ansible-playbook is missing on a Mac with Homebrew:

Terminal window
brew install ansible

In the same folder, save every ansible/... block from The Files. The heading ansible/site.yml means a file named site.yml in an ansible directory next to terraform. In ansible/ansible.cfg, set private_key_file to the private key that matches the public key in terraform.tfvars.

From that ansible directory, after terraform apply has written inventory/hosts.yml:

Terminal window
ansible-playbook site.yml

The first play waits for SSH and for cloud-init status --wait. Proxmox still upgrades packages on first boot, and an API token cannot turn that off, so Ansible waits instead of racing apt. Gathering Facts and Wait for SSH can succeed on all six guests while Wait until cloud-init finishes fails if Ansible treats every non-zero exit as failure.

After cloud-init status --wait returns: exit 0 is a clean done; exit 2 is degraded done (boot finished — often a recoverable deprecation because Proxmox still writes the old cloud-init user key); exit 1 is a real error. The node-prep wait accepts exit 0 or 2 when stdout contains status: done. The failed_when value must be one double-quoted YAML string; an unquoted status: done does not parse.

To stop at a page boundary:

Terminal window
ansible-playbook site.yml --tags node-prep
ansible-playbook site.yml --tags etcd
ansible-playbook site.yml --tags control-plane
ansible-playbook site.yml --tags workers-cni
ansible-playbook site.yml --tags longhorn

For a dry-run preview (Ansible check mode, not a Terraform-style plan):

Terminal window
ansible-playbook site.yml --check --diff
ansible-playbook site.yml --tags node-prep --check --diff

Many tasks on this page (command/shell, kubeadm, Docker, package installs) skip check support or report poorly. A clean check run does not mean the real apply is safe or a no-op. Run without --check when you intend to change the guests.

Run the tags in that order. A later tag creates a fresh kubeadm token. Tokens are not stored in git. A second run skips kubeadm init when /etc/kubernetes/admin.conf exists, leaves an existing etcd data directory in place, and does not point kube-vip back at super-admin.conf. kube-vip uses the guest’s default-route interface. On Ubuntu 24.04 that is often ens18.

If /opt/etcd/data/member already exists, the tiebreaker task starts (or replaces) the container with --initial-cluster-state existing. An empty data directory still uses new. An existing container is left alone only when its image is already quay.io/coreos/etcd:v3.5.24; otherwise the container is replaced. The members task reinstalls the etcd binary when it is older than the pin and restarts one active member at a time.

After node-prep, on each guest: systemctl is-active containerd, kubeadm version -o short, and free -h showing swap at 0B. grep on the containerd config shows SystemdCgroup = true.

After etcd, etcdctl endpoint health from cp1 reports three healthy members. The etcd CA key stays on cp1.

After control-plane:

Terminal window
kubectl --kubeconfig /etc/kubernetes/admin.conf get nodes

Both control planes are listed. NotReady is expected until Cilium is installed. Snapshot timers are etcd-snapshot.timer at 01:00 on cp1 and 02:00 on cp2.

After workers-cni, six nodes are Ready and the workers show host-a or host-b:

Terminal window
kubectl --kubeconfig /etc/kubernetes/admin.conf get nodes -L topology.kubernetes.io/zone

After longhorn, the longhorn StorageClass exists and the daily RecurringJob is applied. The drill apps are not part of that tag. Apply them with kubectl apply -f apps/drill/ (see Longhorn and Failure Drills Step 3), then confirm drill-web and drill-data are running. Copy /etc/kubernetes/admin.conf off cp1 before the drills if you want kubectl on your workstation.

Stop kubelet on the VIP holder and watch the API, as in Workers, CNI, and VIP Failover. Then power off each Proxmox host in turn, as in Longhorn and Failure Drills. Those steps are not Ansible tasks.

Each file heading is the path under the folder you create in Run Terraform. terraform/terraform.tfvars and ansible/inventory/hosts.yml are not listed. You write the first from the example block. Terraform writes the second.

Pins Terraform and the Proxmox/local providers so applies stay reproducible.

terraform {
required_version = ">= 1.5.0"
required_providers {
proxmox = {
source = "bpg/proxmox"
version = "0.123.1"
}
local = {
source = "hashicorp/local"
version = "2.5.3"
}
}
}

Configures the Proxmox API endpoint and token for the provider.

provider "proxmox" {
endpoint = var.proxmox_endpoint
api_token = var.proxmox_api_token
insecure = true
ssh {
agent = false
}
}

Declares every input: node names, guest IPs, VIP, SSH key, NFS, and Longhorn backup target.

variable "proxmox_endpoint" {
type = string
description = "Cluster API on either Proxmox host, for example https://10.0.0.3:8006/"
}
variable "proxmox_api_token" {
type = string
sensitive = true
description = "API token user@realm!tokenid=secret. Create it with privilege separation off."
}
variable "node_a_name" {
type = string
description = "Proxmox node name for Host A, as shown by pvecm status."
}
variable "node_b_name" {
type = string
description = "Proxmox node name for Host B."
}
variable "ssh_public_key" {
type = string
description = "Operator public key for the ubuntu user. Ansible uses the matching private key."
validation {
condition = can(regex("^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256) ", var.ssh_public_key))
error_message = "ssh_public_key must be one OpenSSH public key line."
}
}
variable "bridge" {
type = string
default = "vmbr0"
description = "Proxmox bridge shared by both hosts."
}
variable "image_datastore" {
type = string
default = "local"
description = "Directory datastore that accepts the Import content type."
}
variable "vm_datastore" {
type = string
default = "local-lvm"
description = "Datastore for VM disks and cloud-init. Not shared between hosts."
}
variable "gateway" {
type = string
description = "IPv4 gateway for the guests."
}
variable "prefix_length" {
type = number
default = 24
description = "Prefix length for every guest address."
}
variable "dns_servers" {
type = list(string)
description = "Resolvers written into cloud-init. Required once the address is static."
}
variable "cp1_ip" {
type = string
}
variable "cp2_ip" {
type = string
}
variable "worker1_ip" {
type = string
}
variable "worker2_ip" {
type = string
}
variable "worker3_ip" {
type = string
}
variable "worker4_ip" {
type = string
}
variable "vip" {
type = string
description = "Kubernetes API VIP. Must sit outside the DHCP pool."
}
variable "tiebreaker_ip" {
type = string
description = "Always-on host for etcd3. Terraform does not create this machine."
}
variable "tiebreaker_user" {
type = string
default = "root"
description = "SSH user who can sudo without a password prompt. The etcd play becomes root to run docker."
}
variable "nfs_export" {
type = string
description = "NFS export mounted at /mnt/backup on both control planes, host:/path."
}
variable "longhorn_backup_target" {
type = string
description = "Longhorn backup target URL, for example nfs://10.0.0.91:/volume1/longhorn-backup."
}

Holds pinned component versions, per-host template VMIDs, and the six-guest layout.

locals {
# Pins from the series version matrix and the command pages.
kubernetes_version = "v1.33.4"
etcd_version = "v3.5.24"
kube_vip_version = "v0.8.10"
cilium_version = "1.17.6"
longhorn_version = "1.8.2"
nodes = {
a = {
name = var.node_a_name
template_id = 9000
}
b = {
name = var.node_b_name
template_id = 9001
}
}
# VMIDs are unique across the cluster. Clones stay on the template's node
# because local-zfs (or local-lvm) is not shared; a cross-node clone migrates the disk.
vms = {
cp1 = {
id = 101
node = "a"
ip = var.cp1_ip
disk = 60
zone = "host-a"
role = "control"
etcd_name = "etcd1"
snapshot_hour = 1
}
"worker-1" = {
id = 102
node = "a"
ip = var.worker1_ip
disk = 150
zone = "host-a"
role = "worker"
etcd_name = ""
snapshot_hour = 0
}
"worker-2" = {
id = 103
node = "a"
ip = var.worker2_ip
disk = 150
zone = "host-a"
role = "worker"
etcd_name = ""
snapshot_hour = 0
}
cp2 = {
id = 111
node = "b"
ip = var.cp2_ip
disk = 60
zone = "host-b"
role = "control"
etcd_name = "etcd2"
snapshot_hour = 2
}
"worker-3" = {
id = 112
node = "b"
ip = var.worker3_ip
disk = 150
zone = "host-b"
role = "worker"
etcd_name = ""
snapshot_hour = 0
}
"worker-4" = {
id = 113
node = "b"
ip = var.worker4_ip
disk = 150
zone = "host-b"
role = "worker"
etcd_name = ""
snapshot_hour = 0
}
}
vm_order = ["cp1", "worker-1", "worker-2", "cp2", "worker-3", "worker-4"]
etcd_initial_cluster = join(",", [
"etcd1=https://${var.cp1_ip}:2380",
"etcd2=https://${var.cp2_ip}:2380",
"etcd3=https://${var.tiebreaker_ip}:2380",
])
etcd_members = [
{ name = "etcd1", ip = var.cp1_ip },
{ name = "etcd2", ip = var.cp2_ip },
{ name = "etcd3", ip = var.tiebreaker_ip },
]
}

Downloads the Ubuntu cloud image and builds one template per Proxmox host.

resource "proxmox_download_file" "ubuntu" {
for_each = local.nodes
content_type = "import"
datastore_id = var.image_datastore
node_name = each.value.name
url = "https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img"
# The URL ends in .img. Import needs a .qcow2 name so Proxmox treats it as qcow2.
file_name = "noble-server-cloudimg-amd64.qcow2"
overwrite = false
}
resource "proxmox_virtual_environment_vm" "template" {
for_each = local.nodes
name = "ubuntu-2404-${each.key}"
node_name = each.value.name
vm_id = each.value.template_id
template = true
started = false
description = "Ubuntu 24.04 cloud-image template. Never boot this VM."
reboot_after_update = false
stop_on_destroy = true
scsi_hardware = "virtio-scsi-pci"
boot_order = ["scsi0"]
agent {
enabled = false
}
cpu {
cores = 2
}
memory {
dedicated = 2048
floating = 0
}
disk {
datastore_id = var.vm_datastore
import_from = proxmox_download_file.ubuntu[each.key].id
interface = "scsi0"
file_format = "raw"
size = 8
}
network_device {
bridge = var.bridge
}
operating_system {
type = "l26"
}
serial_device {}
vga {
type = "serial0"
}
initialization {
datastore_id = var.vm_datastore
user_account {
username = "ubuntu"
keys = [trimspace(var.ssh_public_key)]
}
}
}

Clones the six guests from the same-host templates and writes cloud-init addresses.

resource "proxmox_virtual_environment_vm" "guest" {
for_each = local.vms
name = each.key
node_name = local.nodes[each.value.node].name
vm_id = each.value.id
reboot_after_update = false
stop_on_destroy = true
started = true
scsi_hardware = "virtio-scsi-pci"
boot_order = ["scsi0"]
clone {
vm_id = local.nodes[each.value.node].template_id
node_name = local.nodes[each.value.node].name
full = true
}
agent {
enabled = false
}
cpu {
cores = 2
}
memory {
dedicated = 4096
floating = 0
}
disk {
datastore_id = var.vm_datastore
interface = "scsi0"
size = each.value.disk
file_format = "raw"
discard = "on"
}
network_device {
bridge = var.bridge
}
operating_system {
type = "l26"
}
serial_device {}
vga {
type = "serial0"
}
initialization {
datastore_id = var.vm_datastore
dns {
servers = var.dns_servers
}
ip_config {
ipv4 {
address = "${each.value.ip}/${var.prefix_length}"
gateway = var.gateway
}
}
user_account {
username = "ubuntu"
keys = [trimspace(var.ssh_public_key)]
}
}
depends_on = [proxmox_virtual_environment_vm.template]
}

Prints guest addresses and writes the Ansible inventory from the template below.

resource "local_file" "ansible_inventory" {
filename = "${path.module}/../ansible/inventory/hosts.yml"
file_permission = "0644"
content = templatefile("${path.module}/templates/hosts.yml.tftpl", {
vip = var.vip
kubernetes_version = local.kubernetes_version
etcd_version = local.etcd_version
kube_vip_version = local.kube_vip_version
cilium_version = local.cilium_version
longhorn_version = local.longhorn_version
nfs_export = var.nfs_export
longhorn_backup_target = var.longhorn_backup_target
etcd_initial_cluster = local.etcd_initial_cluster
etcd_members = local.etcd_members
vm_order = local.vm_order
vms = local.vms
tiebreaker_ip = var.tiebreaker_ip
tiebreaker_user = var.tiebreaker_user
})
}
output "ansible_inventory" {
value = local_file.ansible_inventory.filename
description = "Generated Ansible inventory. The private key path stays in ansible/ansible.cfg."
}

Sample values for one 10.0.0.0/24 lab. Copy to terraform.tfvars and replace every field.

# Copy to terraform.tfvars and replace every address. One subnet.
# Pass the token in the environment, not in this file:
# export TF_VAR_proxmox_api_token='lab@pam!ha=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
proxmox_endpoint = "https://10.0.0.3:8006/"
node_a_name = "pve-a"
node_b_name = "pve-b"
vm_datastore = "local-zfs"
ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleReplaceWithYourPublicKey operator@lab"
gateway = "10.0.0.1"
dns_servers = ["10.0.0.1"]
cp1_ip = "10.0.0.21"
cp2_ip = "10.0.0.22"
worker1_ip = "10.0.0.31"
worker2_ip = "10.0.0.32"
worker3_ip = "10.0.0.33"
worker4_ip = "10.0.0.34"
vip = "10.0.0.100"
tiebreaker_ip = "10.0.0.91"
tiebreaker_user = "root"
nfs_export = "10.0.0.91:/volume1/etcd-backup"
longhorn_backup_target = "nfs://10.0.0.91:/volume1/longhorn-backup"

Jinja-free Terraform template that becomes ansible/inventory/hosts.yml after apply.

---
all:
vars:
vip: ${vip}
kubernetes_version: ${kubernetes_version}
etcd_version: ${etcd_version}
kube_vip_version: ${kube_vip_version}
cilium_version: ${cilium_version}
longhorn_version: ${longhorn_version}
nfs_export: ${nfs_export}
longhorn_backup_target: ${longhorn_backup_target}
etcd_initial_cluster: ${etcd_initial_cluster}
etcd_members:
%{ for member in etcd_members ~}
- name: ${member.name}
ip: ${member.ip}
%{ endfor ~}
children:
control_planes:
hosts:
%{ for name in vm_order ~}
%{ if vms[name].role == "control" ~}
${name}:
ansible_host: ${vms[name].ip}
ansible_user: ubuntu
zone: ${vms[name].zone}
etcd_name: ${vms[name].etcd_name}
snapshot_hour: ${vms[name].snapshot_hour}
%{ endif ~}
%{ endfor ~}
workers:
hosts:
%{ for name in vm_order ~}
%{ if vms[name].role == "worker" ~}
${name}:
ansible_host: ${vms[name].ip}
ansible_user: ubuntu
zone: ${vms[name].zone}
%{ endif ~}
%{ endfor ~}
kubernetes:
children:
control_planes: {}
workers: {}
tiebreaker:
hosts:
etcd3:
ansible_host: ${tiebreaker_ip}
ansible_user: ${tiebreaker_user}

Provider lockfile from terraform init. Keep it so both machines resolve the same provider builds.

# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.
provider "registry.terraform.io/bpg/proxmox" {
version = "0.123.1"
constraints = "0.123.1"
hashes = [
"h1:o2WB8TBLv+zibOCmf2bmeQpWkKwGLpsPMZjLsswl/lI=",
"zh:0000f7dc8dd600e701ab147b0db5617e756bb04861150e53de37ff17d41d1853",
"zh:15957a774dd0f5e453a83527b850e05c4d8ee389c7358a0aafdeaea4428912b6",
"zh:1d5139930680edbd32b404fff806a0230cbed91521c9b4ecf9431d30a3388a81",
"zh:406a6d0c475ddf525bfe55de406b4baf98c2b10ce0fdb6de068bde9a92a686ab",
"zh:4366bff7e4939fb0be16f018fafab885215016fa982ad604bcc810c6b07cd7e9",
"zh:64ce278264b3a38e9cb7943c526da5a1bfb7ae2a41ee8ee79223bfc2d210f9cf",
"zh:76dea73e4e5ba8083acf243599a753fa2cd3923a094685d453769f3388ff4c7c",
"zh:7784f6634ecdea0d48e23fab65f1ea717613884355e31e6f75e8dce5225d6f33",
"zh:a0ad0783be944e6a9736e17d81a16814ed5e87bd38e114e9d5d41a8c8c4186a2",
"zh:aa718a9fa3b94edbfae23bd824ad1dea73ac82c0ce809afb7d4c322cc6cfbb5c",
"zh:b56ba73f6af2d784efca40d877f26407fd1c085f03c93e1f05fc339fc8fd1c96",
"zh:d1a136278b50915dd122710355d0a17406fee62286a645f9414a6ebfecd6cccc",
"zh:da299008135425f1c6f5ae83dc5c45ceab475d7e24bee8dae40a3aa7edcd475f",
"zh:f26e0763dbe6a6b2195c94b44696f2110f7f55433dc142839be16b9697fa5597",
]
}
provider "registry.terraform.io/hashicorp/local" {
version = "2.5.3"
constraints = "2.5.3"
hashes = [
"h1:MCzg+hs1/ZQ32u56VzJMWP9ONRQPAAqAjuHuzbyshvI=",
"zh:284d4b5b572eacd456e605e94372f740f6de27b71b4e1fd49b63745d8ecd4927",
"zh:40d9dfc9c549e406b5aab73c023aa485633c1b6b730c933d7bcc2fa67fd1ae6e",
"zh:6243509bb208656eb9dc17d3c525c89acdd27f08def427a0dce22d5db90a4c8b",
"zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3",
"zh:885d85869f927853b6fe330e235cd03c337ac3b933b0d9ae827ec32fa1fdcdbf",
"zh:bab66af51039bdfcccf85b25fe562cbba2f54f6b3812202f4873ade834ec201d",
"zh:c505ff1bf9442a889ac7dca3ac05a8ee6f852e0118dd9a61796a2f6ff4837f09",
"zh:d36c0b5770841ddb6eaf0499ba3de48e5d4fc99f4829b6ab66b0fab59b1aaf4f",
"zh:ddb6a407c7f3ec63efb4dad5f948b54f7f4434ee1a2607a49680d494b1776fe1",
"zh:e0dafdd4500bec23d3ff221e3a9b60621c5273e5df867bc59ef6b7e41f5c91f6",
"zh:ece8742fd2882a8fc9d6efd20e2590010d43db386b920b2a9c220cfecc18de47",
"zh:f4c6b3eb8f39105004cf720e202f04f57e3578441cfb76ca27611139bc116a82",
]
}

Default inventory path, SSH settings, and the private key Ansible uses for the guests.

[defaults]
inventory = inventory/hosts.yml
host_key_checking = True
retry_files_enabled = False
interpreter_python = auto_silent
# Private key that matches ssh_public_key in terraform.tfvars.
private_key_file = ~/.ssh/id_ed25519
[ssh_connection]
ssh_args = -o StrictHostKeyChecking=accept-new
[privilege_escalation]
become_method = sudo

Hand-filled inventory shape for reference. Prefer the file Terraform generates after apply.

---
all:
vars:
vip: 10.0.0.100
kubernetes_version: v1.33.4
etcd_version: v3.5.24
kube_vip_version: v0.8.10
cilium_version: 1.17.6
longhorn_version: 1.8.2
nfs_export: 10.0.0.91:/volume1/etcd-backup
longhorn_backup_target: nfs://10.0.0.91:/volume1/longhorn-backup
etcd_initial_cluster: etcd1=https://10.0.0.21:2380,etcd2=https://10.0.0.22:2380,etcd3=https://10.0.0.91:2380
etcd_members:
- name: etcd1
ip: 10.0.0.21
- name: etcd2
ip: 10.0.0.22
- name: etcd3
ip: 10.0.0.91
children:
control_planes:
hosts:
cp1:
ansible_host: 10.0.0.21
ansible_user: ubuntu
zone: host-a
etcd_name: etcd1
snapshot_hour: 1
cp2:
ansible_host: 10.0.0.22
ansible_user: ubuntu
zone: host-b
etcd_name: etcd2
snapshot_hour: 2
workers:
hosts:
worker-1:
ansible_host: 10.0.0.31
ansible_user: ubuntu
zone: host-a
worker-2:
ansible_host: 10.0.0.32
ansible_user: ubuntu
zone: host-a
worker-3:
ansible_host: 10.0.0.33
ansible_user: ubuntu
zone: host-b
worker-4:
ansible_host: 10.0.0.34
ansible_user: ubuntu
zone: host-b
kubernetes:
children:
control_planes: {}
workers: {}
tiebreaker:
hosts:
etcd3:
ansible_host: 10.0.0.91
ansible_user: root

Top-level playbook: wait for cloud-init, then run each role behind the page-boundary tags.

---
- name: Prepare the six guests
hosts: kubernetes
become: true
tags: [node-prep]
roles:
- node_prep
- name: Generate etcd certificates on cp1
hosts: cp1
become: true
tags: [etcd]
tasks:
- name: Certificates
ansible.builtin.import_role:
name: etcd
tasks_from: certs
- name: Start etcd1 and etcd2
hosts: control_planes
become: true
tags: [etcd]
tasks:
- name: Systemd members
ansible.builtin.import_role:
name: etcd
tasks_from: members
- name: Start etcd3 on the tiebreaker
hosts: tiebreaker
gather_facts: false
become: true
tags: [etcd]
tasks:
- name: Docker member
ansible.builtin.import_role:
name: etcd
tasks_from: tiebreaker
- name: Check etcd quorum
hosts: cp1
become: true
tags: [etcd]
tasks:
- name: Quorum
ansible.builtin.import_role:
name: etcd
tasks_from: health
- name: Bootstrap both control planes
hosts: control_planes
become: true
tags: [control-plane]
roles:
- control_plane
- name: Join workers and install Cilium
hosts: workers
become: true
tags: [workers-cni]
tasks:
- name: Join
ansible.builtin.import_role:
name: workers_cni
tasks_from: join
- name: Label workers and install Cilium
hosts: cp1
become: true
tags: [workers-cni]
tasks:
- name: Cilium
ansible.builtin.import_role:
name: workers_cni
tasks_from: cilium
- name: Install Longhorn
hosts: cp1
become: true
tags: [longhorn]
roles:
- longhorn

Disables swap, installs containerd and kubeadm packages, and configures the systemd cgroup driver.

---
- name: Wait for SSH
ansible.builtin.wait_for_connection:
timeout: 300
become: false
- name: Wait until cloud-init finishes
ansible.builtin.command: cloud-init status --wait
register: cloud_init
changed_when: false
# Exit 2 with "status: done" is degraded, not failed. Proxmox cloud-init
# still writes the deprecated `user` key, which cloud-init reports as recoverable.
failed_when: "cloud_init.rc not in [0, 2] or 'status: done' not in cloud_init.stdout"
timeout: 600
- name: Refresh package lists
ansible.builtin.apt:
update_cache: true
cache_valid_time: 3600
- name: Kernel modules
ansible.builtin.copy:
dest: /etc/modules-load.d/k8s.conf
mode: "0644"
content: |
overlay
br_netfilter
- name: Load overlay and br_netfilter
ansible.builtin.command: modprobe {{ item }}
loop:
- overlay
- br_netfilter
changed_when: false
- name: Kubernetes sysctl
ansible.builtin.copy:
dest: /etc/sysctl.d/k8s.conf
mode: "0644"
content: |
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-iptables = 1
- name: Apply sysctl
ansible.builtin.command: sysctl --system
changed_when: false
- name: Turn swap off
ansible.builtin.command: swapoff -a
changed_when: false
- name: Comment swap in fstab
ansible.builtin.replace:
path: /etc/fstab
regexp: '^([^#].*\sswap\s.*)$'
replace: '# \1'
- name: Install chrony
ansible.builtin.apt:
name: chrony
state: present
- name: Enable chrony
ansible.builtin.systemd:
name: chrony
enabled: true
state: started
- name: Install containerd
ansible.builtin.apt:
name: containerd
state: present
- name: Point containerd at the systemd cgroup driver
ansible.builtin.script: containerd-cgroup.sh
register: containerd_cgroup
changed_when: "'updated' in containerd_cgroup.stdout"
- name: Enable containerd
ansible.builtin.systemd:
name: containerd
enabled: true
state: started
- name: Packages for the Kubernetes apt repo
ansible.builtin.apt:
name:
- apt-transport-https
- ca-certificates
- curl
- gpg
state: present
- name: Kubernetes apt key
ansible.builtin.shell: |
set -euo pipefail
install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.33/deb/Release.key | gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
args:
creates: /etc/apt/keyrings/kubernetes-apt-keyring.gpg
executable: /bin/bash
- name: Kubernetes apt source
ansible.builtin.copy:
dest: /etc/apt/sources.list.d/kubernetes.list
mode: "0644"
content: |
deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.33/deb/ /
- name: Install kubelet, kubeadm, and kubectl
ansible.builtin.apt:
name:
- kubelet
- kubeadm
- kubectl
state: present
update_cache: true
- name: Hold the Kubernetes packages
ansible.builtin.dpkg_selections:
name: "{{ item }}"
selection: hold
loop:
- kubelet
- kubeadm
- kubectl
- name: Point kubelet at systemd-resolved
ansible.builtin.copy:
dest: /etc/default/kubelet
mode: "0644"
content: |
KUBELET_EXTRA_ARGS="--resolv-conf=/run/systemd/resolve/resolv.conf"
register: kubelet_args
- name: Restart kubelet
ansible.builtin.systemd:
name: kubelet
state: restarted
enabled: true
when: kubelet_args.changed
- name: NFS client for snapshots and Longhorn backups
ansible.builtin.apt:
name: nfs-common
state: present
- name: Longhorn packages on workers
ansible.builtin.apt:
name:
- open-iscsi
- nfs-common
state: present
when: "'workers' in group_names"
- name: Enable iscsid on workers
ansible.builtin.systemd:
name: iscsid
enabled: true
state: started
when: "'workers' in group_names"

ansible/roles/node_prep/files/containerd-cgroup.sh

Section titled “ansible/roles/node_prep/files/containerd-cgroup.sh”

Sets SystemdCgroup = true in the containerd config before kubelet starts.

#!/bin/bash
set -euo pipefail
if grep -Rqs 'SystemdCgroup = true' /etc/containerd/config.toml /etc/containerd/conf.d 2>/dev/null; then
echo unchanged
exit 0
fi
mkdir -p /etc/containerd/conf.d
containerd config default > /etc/containerd/config.toml
if grep -q 'SystemdCgroup = false' /etc/containerd/config.toml; then
sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
else
cat > /etc/containerd/conf.d/k8s.toml <<'EOF'
[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runc.options]
SystemdCgroup = true
EOF
if grep -q '^imports = ' /etc/containerd/config.toml; then
sed -i 's|^imports = .*|imports = ["/etc/containerd/conf.d/*.toml"]|' /etc/containerd/config.toml
else
sed -i '1a imports = ["/etc/containerd/conf.d/*.toml"]' /etc/containerd/config.toml
fi
fi
grep -q 'SystemdCgroup = true' /etc/containerd/config.toml /etc/containerd/conf.d/*.toml
systemctl restart containerd
echo updated

Creates the etcd PKI on cp1 and copies the member certs to cp2 and the tiebreaker.

---
- name: etcd certificate directory
ansible.builtin.file:
path: /root/etcd-certs
state: directory
mode: "0700"
- name: etcd CA
ansible.builtin.command: kubeadm init phase certs etcd-ca
args:
creates: /etc/kubernetes/pki/etcd/ca.crt
- name: Member configs
ansible.builtin.template:
src: member.yaml.j2
dest: /root/etcd-certs/{{ item.name }}.yaml
mode: "0600"
loop: "{{ etcd_members }}"
- name: Member server and peer certificates
ansible.builtin.shell: |
set -euo pipefail
dest=/root/etcd-certs/{{ item.name }}
if [[ -f $dest/server.crt && -f $dest/peer.key ]]; then
exit 0
fi
kubeadm init phase certs etcd-server --config=/root/etcd-certs/{{ item.name }}.yaml
kubeadm init phase certs etcd-peer --config=/root/etcd-certs/{{ item.name }}.yaml
mkdir -p "$dest"
mv /etc/kubernetes/pki/etcd/server.crt /etc/kubernetes/pki/etcd/server.key \
/etc/kubernetes/pki/etcd/peer.crt /etc/kubernetes/pki/etcd/peer.key "$dest/"
echo updated
args:
executable: /bin/bash
loop: "{{ etcd_members }}"
changed_when: false
- name: etcd client certificates
ansible.builtin.command: kubeadm init phase certs {{ item.phase }}
args:
creates: "{{ item.creates }}"
loop:
- phase: etcd-healthcheck-client
creates: /etc/kubernetes/pki/etcd/healthcheck-client.crt
- phase: apiserver-etcd-client
creates: /etc/kubernetes/pki/apiserver-etcd-client.crt
- name: Restore etcd1 certificates on cp1
ansible.builtin.copy:
src: /root/etcd-certs/etcd1/{{ item.name }}
dest: /etc/kubernetes/pki/etcd/{{ item.name }}
remote_src: true
owner: root
group: root
mode: "{{ item.mode }}"
loop:
- { name: server.crt, mode: "0644" }
- { name: server.key, mode: "0600" }
- { name: peer.crt, mode: "0644" }
- { name: peer.key, mode: "0600" }
- name: Read cp2 and etcd3 material
ansible.builtin.slurp:
src: "{{ item.src }}"
loop:
- { src: /root/etcd-certs/etcd2/server.crt, dest: /etc/kubernetes/pki/etcd/server.crt, mode: "0644" }
- { src: /root/etcd-certs/etcd2/server.key, dest: /etc/kubernetes/pki/etcd/server.key, mode: "0600" }
- { src: /root/etcd-certs/etcd2/peer.crt, dest: /etc/kubernetes/pki/etcd/peer.crt, mode: "0644" }
- { src: /root/etcd-certs/etcd2/peer.key, dest: /etc/kubernetes/pki/etcd/peer.key, mode: "0600" }
- { src: /etc/kubernetes/pki/etcd/ca.crt, dest: /etc/kubernetes/pki/etcd/ca.crt, mode: "0644" }
- { src: /etc/kubernetes/pki/apiserver-etcd-client.crt, dest: /etc/kubernetes/pki/apiserver-etcd-client.crt, mode: "0644" }
- { src: /etc/kubernetes/pki/apiserver-etcd-client.key, dest: /etc/kubernetes/pki/apiserver-etcd-client.key, mode: "0600" }
- { src: /etc/kubernetes/pki/etcd/healthcheck-client.crt, dest: /etc/kubernetes/pki/etcd/healthcheck-client.crt, mode: "0644" }
- { src: /etc/kubernetes/pki/etcd/healthcheck-client.key, dest: /etc/kubernetes/pki/etcd/healthcheck-client.key, mode: "0600" }
register: cp2_material
- name: Certificate directories on cp2
ansible.builtin.file:
path: "{{ item }}"
state: directory
mode: "0755"
loop:
- /etc/kubernetes/pki
- /etc/kubernetes/pki/etcd
delegate_to: cp2
- name: Install etcd2 certificates on cp2
ansible.builtin.copy:
dest: "{{ item.item.dest }}"
content: "{{ item.content | b64decode }}"
owner: root
group: root
mode: "{{ item.item.mode }}"
loop: "{{ cp2_material.results }}"
delegate_to: cp2
- name: Read etcd3 certificates
ansible.builtin.slurp:
src: "{{ item }}"
loop:
- /root/etcd-certs/etcd3/server.crt
- /root/etcd-certs/etcd3/server.key
- /root/etcd-certs/etcd3/peer.crt
- /root/etcd-certs/etcd3/peer.key
- /etc/kubernetes/pki/etcd/ca.crt
register: etcd3_slurp
- name: Pack etcd3 certificates for the tiebreaker
ansible.builtin.set_fact:
etcd3_b64:
server_crt: "{{ etcd3_slurp.results[0].content | regex_replace('\\s', '') }}"
server_key: "{{ etcd3_slurp.results[1].content | regex_replace('\\s', '') }}"
peer_crt: "{{ etcd3_slurp.results[2].content | regex_replace('\\s', '') }}"
peer_key: "{{ etcd3_slurp.results[3].content | regex_replace('\\s', '') }}"
ca_crt: "{{ etcd3_slurp.results[4].content | regex_replace('\\s', '') }}"

Runs etcd1 and etcd2 as systemd units on the control planes. Reinstalls the binary when it is older than the pin and restarts one active member at a time.

---
- name: Installed etcd version
ansible.builtin.command: /usr/local/bin/etcd --version
register: etcd_installed
changed_when: false
failed_when: false
- name: Install the etcd binary
ansible.builtin.shell: |
set -euo pipefail
tmp=$(mktemp -d)
curl -fsSL -o "$tmp/etcd.tgz" "https://github.com/etcd-io/etcd/releases/download/{{ etcd_version }}/etcd-{{ etcd_version }}-linux-amd64.tar.gz"
tar -C "$tmp" -xzf "$tmp/etcd.tgz"
install -m 0755 "$tmp/etcd-{{ etcd_version }}-linux-amd64/etcd" /usr/local/bin/etcd
install -m 0755 "$tmp/etcd-{{ etcd_version }}-linux-amd64/etcdctl" /usr/local/bin/etcdctl
rm -rf "$tmp"
args:
executable: /bin/bash
when: etcd_installed.rc != 0 or (etcd_version | regex_replace('^v', '')) not in etcd_installed.stdout
register: etcd_binary
- name: etcd service activity
ansible.builtin.command: systemctl is-active etcd
register: etcd_active
failed_when: false
changed_when: false
- name: etcd data directory
ansible.builtin.stat:
path: /var/lib/etcd/member
register: etcd_data
- name: Cluster state for a member that is not running
ansible.builtin.set_fact:
etcd_cluster_state: "{{ 'existing' if etcd_data.stat.exists else 'new' }}"
when: etcd_active.stdout != "active"
- name: etcd unit
ansible.builtin.template:
src: etcd.service.j2
dest: /etc/systemd/system/etcd.service
mode: "0644"
when: etcd_active.stdout != "active"
- name: Start etcd
ansible.builtin.systemd:
name: etcd
enabled: true
state: started
daemon_reload: true
when: etcd_active.stdout != "active"
- name: Restart etcd after a binary upgrade
ansible.builtin.systemd:
name: etcd
state: restarted
when:
- etcd_binary is changed
- etcd_active.stdout == "active"
throttle: 1

Starts etcd3 in Docker on the always-on tiebreaker host. Replaces the container when the image tag differs; uses --initial-cluster-state existing when /opt/etcd/data/member already exists.

---
- name: Write etcd3 certificates and start the container
ansible.builtin.raw: |
set -eu
mkdir -p /opt/etcd/certs /opt/etcd/data
umask 077
printf '%s' '{{ hostvars["cp1"].etcd3_b64.server_crt }}' | base64 -d > /opt/etcd/certs/server.crt
printf '%s' '{{ hostvars["cp1"].etcd3_b64.server_key }}' | base64 -d > /opt/etcd/certs/server.key
printf '%s' '{{ hostvars["cp1"].etcd3_b64.peer_crt }}' | base64 -d > /opt/etcd/certs/peer.crt
printf '%s' '{{ hostvars["cp1"].etcd3_b64.peer_key }}' | base64 -d > /opt/etcd/certs/peer.key
printf '%s' '{{ hostvars["cp1"].etcd3_b64.ca_crt }}' | base64 -d > /opt/etcd/certs/ca.crt
chmod 644 /opt/etcd/certs/server.crt /opt/etcd/certs/peer.crt /opt/etcd/certs/ca.crt
chmod 600 /opt/etcd/certs/server.key /opt/etcd/certs/peer.key
desired="quay.io/coreos/etcd:{{ etcd_version }}"
state=new
if [ -d /opt/etcd/data/member ]; then
state=existing
fi
if docker inspect etcd3 >/dev/null 2>&1; then
current=$(docker inspect -f '{% raw %}{{.Config.Image}}{% endraw %}' etcd3)
if [ "$current" = "$desired" ]; then
echo already-running
exit 0
fi
docker rm -f etcd3
fi
docker run -d --name etcd3 --restart unless-stopped \
-v /opt/etcd/data:/etcd-data \
-v /opt/etcd/certs:/etcd-certs:ro \
-p 2379:2379 -p 2380:2380 \
quay.io/coreos/etcd:{{ etcd_version }} \
etcd --name etcd3 \
--data-dir /etcd-data \
--listen-peer-urls https://0.0.0.0:2380 \
--listen-client-urls https://0.0.0.0:2379 \
--initial-advertise-peer-urls https://{{ ansible_host }}:2380 \
--advertise-client-urls https://{{ ansible_host }}:2379 \
--initial-cluster {{ etcd_initial_cluster }} \
--initial-cluster-state "$state" \
--cert-file=/etcd-certs/server.crt \
--key-file=/etcd-certs/server.key \
--peer-cert-file=/etcd-certs/peer.crt \
--peer-key-file=/etcd-certs/peer.key \
--trusted-ca-file=/etcd-certs/ca.crt \
--peer-trusted-ca-file=/etcd-certs/ca.crt \
--client-cert-auth --peer-client-cert-auth
echo bootstrapped
register: etcd3_bootstrap
changed_when: "'bootstrapped' in etcd3_bootstrap.stdout"

Checks that all three etcd members report healthy before kubeadm continues.

---
- name: etcd endpoint health
ansible.builtin.command: >
etcdctl
--endpoints=https://{{ hostvars['cp1'].ansible_host }}:2379,https://{{ hostvars['cp2'].ansible_host }}:2379,https://{{ hostvars['etcd3'].ansible_host }}:2379
--cacert=/etc/kubernetes/pki/etcd/ca.crt
--cert=/etc/kubernetes/pki/apiserver-etcd-client.crt
--key=/etc/kubernetes/pki/apiserver-etcd-client.key
endpoint health
environment:
ETCDCTL_API: "3"
register: etcd_health
retries: 12
delay: 5
until: etcd_health.rc == 0
changed_when: false

ansible/roles/etcd/templates/member.yaml.j2

Section titled “ansible/roles/etcd/templates/member.yaml.j2”

kubeadm snippet that sets etcd server and peer cert SANs for each member IP.

apiVersion: kubeadm.k8s.io/v1beta4
kind: ClusterConfiguration
etcd:
local:
serverCertSANs: ["{{ item.ip }}", "127.0.0.1"]
peerCertSANs: ["{{ item.ip }}"]

ansible/roles/etcd/templates/etcd.service.j2

Section titled “ansible/roles/etcd/templates/etcd.service.j2”

systemd unit for an etcd member on cp1 or cp2.

[Unit]
Description=etcd (external member)
After=network-online.target
[Service]
ExecStart=/usr/local/bin/etcd \
--name {{ etcd_name }} \
--data-dir /var/lib/etcd \
--listen-peer-urls https://{{ ansible_host }}:2380 \
--listen-client-urls https://{{ ansible_host }}:2379,https://127.0.0.1:2379 \
--initial-advertise-peer-urls https://{{ ansible_host }}:2380 \
--advertise-client-urls https://{{ ansible_host }}:2379 \
--initial-cluster {{ etcd_initial_cluster }} \
--initial-cluster-state {{ etcd_cluster_state }} \
--cert-file=/etc/kubernetes/pki/etcd/server.crt \
--key-file=/etc/kubernetes/pki/etcd/server.key \
--peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt \
--peer-key-file=/etc/kubernetes/pki/etcd/peer.key \
--trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt \
--peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt \
--client-cert-auth --peer-client-cert-auth
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target

ansible/roles/control_plane/tasks/main.yml

Section titled “ansible/roles/control_plane/tasks/main.yml”

Mounts NFS backup, runs kubeadm init/join against the VIP, and installs snapshot timers.

---
- name: Install Helm on cp1
ansible.builtin.shell: |
set -euo pipefail
tmp=$(mktemp -d)
curl -fsSL -o "$tmp/helm.tgz" https://get.helm.sh/helm-v3.16.4-linux-amd64.tar.gz
tar -C "$tmp" -xzf "$tmp/helm.tgz"
install -m 0755 "$tmp/linux-amd64/helm" /usr/local/bin/helm
rm -rf "$tmp"
args:
creates: /usr/local/bin/helm
executable: /bin/bash
when: inventory_hostname == "cp1"
- name: kube-vip before init
ansible.builtin.import_tasks: kube_vip.yml
- name: admin.conf on this node
ansible.builtin.stat:
path: /etc/kubernetes/admin.conf
register: admin_conf
- name: kubeadm config
ansible.builtin.template:
src: kubeadm-config.yaml.j2
dest: /root/kubeadm-config.yaml
mode: "0600"
when:
- inventory_hostname == "cp1"
- not admin_conf.stat.exists
- name: kubeadm init on cp1
ansible.builtin.command: kubeadm init --config /root/kubeadm-config.yaml --upload-certs
when:
- inventory_hostname == "cp1"
- not admin_conf.stat.exists
- name: kube-vip after init
ansible.builtin.import_tasks: kube_vip.yml
when: inventory_hostname == "cp1"
- name: kubelet.conf on cp2
ansible.builtin.stat:
path: /etc/kubernetes/kubelet.conf
register: kubelet_conf
when: inventory_hostname == "cp2"
- name: Join credentials from cp1
ansible.builtin.shell: |
set -euo pipefail
join=$(kubeadm token create --print-join-command --ttl 2h)
key=$(kubeadm init phase upload-certs --upload-certs --config /root/kubeadm-config.yaml 2>&1 | awk '
/Using certificate key:/ {
if ($NF ~ /^[0-9a-f]{16,}$/) { print $NF; exit }
getline
print
exit
}
')
printf '%s --control-plane --certificate-key %s\n' "$join" "$key"
args:
executable: /bin/bash
delegate_to: cp1
register: cp_join
changed_when: false
when: inventory_hostname == "cp2" and kubelet_conf is defined and not kubelet_conf.stat.exists
- name: Join cp2
ansible.builtin.command: "{{ cp_join.stdout | trim }}"
when: inventory_hostname == "cp2" and kubelet_conf is defined and not kubelet_conf.stat.exists
- name: kube-vip after cp2 joins
ansible.builtin.import_tasks: kube_vip.yml
when: inventory_hostname == "cp2"
- name: NFS client
ansible.builtin.apt:
name: nfs-common
state: present
- name: Backup mount point
ansible.builtin.file:
path: /mnt/backup/etcd
state: directory
mode: "0755"
- name: fstab entry for the etcd backup export
ansible.builtin.lineinfile:
path: /etc/fstab
line: "{{ nfs_export }} /mnt/backup nfs defaults,_netdev 0 0"
regexp: '^\S+\s+/mnt/backup\s+'
state: present
- name: Backup export already mounted
ansible.builtin.command: mountpoint -q /mnt/backup
register: backup_mounted
changed_when: false
failed_when: false
- name: Mount the etcd backup export
ansible.builtin.command: mount /mnt/backup
when: backup_mounted.rc != 0
- name: etcd snapshot service
ansible.builtin.template:
src: etcd-snapshot.service.j2
dest: /etc/systemd/system/etcd-snapshot.service
mode: "0644"
- name: etcd snapshot timer
ansible.builtin.template:
src: etcd-snapshot.timer.j2
dest: /etc/systemd/system/etcd-snapshot.timer
mode: "0644"
- name: Enable the etcd snapshot timer
ansible.builtin.systemd:
name: etcd-snapshot.timer
enabled: true
state: started
daemon_reload: true

ansible/roles/control_plane/tasks/kube_vip.yml

Section titled “ansible/roles/control_plane/tasks/kube_vip.yml”

Places the kube-vip static pod so the API VIP is up before and after kubeadm.

---
- name: kube-vip manifest
ansible.builtin.shell: |
set -euo pipefail
mkdir -p /etc/kubernetes/manifests
if [[ ! -f /etc/kubernetes/manifests/kube-vip.yaml ]]; then
iface=$(ip route show default | awk '{print $5; exit}')
if [[ -z ${iface} ]]; then
echo "no default route; cannot choose the kube-vip interface" >&2
exit 1
fi
ctr image pull "ghcr.io/kube-vip/kube-vip:{{ kube_vip_version }}"
ctr run --rm --net-host "ghcr.io/kube-vip/kube-vip:{{ kube_vip_version }}" vip \
/kube-vip manifest pod \
--interface "$iface" --address "{{ vip }}" \
--controlplane --arp --leaderElection > /etc/kubernetes/manifests/kube-vip.yaml
echo created
fi
if [[ -f /etc/kubernetes/admin.conf ]]; then
sed -i 's#path: /etc/kubernetes/super-admin.conf#path: /etc/kubernetes/admin.conf#' /etc/kubernetes/manifests/kube-vip.yaml
else
sed -i 's#path: /etc/kubernetes/admin.conf#path: /etc/kubernetes/super-admin.conf#' /etc/kubernetes/manifests/kube-vip.yaml
fi
args:
executable: /bin/bash
register: kube_vip
changed_when: "'created' in kube_vip.stdout"

ansible/roles/control_plane/templates/kubeadm-config.yaml.j2

Section titled “ansible/roles/control_plane/templates/kubeadm-config.yaml.j2”

kubeadm ClusterConfiguration pointing at external etcd and the API VIP.

apiVersion: kubeadm.k8s.io/v1beta4
kind: ClusterConfiguration
kubernetesVersion: {{ kubernetes_version }}
controlPlaneEndpoint: "{{ vip }}:6443"
etcd:
external:
endpoints:
- https://{{ hostvars['cp1'].ansible_host }}:2379
- https://{{ hostvars['cp2'].ansible_host }}:2379
- https://{{ hostvars['etcd3'].ansible_host }}:2379
caFile: /etc/kubernetes/pki/etcd/ca.crt
certFile: /etc/kubernetes/pki/apiserver-etcd-client.crt
keyFile: /etc/kubernetes/pki/apiserver-etcd-client.key

ansible/roles/control_plane/templates/etcd-snapshot.service.j2

Section titled “ansible/roles/control_plane/templates/etcd-snapshot.service.j2”

Oneshot service that writes an etcd snapshot to the NFS backup mount.

[Unit]
Description=etcd snapshot to NFS
[Service]
Type=oneshot
ExecStart=/bin/bash -c '/usr/local/bin/etcdctl \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/apiserver-etcd-client.crt \
--key=/etc/kubernetes/pki/apiserver-etcd-client.key \
snapshot save /mnt/backup/etcd/$(hostname)-$(date +%%F).db'

ansible/roles/control_plane/templates/etcd-snapshot.timer.j2

Section titled “ansible/roles/control_plane/templates/etcd-snapshot.timer.j2”

Daily timer that triggers the snapshot service at the hour set per control plane.

[Unit]
Description=Nightly etcd snapshot
[Timer]
OnCalendar=*-*-* {{ '%02d' | format(snapshot_hour | int) }}:00:00
Persistent=true
[Install]
WantedBy=timers.target

Joins the four workers with a fresh token and applies the host-zone topology labels.

---
- name: kubelet.conf on this worker
ansible.builtin.stat:
path: /etc/kubernetes/kubelet.conf
register: worker_kubelet
- name: Worker join command
ansible.builtin.command: kubeadm token create --print-join-command --ttl 2h
delegate_to: cp1
run_once: true
changed_when: false
register: worker_join
- name: Join the worker
ansible.builtin.command: "{{ hostvars[ansible_play_hosts_all[0]].worker_join.stdout | trim }}"
when: not worker_kubelet.stat.exists

ansible/roles/workers_cni/tasks/cilium.yml

Section titled “ansible/roles/workers_cni/tasks/cilium.yml”

Installs Cilium at the pinned version so nodes leave NotReady.

---
- name: Install Helm on cp1
ansible.builtin.shell: |
set -euo pipefail
tmp=$(mktemp -d)
curl -fsSL -o "$tmp/helm.tgz" https://get.helm.sh/helm-v3.16.4-linux-amd64.tar.gz
tar -C "$tmp" -xzf "$tmp/helm.tgz"
install -m 0755 "$tmp/linux-amd64/helm" /usr/local/bin/helm
rm -rf "$tmp"
args:
creates: /usr/local/bin/helm
executable: /bin/bash
- name: Zone labels
ansible.builtin.command: >
kubectl --kubeconfig /etc/kubernetes/admin.conf label node {{ item }}
topology.kubernetes.io/zone={{ hostvars[item].zone }} --overwrite
loop: "{{ groups['workers'] }}"
changed_when: false
- name: Cilium Helm repo
ansible.builtin.command: helm repo add cilium https://helm.cilium.io/
register: cilium_repo
changed_when: "'has been added' in cilium_repo.stdout"
failed_when: cilium_repo.rc != 0 and 'already exists' not in (cilium_repo.stdout + cilium_repo.stderr)
- name: Update Helm repos
ansible.builtin.command: helm repo update
changed_when: false
- name: Install Cilium
ansible.builtin.command: >
helm upgrade --install cilium cilium/cilium
--version {{ cilium_version }}
--namespace kube-system
--set k8sServiceHost={{ vip }}
--set k8sServicePort=6443
environment:
KUBECONFIG: /etc/kubernetes/admin.conf

Installs Longhorn, sets the NFS backup target, and applies the recurring backup job. Does not deploy the drill apps.

---
- name: Install Helm on cp1
ansible.builtin.shell: |
set -euo pipefail
tmp=$(mktemp -d)
curl -fsSL -o "$tmp/helm.tgz" https://get.helm.sh/helm-v3.16.4-linux-amd64.tar.gz
tar -C "$tmp" -xzf "$tmp/helm.tgz"
install -m 0755 "$tmp/linux-amd64/helm" /usr/local/bin/helm
rm -rf "$tmp"
args:
creates: /usr/local/bin/helm
executable: /bin/bash
- name: Longhorn Helm repo
ansible.builtin.command: helm repo add longhorn https://charts.longhorn.io
register: longhorn_repo
changed_when: "'has been added' in longhorn_repo.stdout"
failed_when: longhorn_repo.rc != 0 and 'already exists' not in (longhorn_repo.stdout + longhorn_repo.stderr)
- name: Update Helm repos
ansible.builtin.command: helm repo update
changed_when: false
- name: Install Longhorn
ansible.builtin.command: >
helm upgrade --install longhorn longhorn/longhorn
--namespace longhorn-system --create-namespace
--version {{ longhorn_version }}
--set defaultSettings.defaultReplicaCount=2
--set defaultSettings.replicaZoneSoftAntiAffinity=true
--set defaultSettings.storageReservedPercentageForDefaultDisk=25
--set persistence.defaultClassReplicaCount=2
--set defaultSettings.backupTarget={{ longhorn_backup_target }}
environment:
KUBECONFIG: /etc/kubernetes/admin.conf
- name: Wait for the longhorn StorageClass
ansible.builtin.command: kubectl --kubeconfig /etc/kubernetes/admin.conf get storageclass longhorn
register: longhorn_sc
retries: 30
delay: 10
until: longhorn_sc.rc == 0
changed_when: false
- name: Backup job manifest on cp1
ansible.builtin.copy:
src: recurring-backup.yaml
dest: /root/recurring-backup.yaml
mode: "0644"
- name: Apply the backup job
ansible.builtin.command: kubectl --kubeconfig /etc/kubernetes/admin.conf apply -f /root/recurring-backup.yaml
changed_when: false
- name: Remove the old drill manifest from cp1
ansible.builtin.file:
path: /root/drill-workloads.yaml
state: absent

ansible/roles/longhorn/files/recurring-backup.yaml

Section titled “ansible/roles/longhorn/files/recurring-backup.yaml”

Daily Longhorn RecurringJob that ships volume backups to the external NFS target.

apiVersion: longhorn.io/v1beta2
kind: RecurringJob
metadata:
name: daily-backup
namespace: longhorn-system
spec:
name: daily-backup
cron: "0 2 * * *"
task: backup
groups: ["default"]
retain: 7
concurrency: 1

Sample drill-web Deployment for the host-loss drills. Not copied or applied by Ansible. A later playbook run does not recreate it after it is deleted.

apiVersion: apps/v1
kind: Deployment
metadata:
name: drill-web
spec:
replicas: 2
selector:
matchLabels:
app: drill-web
template:
metadata:
labels:
app: drill-web
spec:
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: drill-web
containers:
- name: web
image: mccutchen/go-httpbin:v2.15.0
ports:
- containerPort: 8080

drill-data PersistentVolumeClaim. Not copied or applied by Ansible.

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: drill-data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: longhorn
resources:
requests:
storage: 2Gi

drill-data Deployment. Not copied or applied by Ansible.

apiVersion: apps/v1
kind: Deployment
metadata:
name: drill-data
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: drill-data
template:
metadata:
labels:
app: drill-data
spec:
containers:
- name: data
image: mccutchen/go-httpbin:v2.15.0
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: drill-data