nixos/modules/services/mariadb.nix

63 lines
2.3 KiB
Nix
Raw Permalink Normal View History

2023-10-04 10:13:56 +08:00
inputs:
{
options.nixos.services.mariadb = let inherit (inputs.lib) mkOption types; in
{
enable = mkOption { type = types.bool; default = false; };
instances = mkOption
{
type = types.attrsOf (types.submodule (submoduleInputs: { options =
{
database = mkOption { type = types.nonEmptyStr; default = submoduleInputs.config._module.args.name; };
user = mkOption { type = types.nonEmptyStr; default = submoduleInputs.config._module.args.name; };
passwordFile = mkOption { type = types.nullOr types.nonEmptyStr; default = null; };
};}));
default = {};
};
};
config =
let
inherit (inputs.config.nixos.services) mariadb;
inherit (inputs.lib) mkAfter mkIf;
2023-10-04 10:13:56 +08:00
inherit (inputs.localLib) attrsToList;
inherit (builtins) map listToAttrs concatStringsSep filter;
2023-10-04 10:13:56 +08:00
in mkIf mariadb.enable
{
services =
{
mysql =
{
enable = true;
2023-10-04 11:06:37 +08:00
package = inputs.pkgs.mariadb;
2023-10-04 10:13:56 +08:00
ensureDatabases = map (db: db.value.database) (attrsToList mariadb.instances);
ensureUsers = map
(db:
{
name = db.value.user;
ensurePermissions."${db.value.database}.*" = "ALL PRIVILEGES";
})
(attrsToList mariadb.instances);
2023-10-04 10:13:56 +08:00
};
mysqlBackup =
{
enable = true;
databases = map (db: db.value.database) (attrsToList mariadb.instances);
};
};
systemd.services.mysql.postStart = mkAfter (concatStringsSep "\n" (map
(db:
let
passwordFile =
if db.value.passwordFile or null != null then db.value.passwordFile
else inputs.config.sops.secrets."mariadb/${db.value.user}".path;
mysql = "${inputs.config.services.mysql.package}/bin/mysql";
in
# set user password
2023-10-04 11:54:21 +08:00
''echo "ALTER USER '${db.value.user}'@'localhost' IDENTIFIED VIA unix_socket OR mysql_native_password ''
+ ''USING PASSWORD('$(cat ${passwordFile})');" | ${mysql} -N'')
(attrsToList mariadb.instances)));
2023-10-04 10:13:56 +08:00
sops.secrets = listToAttrs (map
(db: { name = "mariadb/${db.value.user}"; value.owner = inputs.config.users.users.mysql.name; })
(filter (db: db.value.passwordFile == null) (attrsToList mariadb.instances)));
};
}