NixOS modules: Difference between revisions

imported>Malteneuss
m Add imports vs import note which trips ups beginners often
imported>Malteneuss
m Improve structure and reuse formulations
Line 1: Line 1:
'''Modules''' are files combined by NixOS to produce the full system configuration. A module contains a Nix expression. It ''declares'' options for other modules to ''define'' (give a value). It processes them and defines options declared in other modules.<ref>{{manual:nixos|sec=#sec-writing-modules|chapter=Chapter 42. Writing NixOS Modules}}</ref>
NixOS produces a full system configuration by combining smaller, more isolated and reusable components: '''Modules'''. A module is a file containing a Nix expression with a specific structure. It ''declares'' options for other modules to ''define'' (give a value). It processes them and defines options declared in other modules.<ref>{{manual:nixos|sec=#sec-writing-modules|chapter=Chapter 42. Writing NixOS Modules}}</ref>


For example, {{ic|/etc/nixos/configuration.nix}} is a module. Most other modules are in {{Nixpkgs Link|nixos/modules}}.
For example, {{ic|/etc/nixos/configuration.nix}} is a module. Most other modules are in {{Nixpkgs Link|nixos/modules}}.
Line 149: Line 149:
== Example ==
== Example ==


put into <code>hello.nix</code> in the same folder as your <code>configuration.nix</code>.
To see how modules are setup and reuse other modules in practice put <code>hello.nix</code> in the same folder as your <code>configuration.nix</code>:
 
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
{ lib, pkgs, config, ... }:
{ lib, pkgs, config, ... }:
with lib;                       
with lib;                       
let
let
  # Shorter name to access final settings a
  # user of hello.nix module HAS ACTUALLY SET.
  # cfg is a typical convention.
   cfg = config.services.hello;
   cfg = config.services.hello;
in {
in {
  # Declare what settings a user of this "hello.nix" module CAN SET.
   options.services.hello = {
   options.services.hello = {
     enable = mkEnableOption "hello service";
     enable = mkEnableOption "hello service";
Line 164: Line 169:
   };
   };


  # Define what other settings, services and resources should be active IF
  # a user of this "hello.nix" module ENABLED this module
  # by setting "services.hello.enable = true;".
   config = mkIf cfg.enable {
   config = mkIf cfg.enable {
     systemd.services.hello = {
     systemd.services.hello = {
Line 173: Line 181:
</syntaxhighlight>
</syntaxhighlight>


Add the following to your <code>configuration.nix</code>
The other <code>configuration.nix</code> module can then import this <code>hello.nix</code> module
and decide to enable it (and optionally set other allowed settings) as follows:
<syntaxhighlight lang=nix>
<syntaxhighlight lang=nix>
{
{