4. The Module System
How a pile of small files becomes one coherent Linux system
By now you can read a configuration.nix and you have a working flake. But there's a
sleight of hand we've been quietly relying on. You wrote something like
services.openssh.enable = true; and a fully configured SSH daemon appeared — a systemd
unit, a generated sshd_config, a firewall hole, the right user and directories. You set
one boolean, and a small mountain of system state fell into place. Where did all that
come from, and how did your single line of config reach across the system and wire it up?
The answer is the NixOS module system: the machinery that collects hundreds of small
files, lets each one both declare new settings and set existing ones, and merges the
whole lot into one giant, consistent description of your machine. It's the layer that
turns "a bunch of .nix files" into "an operating system." Once you see how it works, a
NixOS config stops feeling like magic incantations and starts feeling like what it is: a
big, well-typed data structure that many hands can contribute to.
The whole idea in one paragraph
Picture one enormous form with thousands of labelled fields — hostname, every
service's settings, every user, kernel options, firewall rules. Each field is an
option. A module is a small file that can do two
things: declare new fields on the form, and fill in some of the
fields. Your system is assembled by gathering every module, letting each declare and
fill what it wants, and then merging all their contributions into one
final, fully-filled form. That merged form is config, and it's what
actually builds your system.
A module is a function
Concretely, a module is almost always a function that takes an attribute set and returns
an attribute set. You've already seen its arguments — they're the ones NixOS passes into
every configuration.nix:
The canonical module shape
{ config, pkgs, lib, ... }:
{
imports = [
./hardware-configuration.nix
./web-server.nix
];
options = {
# declare NEW settings that other modules (or this one) can set
};
config = {
# SET the values of settings — yours or ones nixpkgs already declared
};
}
The function's argument is where the module system hands you what you need:
config— the final, fully-merged configuration, after every module has had its say. This is the finished form. You can read any value out of it, which is how one module reacts to what another module set.pkgs— the package set (nixpkgs), so you can referencepkgs.gitand friends.lib— the nixpkgs standard library, home tomkOption,mkIf,mkDefault, thetypes.*collection, and much more....— the module system may pass extra arguments (likemodulesPath), and the...lets your function accept them without naming them. It's required in practice; leave it in.
The returned attribute set has three special keys — imports, options, config —
which we'll take one at a time. But first, the shorthand you've actually been using.
A bare attribute set of settings is a module
If the attribute set a module returns contains none of the reserved
keys (imports, options, config), the module
system treats the entire set as if it were wrapped in config.
That's why your first configuration.nix could just say
services.openssh.enable = true; at the top level with no
config = { ... } around it. It was a module all along — the module system
just filled in the config wrapper for you.
So these two files are exactly equivalent:
Shorthand (config implied)
{ pkgs, ... }:
{
networking.hostName = "bluewhale";
services.openssh.enable = true;
}
Explicit config
{ pkgs, ... }:
{
config = {
networking.hostName = "bluewhale";
services.openssh.enable = true;
};
}
The shorthand is fine until you need to declare your own options — the moment a module
uses options, it must use the explicit form and put its settings under config, because
now the module system can no longer guess which key you meant. We'll hit exactly that in
the worked example at the end.
Declaring options
An option is a named, typed slot in the configuration. Nixpkgs declares tens of
thousands of them (that's what all those services.*, networking.*, boot.* names
are), and you can declare your own. You declare one with lib.mkOption:
Declaring a single option
options.services.myapp.enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to run the myapp background service.";
};
The attribute set you hand mkOption has a few common fields:
type— the option's type. This is what lets the module system validate values and, crucially, decide how to merge multiple definitions of the same option. More on that in a moment.default— the value used if no module sets the option. (Not the same asmkDefault, which we'll meet under merging — that's about priority, this is about absence.)description— human-readable docs. This is what shows up in the searchable NixOS options reference, so it's worth writing well.- Optionally
exampleandapply(a function post-processing the final value).
Types live under lib.types. The ones you'll reach for constantly:
The everyday lib.types
types.bool # true / false
types.int # an integer
types.port # int constrained to 0–65535
types.str # a string
types.enum [ "low" "high" ] # one of a fixed list of values
types.path # a filesystem path
types.package # a derivation (e.g. pkgs.nginx)
types.listOf types.str # a list whose elements are strings
types.attrsOf types.int # an attrset whose values are ints
types.nullOr types.str # a string OR null (optional value)
types.submodule { options = { … }; } # a nested set of options
submodule is the powerful one: it lets an option's value be itself a little
options-and-config world, which is how something like services.nginx.virtualHosts.<name>
can have its own root, locations, and so on. attrsOf (submodule …) — "a named
collection of sub-configs" — is the backbone of most large service modules in nixpkgs.
One shortcut worth knowing: declaring a boolean enable option is so common that nixpkgs
provides lib.mkEnableOption. Writing enable = lib.mkEnableOption "the myapp service";
expands to a bool option that defaults to false with a sensible description.
Setting values, and the enable pattern
Declaring an option just creates the empty slot. Setting it is what config is for, and
it's the same syntax whether the option is one you declared or one of nixpkgs' tens of
thousands:
Setting options in config
config = {
services.openssh.enable = true;
services.openssh.settings.PasswordAuthentication = false;
networking.firewall.allowedTCPPorts = [ 22 80 443 ];
};
This is where the services.* pattern earns its keep. A well-written service module in
nixpkgs declares an enable option that defaults to false, plus a handful of settings —
and then its own config block says, in effect, "if I'm enabled, here is the systemd
unit, the generated config file, the user account, the firewall rule, and everything else
this service needs." That conditional wiring is done with lib.mkIf:
The shape of a service module (simplified nixpkgs style)
{ config, lib, pkgs, ... }:
let
cfg = config.services.myapp; # convention: bind cfg = the module's own tree
in {
options.services.myapp = {
enable = lib.mkEnableOption "the myapp service";
port = lib.mkOption {
type = lib.types.port;
default = 8080;
description = "TCP port myapp listens on.";
};
};
config = lib.mkIf cfg.enable {
systemd.services.myapp = {
wantedBy = [ "multi-user.target" ];
serviceConfig.ExecStart = "${pkgs.myapp}/bin/myapp --port ${toString cfg.port}";
};
networking.firewall.allowedTCPPorts = [ cfg.port ];
};
}
Now the whole trick is visible. This module declares services.myapp.enable and
services.myapp.port. When some other file sets services.myapp.enable = true;, the
mkIf cfg.enable block "turns on" and contributes a systemd unit and a firewall port —
all from that one boolean, exactly like services.openssh.enable did for you earlier.
Notice config reads from config (via cfg = config.services.myapp). A module both
contributes to and reads from the final merged result. That looks circular; the last
section explains why it isn't.
Merging: many modules, one value
Here is the feature that makes the whole system compose: the same option can be set by many modules, and the module system merges all of those definitions into one final value. How it merges depends on the option's type:
- Lists (
listOf …) merge by concatenation. If three modules each add ports tonetworking.firewall.allowedTCPPorts, the final value is all of them combined. This is why services can each independently "open their port" without stepping on each other. - Attribute sets (
attrsOf …, submodules, and the big nested config tree) merge recursively — setservices.nginx.enablein one file andservices.nginx.virtualHostsin another and both land in the sameservices.nginx. - Scalars (a
bool, anint, astr) can't be combined — a port is one number. So exactly one definition must win, and if two modules set the same scalar to different values, you get an evaluation error... unless you use priorities to break the tie.
That's where the mk* priority helpers come in. Every definition has a numeric priority,
and for a scalar, the definition with the lowest number wins. (Yes, lowest — think
"priority 1" beats "priority 100," like a to-do list.)
The priority ladder (lower number wins)
lib.mkOptionDefault x # priority 1500 — the option's built-in default
lib.mkDefault x # priority 1000 — "use this unless overridden"
plain x # priority 100 — an ordinary definition
lib.mkForce x # priority 50 — "I really mean it, override defaults"
lib.mkOverride n x # priority n — set any number you like
So a base module can offer a suggestion with mkDefault, an ordinary module can set a
plain value that beats the suggestion, and a top-level override can stomp everything with
mkForce. If two definitions end up with the same winning priority and different
values, the module system throws a clear conflict error rather than guessing.
Two more helpers round out the toolkit:
lib.mkIf cond { … }— conditionally include a whole block of definitions. Ifcondisfalse, everything inside is dropped from the merge (as if the module never wrote it). This is howmkIf cfg.enablemakes a service's entire footprint appear or vanish with one boolean.lib.mkMerge [ a b c ]— explicitly combine several definition sets into one, using the normal merge rules. Handy when you want to attach severalmkIfblocks to a single attribute, e.g.config = lib.mkMerge [ (mkIf cfg.enable { … }) (mkIf cfg.tls { … }) ];.
Priority vs. default — don't confuse them
An option's default (in its mkOption declaration) is what you
get when no module sets it at all. The mk* helpers
(mkDefault, mkForce, …) are about which of several actual
definitions wins. Under the hood the declared default is itself just
a definition at priority 1500 (mkOptionDefault), which is why any real
definition you write beats it.
Imports: composing modules into a config
A real configuration isn't one file — it's dozens, and imports is the glue. The
imports list names other modules to pull into the evaluation. Their options and
config are gathered right alongside yours and merged into the same final result. There
is no namespacing or ordering to worry about: importing a module just adds its
contributions to the pool.
Splitting a system across files
# configuration.nix
{ ... }:
{
imports = [
./hardware-configuration.nix # generated: disks, kernel modules
./modules/web-server.nix # your nginx + certs
./modules/users.nix # your accounts
./modules/desktop.nix # gnome, fonts, audio
];
networking.hostName = "bluewhale"; # a few top-level settings, too
}
Each imported file is a full module with the same { config, pkgs, lib, ... }: shape, free
to declare its own options and set values. Because everything merges into one config,
users.nix can open a firewall port that web-server.nix also contributes to, and the two
lists simply concatenate. You organize by topic, and the module system stitches the
topics back together.
This is also exactly where a flake's nixosModules plug in. In your flake.nix, a
NixOS system is built with nixpkgs.lib.nixosSystem { modules = [ … ]; }, and that
modules list is just a top-level imports: you list your own ./configuration.nix
alongside modules exported by other flakes (inputs.home-manager.nixosModules.default,
inputs.sops-nix.nixosModules.sops, and so on). A third-party flake ships a
nixosModules.<name> output, you drop it into that list, and its options become available
in your config as if they'd always been part of nixpkgs. That's the whole mechanism behind
"add this flake to get these options" — it's modules, all the way down. We built that list
in your first flake; now you know what each entry in it really is.
How it all evaluates: options declared, values merged, config as a fixpoint
Step back and watch the whole thing run. When you nixos-rebuild switch, the module system:
The evaluation, start to finish
- Collect every module — the ones in your flake's
moduleslist, everything theyimport, and all of nixpkgs' built-in modules — into one big pool. - Declare the options: gather every
optionsblock to learn the name, type, and default of every settable slot. - Gather the definitions: collect every
configcontribution to each option from every module (dropping the ones behind a falsemkIf). - Merge each option's definitions using its type's merge rule and the priority ladder, producing one final value per option.
- The finished, fully-merged result is
config— and that's what gets read to build systemd units, generate files, and assemble your system.
But look again at steps 3 and 5. Modules read from config (like cfg = config.services.myapp)
while they're also contributing to it. How can a module read the final answer before the
final answer exists? This is the same fixpoint idea from the
Nix language article, and Nix's laziness is what makes it work. config
is defined recursively — in terms of itself — and Nix only computes any particular value at
the moment something actually asks for it. So when your service module evaluates
mkIf cfg.enable, Nix pauses, goes and computes just config.services.myapp.enable by
merging its definitions, gets true, and continues. Nothing is computed "too early"; each
value is pulled on demand, and the knot ties itself.
Why the circularity is fine
config is a lazy fixpoint: a big attribute set defined in terms of itself,
where every leaf is only forced when read. A module referring to
config.x isn't asking for "the whole finished config" — it's asking for
one specific merged value, which Nix computes just-in-time. As long as no option's
value genuinely depends on itself in a loop, the whole system resolves
cleanly. (When it does loop, you get an "infinite recursion" error — a
debugging topic for a later article.)
A worked example, end to end
Let's declare our own option and consume it in the very same configuration, so you can see
declaration, setting, and reading all cooperate. We'll add a
custom.greeting.message option and use it to write a login banner (/etc/issue).
modules/greeting.nix — declare and consume
{ config, lib, ... }:
let
cfg = config.custom.greeting;
in {
# 1. DECLARE our own options
options.custom.greeting = {
enable = lib.mkEnableOption "a custom login banner";
message = lib.mkOption {
type = lib.types.str;
default = "Welcome to this NixOS machine.";
description = "Text shown on the login screen (/etc/issue).";
};
};
# 2. CONSUME them: only take effect when enabled
config = lib.mkIf cfg.enable {
# environment.etc."issue" is an ordinary nixpkgs option;
# we READ our own cfg.message to set it.
environment.etc."issue".text = "${cfg.message}\n";
};
}
Now wire it into the system and turn it on from configuration.nix:
configuration.nix — import and set
{ ... }:
{
imports = [ ./modules/greeting.nix ];
custom.greeting.enable = true;
custom.greeting.message = "bluewhale — authorized users only.";
}
Trace what happens on rebuild. The module system collects greeting.nix, learns that
custom.greeting.enable and custom.greeting.message exist (steps 1–2 above). It gathers
the definitions from configuration.nix: enable = true and a message. Because enable
is true, the mkIf block is kept, so environment.etc."issue".text gets a definition
that reads cfg.message — which merges to our banner string. Rebuild, and /etc/issue
shows the custom text. Flip enable to false and rebuild: the mkIf block drops out
entirely, the /etc/issue contribution vanishes, and the system returns to its default —
no leftover state to clean up, because you never mutated anything. You changed the
description and the machine was rebuilt to match.
To feel the merge rules directly, try adding a second import that also touches
custom.greeting.message with lib.mkForce "LOCKED DOWN". On rebuild you'll see the
forced value win over your plain one in configuration.nix — priority 50 beating priority
100 — exactly as the merge diagram predicted.
See the merge happen
Reading about priorities is one thing; watching a value change as you toggle modules
is another. This demo lets you switch a handful of small modules on and off — each
setting the same option — and wrap their definitions in mkDefault,
mkForce, or mkIf, then shows you which definition survives the
merge and why.
Surviving definitions
Key Takeaways
- A module is a function
{ config, pkgs, lib, ... }:returning an attrset with up to three special keys —imports,options,config. A bare set of settings with none of those keys is shorthand for justconfig. - Options are typed slots declared with
lib.mkOption { type; default; description; }. Thelib.types.*family (bool,int,str,enum,listOf,attrsOf,submodule,nullOr,package) both validates values and decides how they merge. - The
enable/services.*pattern is a module declaring anenableoption and gating its whole footprint behindlib.mkIf cfg.enable— one boolean summons a systemd unit, a config file, a firewall rule, and more. - Merging combines every module's definitions: lists concatenate, attrsets merge recursively, and scalars pick a single winner by priority —
mkOptionDefault(1500),mkDefault(1000), plain (100),mkForce(50); lowest number wins.mkIfconditionally drops a block;mkMergecombines several. - Imports compose modules, letting you split a config across files by topic. A flake's
nixosModulesoutputs plug straight into the top-level module list, which is how third-party flakes add options to your system. - Evaluation is a lazy fixpoint: collect modules → declare options → gather definitions → merge → the result is
config. Modules can readconfigwhile contributing to it because Nix computes each value on demand.
You can now read any NixOS module — including the ones deep inside nixpkgs — and see the declare/set/merge machinery for what it is. Every time you rebuild, that machinery produces a fresh, fully-merged system and registers it as a new generation. Next, we'll follow what happens after the merge: how generations and rollback let you move between whole systems, and undo a bad change by rebooting into the last one that worked.