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

3.1 Write your first NixOS service module

Lesson 13 of 28 · 12:29

placeholder thumbnail

Sign in, then buy this course to watch

Free account · no credit card needed

Video chapters

  1. 0:00 Building a Simple NixOS Module
  2. 2:51 Understanding Options, Defaults, and mkIf
  3. 5:57 Testing the Module in a NixOS VM
  4. 9:33 Changing the Port and Opening the Firewall
Transcript

Building a Simple NixOS Module

0:00 So, after we just learned how to consume other NixOS modules, how to find other attribute paths on search.nixos.org and configure whatever we like, everything else is just studying what's there, reading the documentation and just using it, right? Now let's learn how to build our own NixOS module. I've prepared something already, like the simplest module that you will ever see. And the whole idea is that we basically start with a normal format where we have config packages lib in the function header and then an options block that declaratively sets options.

0:39 And the two options that we enable here is services.hello.enable and services.hello.port. So what this means is that we are kind of creating a service that is called hello. And when we are like, so what does this mean? What kind of service is being launched? We can immediately look into the config part and this is kind of what you would do if you were reading a foreign NixOS module too. And here we can see that if this is enabled, then we enable a new systemd service that's called hello.

1:18 So this is interesting. We are using the systemd modules that are defined elsewhere and create a new attribute there that's called hello. And that now contains systemd stuff. If you ever wrote systemd unit files yourself, then you will immediately recognize this wanted by and exec start and stuff like that nomenclature because that is how you configure systemd. So let's go through this one by one again. Our enable option is they are both prefixed with services.hello, right.

The full transcript comes with the lesson.

About this lesson

Turn a program into a service that anyone can enable with one line. This lesson walks through a minimal module that declares services.hello.enable and a port option, wires them to a systemd service, and deploys it on a running NixOS system.

In this video

  • Reading a module starting from its config part, the way you would read a foreign one
  • lib.mkIf, and how a block joins the configuration only when the service is enabled
  • Just enough systemd to understand wantedBy and ExecStart
  • Changing the port and watching the service follow
  • Opening the firewall with the port from the module, so there is only one source of truth

After this lesson

You can turn your own software into a configurable NixOS service, and change its settings without touching its internals.

Links: