diff --git a/modules/consul-service-registry/default.nix b/modules/consul-service-registry/default.nix new file mode 100644 index 0000000..35b725c --- /dev/null +++ b/modules/consul-service-registry/default.nix @@ -0,0 +1,47 @@ +{ config, lib, ... }: + +with lib; + +let + cfg = config.consul; + + consul = "${config.services.consul.package}/bin/consul"; + + consulServiceDefinition = submodule ({ name, ... }: { + unit = mkOption { + description = "Which systemd service to attach to."; + default = name; + type = types.str; + }; + definition = mkOption { + description = "Consul service definition."; + type = types.attrs; + }; + }); + + attachToService = name: conf: let + serviceJson = pkgs.writeText "consul-service-${name}.json" (builtins.toJSON conf.definition); + in { + name = conf.unit; + value = { + serviceConfig = { + ExecStartPost = "${consul} services register ${serviceJson}"; + ExecStopPre = "${consul} services deregister ${serviceJson}"; + }; + }; + }; +in + +{ + options.consul = { + services = mkOption { + type = with types; attrsOf consulServiceDefinition; + default = {}; + }; + }; + + config = lib.mkIf (cfg.services != {}) { + systemd.services = mapAttrs' attachToService cfg.services; + warnings = optional (!config.services.consul.enable) "Consul service registrations found, but Consul agent is not enabled on this machine."; + }; +} diff --git a/modules/default.nix b/modules/default.nix index 3c13c56..eb6c90e 100644 --- a/modules/default.nix +++ b/modules/default.nix @@ -3,6 +3,7 @@ with builtins; let aspects = { autopatch = import ./autopatch; + consul-service-registry = import ./consul-service-registry; deploy-rs-receiver = import ./deploy-rs-receiver; enterprise = import ./enterprise; fail2ban = import ./fail2ban; @@ -41,6 +42,7 @@ in rec { ]; server = [ + consul-service-registry deploy-rs-receiver fail2ban motd