Bootstrapping K3s with Ansible

Overview

Deploying a production-grade K3s cluster requires more than running an installation script. In infra-bootstrap-tools, Ansible orchestrates the complete lifecycle:

  1. Host Hardening: Firewalls locked down, ports isolated (k3s_os_hardening).
  2. Control Plane Provisioning: Declarative configuration, localhost API binding, token extraction (k3s_server).
  3. GitOps Engine Bootstrap: Flux Operator installation and GitHub authentication via 1Password (k3s_flux_bootstrap).
  4. Worker Node Joins: Automated cluster joins over private network CIDRs (k3s_agent).

All stages are executed cleanly through the unified playbook ansible/playbooks/k3s.yml (invoked via make k3s).


The 4-Stage Ansible Orchestration Pipeline

4-Stage Ansible K3s Provisioning Pipeline


Stage 1: Host Hardening (k3s_os_hardening)

A fundamental prerequisite of the Dark K3s philosophy is defense-in-depth at the host operating system level. Before K3s or container runtimes are installed, the host node is locked down using UFW (Uncomplicated Firewall) to prevent unintentional port exposure to the public internet.

The firewall follows a strict default-deny ingress security posture:

Default Incoming: DENY  โ”‚  Default Outgoing: ALLOW  โ”‚  Default Routed: DENY

Ingress Port Matrix

PortProtocolPurposeAccess Scope
8441TCPOpenZiti Controller APIPublic / Edge Clients
8442TCPOpenZiti Edge Router ListenerPublic / Mesh Routers & Tunnels
22TCPSSH AdministrationRestricted to Admin CIDR (or temporary)
6443TCPK3s Kubernetes API ServerInternal Only (k3s_os_hardening_k3s_api_cidr)
8472UDPFlannel CNI VXLAN OverlayInternal Only (k3s_os_hardening_k3s_api_cidr)
10250TCPKubelet Node APIInternal Only (k3s_os_hardening_k3s_api_cidr)

By isolating port 6443 strictly to internal network interfaces (or localhost), internet scanners cannot detect or brute-force the Kubernetes API server.

Role Configuration & Variables

Key variables defined in ansible/roles/k3s_os_hardening/defaults/main.yml:

# Default firewall policies
k3s_os_hardening_default_input: "deny"
k3s_os_hardening_default_output: "allow"

# Internal CIDR permitted to communicate with K3s API and CNI (override with your VPC/overlay CIDR)
k3s_os_hardening_k3s_api_cidr: "10.0.0.0/24"

# OpenZiti Ingress Ports
k3s_os_hardening_openziti_controller_port: 8441
k3s_os_hardening_openziti_router_port: 8442

# Management Access
k3s_os_hardening_ssh_port: 22
k3s_os_hardening_ssh_cidr: "0.0.0.0/0" # Strongly recommended to restrict to your IP

Firewall Verification

After playbook execution, verify active rules on the target host:

sudo ufw status verbose

Expected output:

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW IN    198.51.100.24
8441/tcp                   ALLOW IN    Anywhere
8442/tcp                   ALLOW IN    Anywhere
6443/tcp                   ALLOW IN    10.136.0.0/16
8472/udp                   ALLOW IN    10.136.0.0/16

Stage 2: Declarative Control Plane (k3s_server)

Early iterations of K3s automation relied on passing flags via systemd unit environment variables (INSTALL_K3S_EXEC). This approach was brittle and caused unnecessary service reloads on routine playbook runs.

The current implementation renders K3s’s native declarative configuration file at /etc/rancher/k3s/config.yaml:

# /etc/rancher/k3s/config.yaml
write-kubeconfig-mode: "600"
bind-address: "127.0.0.1"
tls-san:
  - "k3s.ziti"
disable:
  - "traefik"

Architectural Parameters Explained

  • bind-address: 127.0.0.1: Forces the K3s API server to listen strictly on loopback. It cannot be reached via public or private cloud network cards directly.
  • tls-san: ["k3s.ziti"]: Injects the virtual zero-trust hostname into the API server’s TLS x509 certificate, ensuring client tools like kubectl validate TLS certificates cleanly when connecting through the OpenZiti tunnel.
  • disable: ["traefik"]: Omits the default bundled Traefik ingress controller, delegating ingress to our GitOps platform layer.

Token Capture for Worker Nodes

Upon service startup, the role securely reads the cluster join token from /var/lib/rancher/k3s/server/node-token and registers it as an in-memory fact:

- name: Read node-token from master
  ansible.builtin.slurp:
    src: /var/lib/rancher/k3s/server/node-token
  register: node_token

- name: Store master node token
  ansible.builtin.set_fact:
    k3s_server_token: "{{ node_token.content | b64decode | trim }}"

Stage 3: GitOps Bootstrap (k3s_flux_bootstrap)

Once the K3s API server is operational on localhost, Ansible connects FluxCD to our monorepo:

  1. Secret Lookup via 1Password: The role uses Ansible’s community.general.onepassword lookup plugin to retrieve the GitHub Personal Access Token (GitHub_Flux_Token) stored in the infra-bootstrap-tools vault. No credentials are ever stored in Git:
    k3s_flux_bootstrap_github_token: "{{ lookup('community.general.onepassword', 'GitHub_Flux_Token', vault='infra-bootstrap-tools', field='password') }}"
    
  2. Install Flux Operator: Installs the ControlPlane Flux Operator, which manages the lifecycle of the Flux controllers.
  3. Deploy FluxInstance: Renders and applies the FluxInstance CRD pointing to the cluster’s fleet OCI artifact:
    apiVersion: fluxcd.controlplane.io/v1
    kind: FluxInstance
    metadata:
      name: flux
      namespace: flux-system
    spec:
      distribution:
        version: "2.x"
      sync:
        kind: OCIRepository
        url: "oci://ghcr.io/xnok/infra-bootstrap-tools/manifests/fleet/k3s"
        ref:
          tag: latest
        path: "."
        pullSecret: flux-system
    

From this moment forward, the cluster self-manages via GitOps!


Stage 4: Worker Node Joins (k3s_agent)

For multi-node topologies, worker nodes in the k3s_agents inventory group join the control plane automatically:

- name: Setup K3s Agents
  hosts: k3s_agents
  become: true
  roles:
    - role: k3s_agent
      vars:
        k3s_agent_server_url: "https://{{ hostvars[groups['k3s_servers'][0]]['ansible_default_ipv4']['address'] }}:6443"
        k3s_agent_token: "{{ hostvars[groups['k3s_servers'][0]]['k3s_server_token'] }}"

Workers connect directly over private cloud VPC networking using the captured token and join the Flannel VXLAN overlay.


Executing the Deployment

Builds the collection package and runs the full K3s playbook in one command:

make k3s

Direct Ansible Playbook Invocation

ansible-playbook -i ansible/playbooks/inventory/ ansible/playbooks/k3s.yml

Verification

Once complete, log in to the server or connect via your OpenZiti tunnel:

# Verify nodes are Ready:
kubectl get nodes -o wide

# Verify Flux controllers are reconciling:
flux get all -A