Using the sops.nix Key Management Module in NixOS

sops.nix Link to sops.nix

GitHub Repository

Using Templates to Configure Structured Secret Files Link to Using Templates to Configure Structured Secret Files

GitHub CLI requires a structured hosts.yml secret file, for example:

YAML
1
2
3
4
5
6
github.com:
  users:
    JackTheMico:
      oauth_token: <token>
  git_protocol: ssh
  oauth_token: <token>
  user: JackTheMico

For such scenarios, leverage the templates feature of sops.nix combined with the config.lib.file.mkOutOfStoreSymlink function to place service-specific secret files in designated locations.

NIX
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
{moduleNameSpace, ...}: {
  inputs,
  config,
  lib,
  ...
}:
with lib; let
  cfg = config.${moduleNameSpace}.sopsnix;
  secretsPath = builtins.toString inputs.jackwy-secrets;
in {
  options.${moduleNameSpace}.sopsnix = {
    enable = mkEnableOption "User Sops.nix";
  };

  config = mkIf cfg.enable {
    sops = {
      age.keyFile = "${config.home.homeDirectory}/.config/sops/age/keys.txt";
      defaultSopsFile = "${secretsPath}/secrets.yaml";
      secrets = {
        "gh_token" = {};
      };
      templates = {
        "hosts.yml".content =
          /*
          yaml
          */
          ''
            github.com:
              users:
                JackTheMico:
                  oauth_token: "${config.sops.placeholder.gh_token}"
              git_protocol: ssh
              oauth_token: "${config.sops.placeholder.gh_token}"
              user: JackTheMico
          '';
        "nix.conf".content = ''
          access-tokens = github.com=${config.sops.placeholder.gh_token}
        '';
      };
    };
    xdg.configFile."gh/hosts.yml".source = config.lib.file.mkOutOfStoreSymlink "${config.sops.templates."hosts.yml".path}";
  };
}

Storing Secret Files in a Private Repository Link to Storing Secret Files in a Private Repository

Credit to YouTuber “EmermentalMind” for this approach: Store secret files in a private repository, then add them to flakes inputs via git+ssh. This allows related configurations to access the secrets while managing passwords/keys with Git.
Original Video

Using the sops.nix Key Management Module in NixOS

Tue Mar 25 2025
240 Words · 3 Minutes