NixOS 101 Course / Section 3: Your own NixOS service modules
Premium

3.4 NixOS module rules: keep your configurations composable

Lesson 16 of 28 · 20:20

placeholder thumbnail

Sign in, then buy this course to watch

Free account · no credit card needed

Video chapters

  1. 0:00 NixOS Module System Basics
  2. 2:06 Evaluated Config, Options, and Build Outputs
  3. 6:12 Separating Application and Platform Modules
  4. 10:12 Inspecting Definitions in REPL and nixos-option
  5. 13:18 Module Design Rules and Side-Effect-Free Imports
  6. 18:00 Avoiding Parameters and Preserving Composability
Transcript

NixOS Module System Basics

0:00 Okay, so after we built our own NixOS system as a VM and built our own module and stuff like that, let's revisit a few basics. So in general, the NixOS system is basically a list of modules that are somehow merged. Either they import each other or they are imported as a list, something like that. And then you need to throw them through a function that evaluates the NixOS module system. So the easiest case for that is running the function packages.nixos on your list of modules.

0:34 Or if you're in a flake context, you would say nixpkgs.lib.nixosSystem. And the result of that is an evaluated module system. And then from that evaluated module system, you can access all kinds of sub-attributes, like, for example, config and options, as we have seen in the REPL earlier. So now what's interesting is that you can build different kinds of system from that. In general, there's always the config.system.build.toplevel derivation available.

1:07 The top level derivation is basically the closure of your system, regardless if that is for a VM image or an ISO image or for an installation on disk. That top level derivation basically describes your kernel, your initial RAM disk, your modules and the rest of your system that needs to be there, including all the packages and services. So if your top level derivation doesn't build, then your configuration is broken anyway. And then depending on what you want to build for, you would build different output derivations.

The full transcript comes with the lesson.

About this lesson

This lesson recaps how a NixOS system is evaluated and built. Then, we define a set of rules for module authors. These come from training hundreds of people and seeing which shortcuts hurt later.

In this video

  • One evaluation, many outputs: the system closure, ISO images, VMs, and the cloud image profiles that ship with nixpkgs
  • Separating application specific from platform specific modules
  • nixos-option for tracing values from the command line
  • Modules versus profiles, and why importing a module alone should never change your system
  • A pattern that looks convenient, shows up in many projects, and makes modules impossible to override later

After this lesson

You can write modules that your colleagues can import, combine, and override without fighting your decisions.