diff --git a/modules/sops/templates/default.nix b/modules/sops/templates/default.nix index 5b6e6923..892ad9b8 100644 --- a/modules/sops/templates/default.nix +++ b/modules/sops/templates/default.nix @@ -6,6 +6,27 @@ let cfg = config.sops; secretsForUsers = lib.filterAttrs (_: v: v.neededForUsers) cfg.secrets; users = config.users.users; + useSystemdActivation = (options.systemd ? sysusers && config.systemd.sysusers.enable) || + (options.services ? userborn && config.services.userborn.enable); + renderScript = '' + echo Setting up sops templates... + ${concatMapStringsSep "\n" (name: + let + tpl = config.sops.templates.${name}; + substitute = pkgs.writers.writePython3 "substitute" { } + (readFile ./subs.py); + subst-pairs = pkgs.writeText "pairs" (concatMapStringsSep "\n" + (name: + "${toString config.sops.placeholder.${name}} ${ + config.sops.secrets.${name}.path + }") (attrNames config.sops.secrets)); + in '' + mkdir -p "${dirOf tpl.path}" + (umask 077; ${substitute} ${tpl.file} ${subst-pairs} > ${tpl.path}) + chmod "${tpl.mode}" "${tpl.path}" + chown "${tpl.owner}:${tpl.group}" "${tpl.path}" + '') (attrNames config.sops.templates)} + ''; in { options.sops = { templates = mkOption { @@ -84,26 +105,23 @@ in { (name: _: mkDefault "") config.sops.secrets; - system.activationScripts.renderSecrets = mkIf (cfg.templates != { }) - (stringAfter ([ "setupSecrets" ] - ++ optional (secretsForUsers != { }) "setupSecretsForUsers") '' - echo Setting up sops templates... - ${concatMapStringsSep "\n" (name: - let - tpl = config.sops.templates.${name}; - substitute = pkgs.writers.writePython3 "substitute" { } - (readFile ./subs.py); - subst-pairs = pkgs.writeText "pairs" (concatMapStringsSep "\n" - (name: - "${toString config.sops.placeholder.${name}} ${ - config.sops.secrets.${name}.path - }") (attrNames config.sops.secrets)); - in '' - mkdir -p "${dirOf tpl.path}" - (umask 077; ${substitute} ${tpl.file} ${subst-pairs} > ${tpl.path}) - chmod "${tpl.mode}" "${tpl.path}" - chown "${tpl.owner}:${tpl.group}" "${tpl.path}" - '') (attrNames config.sops.templates)} - ''); + systemd.services.sops-render-secrets = let + installServices = [ "sops-install-secrets.service" ] ++ optional (secretsForUsers != { }) "sops-install-secrets-for-users.service"; + in lib.mkIf (cfg.templates != { } && useSystemdActivation) { + wantedBy = [ "sysinit.target" ]; + requires = installServices; + after = installServices; + unitConfig.DefaultDependencies = "no"; + + script = renderScript; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + }; + }; + + system.activationScripts.renderSecrets = mkIf (cfg.templates != { } && !useSystemdActivation) + (stringAfter ([ "setupSecrets" ] ++ optional (secretsForUsers != { }) "setupSecretsForUsers") + renderScript); }); }