summaryrefslogtreecommitdiff
path: root/modules/nixos/mixins/cloudflared.nix
blob: 372103b5b6910900cb830ddb2eee9b4968252277 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
{
  config,
  lib,
  secretsDir,
  ...
}:
let
  cfg = config.mixins.cloudflared;
  inherit (config.services) nginx;
in
{
  options.mixins.cloudflared = {
    enable = lib.mkEnableOption "cloudflared mixin";
    tunnelName = lib.mkOption {
      description = ''
        Name of the default tunnel being created
      '';
      type = lib.types.str;
      default = "${config.networking.hostName}-nginx";
      defaultText = lib.literalExpression "\${config.networking.hostName}-nginx";
      example = "my-tunnel";
    };

    manageSecrets = lib.mkEnableOption "automatic management of secrets" // {
      default = config.traits.secrets.enable;
      defaultText = lib.literalExpression "config.traits.secrets.enable";
    };
  };

  config = lib.mkIf cfg.enable (
    lib.mkMerge [
      {
        services.cloudflared = {
          enable = true;
          tunnels.${cfg.tunnelName} = {
            default = "http_status:404";

            # map our virtualHosts from nginx to ingress rules
            ingress = lib.mapAttrs (_: _: {
              service = "http://localhost:${toString nginx.defaultHTTPListenPort}";
            }) nginx.virtualHosts;
          };
        };
      }

      (lib.mkIf cfg.manageSecrets {
        age.secrets.cloudflaredCreds = {
          file = secretsDir + "/cloudflaredCreds.age";
          mode = "400";
          owner = "cloudflared";
          group = "cloudflared";
        };

        services.cloudflared.tunnels.${cfg.tunnelName} = {
          credentialsFile = config.age.secrets.cloudflaredCreds.path;
        };
      })
    ]
  );
}