Skip to content

Instantly share code, notes, and snippets.

@phaer
Last active January 14, 2022 09:47
Show Gist options
  • Save phaer/0b827580b30ff869168638f90b71b0d0 to your computer and use it in GitHub Desktop.
Save phaer/0b827580b30ff869168638f90b71b0d0 to your computer and use it in GitHub Desktop.
nixos-secret-templates
{ pkgs, lib, config, ... }:
let
cfg = config.my.secrets;
makeSecretServiceUnit = name: value:
lib.nameValuePair "secret-${value.secret}" {
description = "template for secret ${value.secret}";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script =
''
${pkgs.gomplate}/bin/gomplate \
--file ${value.template} \
--context data=/run/keys/${value.secret}?type=application/json \
--out ${name} --chmod 0400
# note that the output file should be owned by root upon creation,
# so this should be safe.
chown --reference=/run/keys/${value.secret} ${name}
chmod --reference=/run/keys/${value.secret} ${name}
'';
};
makeSecretPathUnit = _name: value:
lib.nameValuePair "secret-${value.secret}" {
wantedBy = [ "multi-user.target" ];
pathConfig =
let
path = "/run/keys/${value.secret}";
in
{
PathExists = path;
PathChanged = path;
};
};
in
{
options = with lib; with types; {
my.secrets = {
enable = lib.mkEnableOption "enable secret key upload & templating";
secrets = lib.mkOption { type = attrsOf anything; };
templates = lib.mkOption { type = attrsOf anything; };
};
};
config = {
systemd.services =
lib.mapAttrs' makeSecretServiceUnit cfg.templates;
systemd.paths =
lib.mapAttrs' makeSecretPathUnit cfg.templates;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment