nixos-config/modules/secrets-envsubst.nix

111 lines
3.1 KiB
Nix
Raw Normal View History

{ pkgs, config, lib, inputs, ... }:
with lib;
with types;
let
envsubstSecrets = { name, ... }: {
options = {
2021-01-11 21:51:09 +04:00
directory = mkOption {
type = nullOr str;
default = name;
};
secrets = mkOption { type = listOf str; };
template = mkOption { type = str; };
prefix = mkOption {
type = nullOr str;
default = null;
};
substituted = mkOption {
type = path;
default = "/var/secrets/${name}-envsubst";
};
envsubst = mkOption {
type = str;
default = "${pkgs.envsubst}/bin/envsubst -no-unset -no-empty";
};
owner = mkOption {
type = str;
default = "root:root";
};
permissions = mkOption {
type = lib.types.addCheck lib.types.str
(perm: !isNull (builtins.match "[0-7]{3}" perm));
default = "400";
};
services = mkOption {
type = listOf str;
default = [ "${name}.service" ];
};
__toString = mkOption {
readOnly = true;
default = s: s.substituted;
};
};
};
exportSecrets = name: cfg:
let prefix = lib.optionalString (!isNull cfg.prefix) "${cfg.prefix}_";
in map (secret:
''
export ${prefix}${secret}="$(cat ${
config.secrets."${name}-envsubst-${secret}".decrypted
2021-01-11 21:51:09 +04:00
})"'') cfg.secrets;
envsubst = name: cfg:
with cfg; {
"${name}-envsubst" = rec {
2021-01-11 21:51:09 +04:00
requires = [ "user@1000.service" ]
++ map (secret: "${name}-envsubst-${secret}-secrets.service")
cfg.secrets;
after = requires;
2021-01-11 21:51:09 +04:00
bindsTo = requires;
preStart = "mkdir -p '${builtins.dirOf substituted}'";
script = ''
${builtins.concatStringsSep "\n" (exportSecrets name cfg)}
2021-01-11 21:51:09 +04:00
if cat '${
builtins.toFile "template" template
}' | ${cfg.envsubst} > '${substituted}.tmp'; then
mv -f '${substituted}.tmp' '${substituted}'
chown '${owner}' '${substituted}'
chmod '${permissions}' '${substituted}'
else
echo "Failed to run the substition"
rm '${substituted}.tmp'
fi
'';
serviceConfig = {
Type = "oneshot";
RemainAfterExit = "yes";
};
};
};
addDependencies = name: cfg:
with cfg;
genAttrs services (service: rec {
requires = [ "${name}-envsubst" ];
after = requires;
2021-01-11 21:51:09 +04:00
bindsTo = requires;
});
mkServices = name: cfg: [ (envsubst name cfg) (addDependencies name cfg) ];
mkIndividualSecrets = name: cfg:
map (x: {
"${name}-envsubst-${x}" = {
2021-01-11 21:51:09 +04:00
encrypted = "/home/balsoft/.password-store/${lib.optionalString (! isNull cfg.directory) "${cfg.directory}/"}${x}.gpg";
services = [ ];
};
2021-01-11 21:51:09 +04:00
}) cfg.secrets;
in {
options.secrets-envsubst =
lib.mkOption { type = attrsOf (submodule envsubstSecrets); };
config.systemd.services =
mkMerge (concatLists (mapAttrsToList mkServices config.secrets-envsubst));
config.secrets = mkMerge
(concatLists (mapAttrsToList mkIndividualSecrets config.secrets-envsubst));
}