NixOS 中密钥管理模块sops.nix的使用

Sops.nix Link to Sops.nix

github 仓库

使用templates 来配置复杂结构的密钥文件 Link to 使用templates 来配置复杂结构的密钥文件

github-cli 要求复杂结构的host.yml密钥文件,例如:

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

遇到这种情况可以使用sops.nix 的 templates 功能, 结合config.lib.file.mkOutOfStoreSymlink 函数即可把服务需要的密钥文件放到指定的位置。

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}";
  };
}

将密钥文件保存在私人仓库里 Link to 将密钥文件保存在私人仓库里

感谢Youtuber: “EmergentMind” 给出的方案:将密钥文件保存在私人仓库里,然后使用git+ssh的方式将其添加至 flakes inputs 里,这样与其相关的配置都能使用到,也能用git来管理密码和密钥。 原视频

NixOS 中密钥管理模块sops.nix的使用

Tue Mar 25 2025
347 字 · 3 分钟