Setting up Cloudflared Ingress on NixOS

Setting up Cloudflared Ingress on NixOS

This playbook guides you through how to onboard a NixOS machine to have working HTTPS ingress using cloudflared.

Creating a Tunnel

  1. Ensure you have cloudflared. You may use nix run nixpkgs#cloudflared -- for your convenience.
  2. Create the tunnel: cloudflared tunnel create {machine}-{for-host-suffix}:
  • Example machine name: nixos-aux-1
  • Example host suffix: space for dma.space
  • Resulting tunnel name: nixos-aux-1-space
  1. Pay attention to the command output, which points to a ~/.cloudflared/{UUID}.json file. Copy this file's content.
  2. Add this secret to the machine's Bitwarden secrets with the name cloudflared/{machine}-{for-host-suffix}.json.

Deploying the Tunnel

First, synchronize the secrets into SOPS:

bw sync
just sync-bitwarden-secrets {machine}

For guidance on setting up the Bitwarden CLI bw, see the Bitwarden and SOPS for a NixOS Machine playbook.

Once you've validated that the secret added above is visible in the machine's secrets.bitwarden.yaml, simply copy an existing machine's http.nix into yours. For example, here is nixos-colo-komo-00's:

services.caddy = {
  enable = true;
  email = "[email protected]";
  globalConfig = ''
    debug
    auto_https disable_redirects # handled by cloudflared
  '';
  logFormat = ''
    format console
  '';
};
 
# Use cloudflared tunneling until we have a better internet situation.
# Tunnel secret was manually provisioned.
services.cloudflared = {
  enable = true;
  # for dma.space zones:
  tunnels."nixos-colo-komo-00-space" = {
    credentialsFile = "/run/secrets/cloudflared/nixos-colo-komo-00-space.json";
    default = "http://localhost:80";
  };
};
 
sops.secrets = {
  "cloudflared/nixos-colo-komo-00-space.json".owner = "root";
};

Add the http.nix import into the configuration.nix.

Adding a DNS Record

cloudflared tunnel route dns {machine}-{for-host-suffix} {subdomain}.dma.space

For example:

cloudflared tunnel route dns nixos-colo-komo-00-space infra.dma.space