Hello everyone,
I have recently descovered that Nix Expression Language seems to not have a way to define a global variables. The thing I’m willing to achieve is to have all variables in one place and to only reference their values in actual config this way:
variables.nix
userdata = (
domain = "mydomain.com";
username = "user";
hashedMasterPassword = "3hg1509509824h598g<4879gb2g95";
)
mailserver.nix
{ lib, pkgs, ... }:
{
services = {
postfix = {
user = ${userdata.user};
domain = ${userdata.domain};
};
};
}
As far as Nix Language does not provide any way to define global variables, I would like to know, is it possible to create a module and define its options to use them later in the config?
I’ve created the following module:
module.nix
{ config, lib, pkgs, ... }:
with lib;
let
cfg = config.services.userdata;
directionArg = if cfg.direction == ""
then ""
else "--direction=${cfg.direction}";
in
{
options.services.userdata = {
enable = mkOption {
default = true;
type = types.nullOr types.bool;
};
domain = mkOption {
description = ''
Domain used by the server
'';
type = types.nullOr types.str;
};
username = mkOption {
description = ''
Username that was defined at the initial setup process
'';
type = types.nullOr types.str;
};
hashedMasterPassword = {
description = ''
Hash of the password that was defined at the initial setup process
'';
type = types.nullOr types.str;
};
};
}
My idea was to use values from this module in later configuration:
mailserver.nix
{ lib, pkgs, ... }:
{
services = {
userdata = {
user = "user";
};
postfix = {
user = ${services.userdata.user};
};
};
}
But when I build this module, I encounter the following issue:
error: You're trying to declare a value of type `string'
rather than an attribute-set for the option
`services.userdata.hashedMasterPassword.description'!
This usually happens if `services.userdata.hashedMasterPassword.description' has option
definitions inside that are not matched. Please check how to properly define
this option by e.g. referring to `man 5 configuration.nix'!
(use '--show-trace' to show detailed location information)
Could someone please suggest, if it possible to implement global variables in the way I’ve chosen?
Thanks