NixOS 17.03 Installation Guide
NixOS 17.03 Installation Guide
Version 17.03
Preface (index.html#idm140737316949424)
I. Installation (index.html#ch-installation)
Preface
This manual describes how to install, use and extend NixOS, a Linux distribution based on the purely functional package management system Nix.
Note: Commands prefixed with # have to be run as root, either requiring to login as root user or temporarily switching to it using sudo for
example.
Part I. Installation
This section describes how to obtain, install, and configure NixOS for first-time use.
As an alternative to installing NixOS yourself, you can get a running NixOS system through several other means:
Using virtual appliances in Open Virtualization Format (OVF) that can be imported into VirtualBox. These are available from the NixOS download
page (http://nixos.org/nixos/download.html).
Using AMIs for Amazons EC2. To find one for your region and instance type, please refer to the list of most recent AMIs (https://github.
com/NixOS/nixpkgs/blob/master/nixos/modules/virtualisation/ec2-amis.nix).
Using NixOps, the NixOS-based cloud deployment tool, which allows you to provision VirtualBox and EC2 NixOS instances from declarative spec
ifications. Check out the NixOps homepage (https://nixos.org/nixops) for details.
2. The CD contains a basic NixOS installation. (It also contains Memtest86+, useful if you want to test new hardware). When its finished booting, it
should have detected most of your hardware.
5. If you downloaded the graphical ISO image, you can run systemctl start display-manager to start KDE. If you want to continue on the terminal,
you can use loadkeys to switch to your preferred keyboard layout. (We even provide neo2 via loadkeys de neo!)
6. The boot process should have brought up networking (check ip a). Networking is necessary for the installer, since it will download lots of stu
(such as source tarballs or Nixpkgs channel binaries). Its best if you have a DHCP server on your network. Otherwise configure networking manu
ally using ifconfig.
To manually configure the network on the graphical installer, first disable network-manager with systemctl stop network-manager.
7. If you would like to continue the installation from a dierent machine you need to activate the SSH daemon via systemctl start sshd. In or
der to be able to login you also need to set a password for root using passwd.
8. The NixOS installer doesnt do any partitioning or formatting yet, so you need to do that yourself. Use the following commands:
For initialising Ext4 partitions: mkfs.ext4. It is recommended that you assign a unique symbolic label to the file system using the option
-L label, since this makes the file system configuration independent from device changes. For example:
For creating swap partitions: mkswap. Again its recommended to assign a label to the swap partition: -L label.
9. Mount the target file system on which NixOS should be installed on /mnt, e.g.
10. If your machine has a limited amount of memory, you may want to activate swap devices now (swapon device ). The installer (or rather, the build
actions that it may spawn) may need quite a bit of RAM, depending on your configuration.
11. You now need to create a file /mnt/etc/nixos/configuration.nix that specifies the intended configuration of the system. This is because
NixOS has a declarative configuration model: you create or edit a description of the desired configuration of your system, and then NixOS takes
care of making it happen. The syntax of the NixOS configuration file is described in Chapter 5, Configuration Syntax (index.html#sec-configura
tion-syntax), while a list of available configuration options appears in Appendix A, Configuration Options (options.html). A minimal example is
shown in Example 2.2, NixOS Configuration (index.html#ex-config).
The command nixos-generate-config can generate an initial configuration file for you:
# nano /mnt/etc/nixos/configuration.nix
If youre using the graphical ISO image, other editors may be available (such as vim). If you have network access, you can also install other editors
for instance, you can install Emacs by running nix-env -i emacs.
You must set the option boot.loader.grub.device to specify on which disk the GRUB boot loader is to be installed. Without it, NixOS cannot
boot.
Another critical option is fileSystems, specifying the file systems that need to be mounted by NixOS. However, you typically dont need to set it
yourself, because nixos-generate-config sets it automatically in /mnt/etc/nixos/hardware-configuration.nix from your currently
mounted file systems. (The configuration file hardware-configuration.nix is included from configuration.nix and will be overwritten by
future invocations of nixos-generate-config; thus, you generally should not modify it.)
Note: Depending on your hardware configuration or type of file system, you may need to set the option boot.initrd.kernelModules
to include the kernel modules that are necessary for mounting the root file system, otherwise the installed system will not be able to boot.
(If this happens, boot from the CD again, mount the target file system on /mnt, fix /mnt/etc/nixos/configuration.nix and rerun
nixos-install.) In most cases, nixos-generate-config will figure out the required modules.
# nixos-install
Cross fingers. If this fails due to a temporary problem (such as a network issue while downloading binaries from the NixOS binary cache), you can
just re-run nixos-install. Otherwise, fix your configuration.nix and then re-run nixos-install.
As the last step, nixos-install will ask you to set the password for the root user, e.g.
# reboot
14. You should now be able to boot into the installed NixOS. The GRUB boot menu shows a list of available configurations (initially just one). Every
time you change the NixOS configuration (see Changing Configuration (index.html#sec-changing-config) ), a new item is added to the menu. This
allows you to easily roll back to a previous configuration if something goes wrong.
You should log in and change the root password with passwd.
Youll probably want to create some user accounts as well, which can be done with useradd:
$ nix-env -qa \*
$ nix-env -i w3m
To summarise, Example 2.1, Commands for Installing NixOS on /dev/sda (index.html#ex-install-sequence) shows a typical sequence of com
mands for installing NixOS on an empty hard drive (here /dev/sda). Example 2.2, NixOS Configuration (index.html#ex-config) shows a correspond
ing configuration Nix expression.
{
imports =
[ # Include the results of the hardware scan.
./hardware-configuration.nix
];
boot.loader.grub.device = "/dev/sda";
You should boot the live CD in UEFI mode (consult your specific hardware's documentation for instructions). You may find the rEFInd boot manag
er (http://www.rodsbooks.com/refind) useful.
Instead of fdisk, you should use gdisk to partition your disks. You will need to have a separate partition for /boot with partition code EF00, and it
should be formatted as a vfat filesystem.
You must set boot.loader.systemd-boot.enable to true. nixos-generate-config should do this automatically for new configurations
when booted in UEFI mode.
After having mounted your installation partition to /mnt, you must mount the boot partition to /mnt/boot.
You may want to look at the options starting with boot.loader.efi and boot.loader.systemd-boot as well.
The dd utility will write the image verbatim to the drive, making it the recommended option for both UEFI and non-UEFI installations. For non-UEFI in
stallations, you can alternatively use unetbootin (http://unetbootin.sourceforge.net/). If you cannot use dd for a UEFI installation, you can also mount
the ISO, copy its contents verbatim to your drive, then either:
Change the label of the disk partition to the label of the ISO (visible with the blkid command), or
Edit loader/entries/nixos-livecd.conf on the drive and change the root= field in the options line to point to your drive (see the docu
mentation on root= in the kernel documentation (https://www.kernel.org/doc/Documentation/kernel-parameters.txt) for more details).
These instructions assume that you have an existing PXE or iPXE infrastructure and simply want to add the NixOS installer as another option. To build
the necessary files from a recent version of nixpkgs, you can run:
This will create a result directory containing: * bzImage the Linux kernel * initrd the initrd file * netboot.ipxe an example ipxe script
demonstrating the appropriate kernel command line arguments for this image
If youre using plain PXE, configure your boot loader to use the bzImage and initrd files and have it provide the same kernel command line argu
ments found in netboot.ipxe.
If youre using iPXE, depending on how your HTTP/FTP/etc. server is configured you may be able to use netboot.ipxe unmodified, or you may
need to update the paths to the files to match your servers directory layout
In the future we may begin making these files available as build products from hydra at which point we will update this documentation with instruc
tions on how to obtain them either for placing on a dedicated TFTP server or to boot them directly over the internet.
4. Mount the CD-ROM with the NixOS ISO (by clicking on CD/DVD-ROM)
7. Save the settings, start the virtual machine, and continue installation like normal
There are a few modifications you should make in configuration.nix. Enable the virtualbox guest service in the main block:
virtualisation.virtualbox.guest.enable = true;
Enable booting:
boot.loader.grub.device = "/dev/sda";
Also remove the fsck that runs at startup. It will always fail to run, stopping your boot until you press *.
boot.initrd.checkJournalingFS = false;
Shared folders can be given a name and a path in the host system in the VirtualBox settings (Machine / Settings / Shared Folders, then click on the
"Add" icon). Add the following to the /etc/nixos/configuration.nix to auto-mount them:
fileSystems."/virtualboxshare" = {
fsType = "vboxsf";
device = "nameofthesharedfolder";
options = [ "rw" ];
};
}
# nixos-rebuild switch
to build the new configuration, make it the default configuration for booting, and try to realise the configuration in the running system (e.g., by restart
ing system services).
Warning: These commands must be executed as root, so you should either run them from a root shell or by prefixing them with sudo -i.
# nixos-rebuild test
to build the configuration and switch the running system to it, but without making it the boot default. So if (say) the configuration locks up your ma
chine, you can just reboot to get back to a working configuration.
There is also
# nixos-rebuild boot
to build the configuration and make it the boot default, but not switch to it now (so it will only take eect after the next reboot).
You can make your configuration show up in a dierent submenu of the GRUB 2 boot screen by giving it a dierent profile name, e.g.
which causes the new configuration (and previous ones created using -p test) to show up in the GRUB submenu NixOS - Profile 'test'. This can
be useful to separate test configurations from stable configurations.
$ nixos-rebuild build
to build the configuration but nothing more. This is useful to see whether everything compiles cleanly.
If you have a machine that supports hardware virtualisation, you can also test the new configuration in a sandbox by building and running a QEMU vir
tual machine that contains the desired configuration. Just do
$ nixos-rebuild build-vm
$ ./result/bin/run-*-vm
The VM does not have any data from your host system, so your existing user accounts and home directories will not be available. You can forward
ports on the host to the guest. For instance, the following will forward host port 2222 to guest port 22 (SSH):
$ QEMU_NET_OPTS="hostfwd=tcp::2222-:22" ./result/bin/run-*-vm
allowing you to log in via SSH (assuming you have set the appropriate passwords or SSH authorized keys):
Stable channels, such as nixos-17.03 (https://nixos.org/channels/nixos-17.03). These only get conservative bug fixes and pack
age upgrades. For instance, a channel update may cause the Linux kernel on your system to be upgraded from 4.9.16 to 4.9.17 (a minor bug fix),
but not from 4.9.x to 4.11.x (a major change that has the potential to break things). Stable channels are generally maintained until the next stable
branch is created.
The unstable channel, nixos-unstable (https://nixos.org/channels/nixos-unstable). This corresponds to NixOSs main develop
ment branch, and may thus see radical changes between channel updates. Its not recommended for production systems.
To see what channels are available, go to https://nixos.org/channels (https://nixos.org/channels). (Note that the URIs of the various channels redirect
to a directory that contains the channels latest version and includes ISO images and VirtualBox appliances.)
When you first install NixOS, youre automatically subscribed to the NixOS channel that corresponds to your installation source. For instance, if you
installed from a 17.03 ISO, you will be subscribed to the nixos-17.03 channel. To see which NixOS channel youre subscribed to, run the following
as root:
(Be sure to include the nixos parameter at the end.) For instance, to use the NixOS 17.03 stable channel:
If you have a server, you may want to use the small channel instead:
You can then upgrade NixOS to the latest version in your chosen channel by running
which is equivalent to the more verbose nix-channel --update nixos; nixos-rebuild switch.
Note: Channels are set per user. This means that running nix-channel --add as a non root user (or without sudo) will not aect
configuration in /etc/nixos/configuration.nix
Warning: It is generally safe to switch back and forth between channels. The only exception is that a newer NixOS may also have a newer Nix
version, which may involve an upgrade of Nixs database schema. This cannot be undone easily, so in that case you will not be able to go
back to your original channel.
system.autoUpgrade.enable = true;
This enables a periodically executed systemd service named nixos-upgrade.service. It runs nixos-rebuild switch --upgrade to upgrade NixOS
to the latest version in the current channel. (To see when the service runs, see systemctl list-timers.) You can also specify a channel explicitly, e.g.
system.autoUpgrade.channel = https://nixos.org/channels/nixos-17.03;
This chapter describes how to configure various aspects of a NixOS machine through the configuration file /etc/nixos/configuration.nix. As
described in Chapter 3, Changing the Configuration (index.html#sec-changing-config), changes to this file only take eect after you run nixos-rebuild.
{ option definitions
}
The first line ({ config, pkgs, ... }:) denotes that this is actually a function that takes at least the two arguments config and pkgs. (These are
explained later.) The function returns a set of option definitions ({ ... }). These definitions have the form name = value, where name is the name
of an option and value is its value. For example,
{ services.httpd.enable = true;
services.httpd.adminAddr = "alice@example.org";
services.httpd.documentRoot = "/webroot";
}
defines a configuration with three option definitions that together enable the Apache HTTP Server with /webroot as the document root.
Sets can be nested, and in fact dots in option names are shorthand for defining a set containing another set. For instance, services.httpd.en
able defines a set named services that contains a set named httpd, which in turn contains an option definition named enable with value true.
This means that the example above can also be written as:
{ services = {
httpd = {
enable = true;
adminAddr = "alice@example.org";
documentRoot = "/webroot";
};
};
}
which may be more convenient if you have lots of option definitions that share the same prefix (such as services.httpd).
NixOS checks your option definitions for correctness. For instance, if you try to define an option that doesnt exist (that is, doesnt have a correspond
ing option declaration), nixos-rebuild will give an error like:
Likewise, values in option definitions must have a correct type. For instance, services.httpd.enable must be a Boolean (true or false). Trying
to give it a value of another type, such as a string, will cause an error:
Strings
Strings are enclosed in double quotes, e.g.
networking.hostName = "dexter";
Special characters can be escaped by prefixing them with a backslash (e.g. \").
The main dierence is that it strips from each line a number of spaces equal to the minimal indentation of the string as a whole (disregarding the in
dentation of empty lines), and that characters like " and \ are not special (making it more convenient for including things like shell code). See more
info about this in the Nix manual here (https://nixos.org/nix/manual/#ssec-values).
Booleans
These can be true or false, e.g.
networking.firewall.enable = true;
networking.firewall.allowPing = false;
Integers
For example,
boot.kernel.sysctl."net.ipv4.tcp_keepalive_time" = 60;
(Note that here the attribute name net.ipv4.tcp_keepalive_time is enclosed in quotes to prevent it from being interpreted as a set named net
containing a set named ipv4, and so on. This is because its not a NixOS option but the literal name of a Linux kernel setting.)
Sets
Sets were introduced above. They are name/value pairs enclosed in braces, as in the option definition
fileSystems."/boot" =
{ device = "/dev/sda1";
fsType = "ext4";
options = [ "rw" "data=ordered" "relatime" ];
};
Lists
The important thing to note about lists is that list elements are separated by whitespace, like this:
Packages
Usually, the packages you need are already part of the Nix Packages collection, which is a set that can be accessed through the function argument
pkgs. Typical uses:
environment.systemPackages =
[ pkgs.thunderbird
pkgs.emacs
];
postgresql.package = pkgs.postgresql90;
The latter option definition changes the default PostgreSQL package used by NixOSs PostgreSQL service to 9.0. For more information on pack
ages, including how to add new ones, see Section 6.1.2, Adding Custom Packages (index.html#sec-custom-packages).
5.2. Abstractions
If you find yourself repeating yourself over and over, its time to abstract. Take, for instance, this Apache HTTP Server configuration:
{
services.httpd.virtualHosts =
[ { hostName = "example.org";
documentRoot = "/webroot";
adminAddr = "alice@example.org";
enableUserDir = true;
}
{ hostName = "example.org";
documentRoot = "/webroot";
adminAddr = "alice@example.org";
enableUserDir = true;
enableSSL = true;
sslServerCert = "/root/ssl-example-org.crt";
sslServerKey = "/root/ssl-example-org.key";
}
];
}
It defines two virtual hosts with nearly identical configuration; the only dierence is that the second one has SSL enabled. To prevent this duplication,
we can use a let:
let
exampleOrgCommon =
{ hostName = "example.org";
documentRoot = "/webroot";
adminAddr = "alice@example.org";
enableUserDir = true;
};
in
{
services.httpd.virtualHosts =
[ exampleOrgCommon
(exampleOrgCommon // {
enableSSL = true;
sslServerCert = "/root/ssl-example-org.crt";
sslServerKey = "/root/ssl-example-org.key";
})
];
}
The let exampleOrgCommon = ... defines a variable named exampleOrgCommon. The // operator merges two attribute sets, so the configura
tion of the second virtual host is the set exampleOrgCommon extended with the SSL options.
You can write a let wherever an expression is allowed. Thus, you also could have written:
{
services.httpd.virtualHosts =
let exampleOrgCommon = ...; in
[ exampleOrgCommon
(exampleOrgCommon // { ... })
];
}
but not { let exampleOrgCommon = ...; in ...; } since attributes (as opposed to attribute values) are not expressions.
Functions provide another method of abstraction. For instance, suppose that we want to generate lots of dierent virtual hosts, all with identical con
figuration except for the host name. This can be done as follows:
{
services.httpd.virtualHosts =
let
makeVirtualHost = name:
{ hostName = name;
documentRoot = "/webroot";
adminAddr = "alice@example.org";
};
in
[ (makeVirtualHost "example.org")
(makeVirtualHost "example.com")
(makeVirtualHost "example.gov")
(makeVirtualHost "example.nl")
];
}
Here, makeVirtualHost is a function that takes a single argument name and returns the configuration for a virtual host. That function is then called
for several names to produce the list of virtual host configurations.
We can further improve on this by using the function map, which applies another function to every element in a list:
{
services.httpd.virtualHosts =
let
makeVirtualHost = ...;
in map makeVirtualHost
[ "example.org" "example.com" "example.gov" "example.nl" ];
}
(The function map is called a higher-order function because it takes another function as an argument.)
What if you need more than one argument, for instance, if we want to use a dierent documentRoot for each virtual host? Then we can make make
VirtualHost a function that takes a set as its argument, like this:
{
services.httpd.virtualHosts =
let
makeVirtualHost = { name, root }:
{ hostName = name;
documentRoot = root;
adminAddr = "alice@example.org";
};
in map makeVirtualHost
[ { name = "example.org"; root = "/sites/example.org"; }
{ name = "example.com"; root = "/sites/example.com"; }
{ name = "example.gov"; root = "/sites/example.gov"; }
{ name = "example.nl"; root = "/sites/example.nl"; }
];
}
But in this case (where every root is a subdirectory of /sites named after the virtual host), it would have been shorter to define makeVirtualHost
as
makeVirtualHost = name:
{ hostName = name;
documentRoot = "/sites/${name}";
adminAddr = "alice@example.org";
};
Here, the construct ${...} allows the result of an expression to be spliced into a string.
5.3. Modularity
The NixOS configuration mechanism is modular. If your configuration.nix becomes too big, you can split it into multiple files. Likewise, if you
have multiple NixOS configurations (e.g. for dierent computers) with some commonality, you can move the common configuration into a shared file.
Modules have exactly the same syntax as configuration.nix. In fact, configuration.nix is itself a module. You can use other modules by in
cluding them from configuration.nix, e.g.:
Here, we include two modules from the same directory, vpn.nix and kde.nix. The latter might look like this:
{ services.xserver.enable = true;
services.xserver.displayManager.sddm.enable = true;
services.xserver.desktopManager.plasma5.enable = true;
}
Note that both configuration.nix and kde.nix define the option environment.systemPackages. When multiple modules define an option,
NixOS will try to merge the definitions. In the case of environment.systemPackages, thats easy: the lists of packages can simply be concatenat
ed. The value in configuration.nix is merged last, so for list-type options, it will appear at the end of the merged list. If you want it to appear first,
you can use mkBefore:
This causes the kvm-intel kernel module to be loaded before any other kernel modules.
For other types of options, a merge may not be possible. For instance, if two modules define services.httpd.adminAddr, nixos-rebuild will give
an error:
The unique option `services.httpd.adminAddr' is defined multiple times, in `/etc/nixos/httpd.nix' and `/etc/nixos/con
figuration.nix'.
When that happens, its possible to force one definition take precedence over the others:
When using multiple modules, you may need to access configuration values defined in other modules. This is what the config function argument is
for: it contains the complete, merged system configuration. That is, config is the result of combining the configurations returned by every module[1].
For example, here is a module that adds some packages to environment.systemPackages only if services.xserver.enable is set to true
somewhere else:
{ environment.systemPackages =
if config.services.xserver.enable then
[ pkgs.firefox
pkgs.thunderbird
]
else
[ ];
}
With multiple modules, it may not be obvious what the final value of a configuration option is. The command nixos-option allows you to find out:
$ nixos-option services.xserver.enable
true
$ nixos-option boot.kernelModules
[ "tun" "ipv6" "loop" ... ]
Interactive exploration of the configuration is possible using nix-repl (https://github.com/edolstra/nix-repl), a read-eval-print loop for Nix expres
sions. Its not installed by default; run nix-env -i nix-repl to get it. A typical use:
$ nix-repl '<nixpkgs/nixos>'
nix-repl> config.networking.hostName
"mandark"
Example Description
Basic values
"Hello world" A string
A string containing an expression (expands to
"${pkgs.bash}/bin/sh"
"/nix/store/hash-bash-version/bin/sh")
true, false Booleans
123 An integer
./foo.png A path (relative to the containing Nix expression)
Compound values
{ x = 1; y = 2; } An set with attributes names x and y
{ foo.bar = 1; } A nested set, equivalent to { foo = { bar = 1; }; }
rec { x = "foo"; y = x + "bar"; } A recursive set, equivalent to { x = "foo"; y = "foobar"; }
[ "foo" "bar" ] A list with two elements
Operators
"foo" + "bar" String concatenation
1 + 2 Integer addition
"foo" == "f" + "oo" Equality test (evaluates to true)
"foo" != "bar" Inequality test (evaluates to true)
!true Boolean negation
{ x = 1; y = 2; }.x Attribute selection (evaluates to 1)
{ x = 1; y = 2; }.z or 3 Attribute selection with default (evaluates to 3)
{ x = 1; y = 2; } // { z = 3; } Merge two sets (attributes in the right-hand set taking precedence)
Control structures
if 1 + 1 == 2 then "yes!" else "no!" Conditional expression
assert 1 + 1 == 2; "yes!" Assertion check (evaluates to "yes!")
let x = "foo"; y = "bar"; in x + y Variable definition
with pkgs.lib; head [ 1 2 3 ] Add all attributes from the given set to the scope (evaluates to 1)
Functions (lambdas)
x: x + 1 A function that expects an integer and returns it increased by 1
(x: x + 1) 100 A function call (evaluates to 101)
let inc = x: x + 1; in inc (inc (inc 100)) A function bound to a variable and subsequently called by name (evaluates to 103)
{ x, y }: x + y A function that expects a set with required attributes x and y and concatenates them
A function that expects a set with required attribute x and optional y, using "bar" as default
{ x, y ? "bar" }: x + y
value for y
{ x, y, ... }: x + y A function that expects a set with required attributes x and y and ignores any other attributes
A function that expects a set with required attributes x and y, and binds the whole set to
{ x, y } @ args: x + y
args
Built-in functions
import ./foo.nix Load and return Nix expression in given file
map (x: x + x) [ 1 2 3 ] Apply a function to every element of a list (evaluates to [ 2 4 6 ])
[1] If
youre wondering how its possible that the (indirect) result of a function is passed as an input to that same function: thats because Nix is a lazy
language it only computes values when they are needed. This works as long as no individual configuration value depends on itself.
Declarative, where you declare what packages you want in your configuration.nix. Every time you run nixos-rebuild, NixOS will ensure that
you get a consistent set of binaries corresponding to your specification.
Ad hoc, where you install, upgrade and uninstall packages via the nix-env command. This style allows mixing packages from dierent Nixpkgs
versions. Its the only choice for non-root users.
environment.systemPackages = [ pkgs.thunderbird ];
The eect of this specification is that the Thunderbird package from Nixpkgs will be built or downloaded as part of the system when you run nixos-
rebuild switch.
The first column in the output is the attribute name, such as nixos.thunderbird. (The nixos prefix allows distinguishing between dierent chan
nels that you might have.)
To uninstall a package, simply remove it from environment.systemPackages and run nixos-rebuild switch.
Warning: Unfortunately, Nixpkgs currently lacks a way to query available configuration options.
Apart from high-level options, its possible to tweak a package in almost arbitrary ways, such as changing or disabling dependencies of a package.
For instance, the Emacs package in Nixpkgs by default has a dependency on GTK+ 2. If you want to build it against GTK+ 3, you can specify that as
follows:
environment.systemPackages = [ (pkgs.emacs.override { gtk = pkgs.gtk3; }) ];
The function override performs the call to the Nix function that produces Emacs, with the original arguments amended by the set of arguments
specified by you. So here the function argument gtk gets the value pkgs.gtk3, causing Emacs to depend on GTK+ 3. (The parentheses are neces
sary because in Nix, function application binds more weakly than list construction, so without them, environment.systemPackages would be a list
with two elements.)
Even greater customisation is possible using the function overrideAttrs. While the override mechanism above overrides the arguments of a
package function, overrideAttrs allows changing the attributes passed to mkDerivation. This permits changing any aspect of the package,
such as the source code. For instance, if you want to override the source code of Emacs, you can say:
environment.systemPackages = [
(pkgs.emacs.overrideAttrs (oldAttrs: {
name = "emacs-25.0-pre";
src = /path/to/my/emacs/tree;
}))
];
Here, overrideAttrs takes the Nix derivation specified by pkgs.emacs and produces a new derivation in which the originals name and src at
tribute have been replaced by the given values by re-calling stdenv.mkDerivation. The original attributes are accessible via the function argument,
which is conventionally named oldAttrs.
The overrides shown above are not global. They do not aect the original package; other packages in Nixpkgs continue to depend on the original
rather than the customised package. This means that if another package in your system depends on the original package, you end up with two in
stances of the package. If you want to have everything depend on your customised instance, you can apply a global override as follows:
nixpkgs.config.packageOverrides = pkgs:
{ emacs = pkgs.emacs.override { gtk = pkgs.gtk3; };
};
The eect of this definition is essentially equivalent to modifying the emacs attribute in the Nixpkgs source tree. Any package in Nixpkgs that depends
on emacs will be passed your customised instance. (However, the value pkgs.emacs in nixpkgs.config.packageOverrides refers to the origi
nal rather than overridden instance, to prevent an infinite recursion.)
Then you write and test the package as described in the Nixpkgs manual. Finally, you add it to environment.systemPackages, e.g.
environment.systemPackages = [ pkgs.my-package ];
The second possibility is to add the package outside of the Nixpkgs tree. For instance, here is how you specify a build of the GNU Hello
(http://www.gnu.org/software/hello/) package directly in configuration.nix:
environment.systemPackages =
let
my-hello = with pkgs; stdenv.mkDerivation rec {
name = "hello-2.8";
src = fetchurl {
url = "mirror://gnu/hello/${name}.tar.gz";
sha256 = "0wqd8sjmxfskrflaxywc7gqw7sfawrfvdxd9skxawzfgyy0pzdz6";
};
};
in
[ my-hello ];
Of course, you can also move the definition of my-hello into a separate Nix expression, e.g.
stdenv.mkDerivation rec {
name = "hello-2.8";
src = fetchurl {
url = "mirror://gnu/hello/${name}.tar.gz";
sha256 = "0wqd8sjmxfskrflaxywc7gqw7sfawrfvdxd9skxawzfgyy0pzdz6";
};
}
$ nix-build my-hello.nix
$ ./result/bin/hello
Hello, world!
If you invoke this as root, the package is installed in the Nix profile /nix/var/nix/profiles/default and visible to all users of the system; other
wise, the package ends up in /nix/var/nix/profiles/per-user/username/profile and is not visible to other users. The -A flag specifies
the package by its attribute name; without it, the package is installed by matching against its package name (e.g. thunderbird). The latter is slower
because it requires matching against all available Nix packages, and is ambiguous if there are multiple matching packages.
Packages come from the NixOS channel. You typically upgrade a package by updating to the latest version of the NixOS channel:
and then running nix-env -i again. Other packages in the profile are not aected; this is the crucial dierence with the declarative style of package
management, where running nixos-rebuild switch causes all packages to be updated to their current versions in the NixOS channel. You can howev
er upgrade all packages for which there is a newer version by doing:
$ nix-env -u '*'
$ nix-env --rollback
nix-env has many more flags. For details, see the nix-env(1) manpage or the Nix manual.
users.extraUsers.alice =
{ isNormalUser = true;
home = "/home/alice";
description = "Alice Foobar";
extraGroups = [ "wheel" "networkmanager" ];
openssh.authorizedKeys.keys = [ "ssh-dss AAAAB3Nza... alice@foobar" ];
};
Note that alice is a member of the wheel and networkmanager groups, which allows her to use sudo to execute commands as root and to con
figure the network, respectively. Also note the SSH public key that allows remote logins with the corresponding private key. Users created in this way
do not have a password by default, so they cannot log in via mechanisms that require a password. However, you can use the passwd program to set
a password, which is retained across invocations of nixos-rebuild.
If you set users.mutableUsers to false, then the contents of /etc/passwd and /etc/group will be congruent to your NixOS configuration. For instance, if
you remove a user from users.extraUsers and run nixos-rebuild, the user account will cease to exist. Also, imperative commands for managing users
and groups, such as useradd, are no longer available. Passwords may still be assigned by setting the user's hashedPassword option. A hashed
password can be generated using mkpasswd -m sha-512 after installing the mkpasswd package.
A user ID (uid) is assigned automatically. You can also specify a uid manually by adding
uid = 1000;
Groups can be specified similarly. The following states that a group named students shall exist:
users.extraGroups.students.gid = 1000;
As with users, the group ID (gid) is optional and will be assigned automatically if its missing.
In the imperative style, users and groups are managed by commands such as useradd, groupmod and so on. For instance, to create a user account
named alice:
# useradd -m alice
To make all nix tools available to this new user use `su - USER` which opens a login shell (==shell that loads the profile) for given user. This will create
the ~/.nix-defexpr symlink. So run:
# su - alice -c "true"
The flag -m causes the creation of a home directory for the new user, which is generally what you want. The user does not have an initial password
and therefore cannot log in. A password can be set using the passwd utility:
# passwd alice
Enter new UNIX password: ***
Retype new UNIX password: ***
A user can be deleted using userdel:
# userdel -r alice
The flag -r deletes the users home directory. Accounts can be modified using usermod. Unix groups can be managed using groupadd, groupmod
and groupdel.
fileSystems."/data" =
{ device = "/dev/disk/by-label/data";
fsType = "ext4";
};
Mount points are created automatically if they dont already exist. For device, its best to use the topology-independent device aliases in
/dev/disk/by-label and /dev/disk/by-uuid, as these dont change if the topology changes (e.g. if a disk is moved to another IDE controller).
You can usually omit the file system type (fsType), since mount can usually detect the type and load the necessary kernel module automatically.
However, if the file system is needed at early boot (in the initial ramdisk) and is not ext2, ext3 or ext4, then its best to specify fsType to ensure
that the kernel module is available.
WARNING!
========
This will overwrite data on /dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d irrevocably.
# mkfs.ext4 /dev/mapper/crypted
To ensure that this file system is automatically mounted at boot time as /, add the following to configuration.nix:
boot.initrd.luks.devices.crypted.device = "/dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d";
fileSystems."/".device = "/dev/mapper/crypted";
Should grub be used as bootloader, and /boot is located on an encrypted partition, it is necessary to add the following grub option:
boot.loader.grub.enableCryptodisk = true;
The X server will automatically detect and use the appropriate video driver from a set of X.org drivers (such as vesa and intel). You can also specify
a driver manually, e.g.
services.xserver.videoDrivers = [ "r128" ];
You also need to enable at least one desktop or window manager. Otherwise, you can only log into a plain undecorated xterm window. Thus you
should pick one or more of the following lines:
services.xserver.desktopManager.plasma5.enable = true;
services.xserver.desktopManager.xfce.enable = true;
services.xserver.desktopManager.gnome3.enable = true;
services.xserver.windowManager.xmonad.enable = true;
services.xserver.windowManager.twm.enable = true;
services.xserver.windowManager.icewm.enable = true;
services.xserver.windowManager.i3.enable = true;
NixOSs default display manager (the program that provides a graphical login prompt and manages the X server) is SLiM. You can select an alternative
one by picking one of the following lines:
services.xserver.displayManager.sddm.enable = true;
services.xserver.displayManager.lightdm.enable = true;
The X server is started automatically at boot time. If you dont want this to happen, you can set:
services.xserver.autorun = false;
services.xserver.videoDrivers = [ "nvidia" ];
Or if you have an older card, you may have to use one of the legacy drivers:
services.xserver.videoDrivers = [ "nvidiaLegacy340" ];
services.xserver.videoDrivers = [ "nvidiaLegacy304" ];
services.xserver.videoDrivers = [ "nvidiaLegacy173" ];
You may need to reboot after enabling this driver to prevent a clash with other kernel modules.
On 64-bit systems, if you want full acceleration for 32-bit programs such as Wine, you should also set the following:
hardware.opengl.driSupport32Bit = true;
You will need to reboot after enabling this driver to prevent a clash with other kernel modules.
On 64-bit systems, if you want full acceleration for 32-bit programs such as Wine, you should also set the following:
hardware.opengl.driSupport32Bit = true;
Touchpads
Support for Synaptics touchpads (found in many laptops such as the Dell Latitude series) can be enabled as follows:
services.xserver.synaptics.enable = true;
The driver has many options (see Appendix A, Configuration Options (options.html)). For instance, the following enables two-finger scrolling:
services.xserver.synaptics.twoFingerScroll = true;
GTK/Qt themes
GTK themes can be installed either to user profile or system-wide (via system.environmentPackages). To make Qt 5 applications look similar to
GTK2 ones, you can install qt5.qtbase.gtk package into your system environment. It should work for all Qt 5 library versions.
services.xserver.desktopManager = {
xfce.enable = true;
default = "xfce";
};
Optionally, compton can be enabled for nice graphical eects, some example settings:
services.compton = {
enable = true;
fade = true;
inactiveOpacity = "0.9";
shadow = true;
fadeDelta = 4;
};
Some Xfce programs are not installed automatically. To install them manually (system wide), put them into your environment.systemPackages.
NixOSs default display manager is SLiM. (DM is the program that provides a graphical login prompt and manages the X server.) You can, for example,
select KDEs sddm instead:
services.xserver.displayManager.sddm.enable = true;
Troubleshooting
Even after enabling udisks2, volume management might not work. Thunar and/or the desktop takes time to show up. Thunar will spit out this kind of
message on start (look at journalctl --user -b).
Thunar:2410): GVFS-RemoteVolumeMonitor-WARNING **: remote volume monitor with dbus name org.gtk.Private.UDisks2Volume
Monitor is not supported
This is caused by some needed GNOME services not running. This is all fixed by enabling "Launch GNOME services on startup" in the Advanced tab
of the Session and Startup settings panel. Alternatively, you can run this command to do the same thing.
11.1. NetworkManager
To facilitate network configuration, some desktop environments use NetworkManager. You can enable NetworkManager by setting:
networking.networkmanager.enable = true;
some desktop managers (e.g., GNOME) enable NetworkManager automatically for you.
All users that should have permission to change network settings must belong to the networkmanager group:
users.extraUsers.youruser.extraGroups = [ "networkmanager" ];
NetworkManager is controlled using either nmcli or nmtui (curses-based terminal user interface). See their manual pages for details on their usage.
Some desktop environments (GNOME, KDE) have their own configuration tools for NetworkManager. On XFCE, there is no configuration tool for Net
workManager by default: by adding networkmanagerapplet to the list of system packages, the graphical applet will be installed and will launch au
tomatically when XFCE is starting (and will show in the status tray).
Note: networking.networkmanager and networking.wireless (WPA Supplicant) cannot be enabled at the same time: you can still
connect to the wireless networks using NetworkManager.
By default, root logins using a password are disallowed. They can be disabled entirely by setting services.openssh.permitRootLogin to "no".
You can declaratively specify authorised RSA/DSA public keys for a user as follows:
users.extraUsers.alice.openssh.authorizedKeys.keys =
[ "ssh-dss AAAAB3NzaC1kc3MAAACBAPIkGWVEt4..." ];
Typically youll also want to set a default gateway and set of name servers:
networking.defaultGateway = "192.168.1.1";
networking.nameservers = [ "8.8.8.8" ];
Note: Statically configured interfaces are set up by the systemd service interface-name-cfg.service. The default gateway and name
server configuration is performed by network-setup.service.
networking.hostName = "cartman";
The default host name is nixos. Set it to the empty string ("") to allow the DHCP server to provide the host name.
networking.enableIPv6 = false;
You can disable IPv6 on a single interface using a normal sysctl (in this example, we use interface eth0):
boot.kernel.sysctl."net.ipv6.conf.eth0.disable_ipv6" = true;
As with IPv4 networking interfaces are automatically configured via DHCPv6. You can configure an interface manually:
networking.defaultGateway6 = {
address = "fe00::1";
interface = "enp0s3";
}
See Section 11.3, IPv4 Configuration (index.html#sec-ipv4) for similar examples and additional information.
11.5. Firewall
NixOS has a simple stateful firewall that blocks incoming connections and other unexpected packets. The firewall applies to both IPv4 and IPv6 trac.
It is enabled by default. It can be disabled as follows:
networking.firewall.enable = false;
If the firewall is enabled, you can open specific TCP ports to the outside world:
networking.firewall.allowedTCPPorts = [ 80 443 ];
Note that TCP port 22 (ssh) is opened automatically if the SSH daemon is enabled (services.openssh.enable = true). UDP ports can be
opened through networking.firewall.allowedUDPPorts. Also of interest is
networking.firewall.allowPing = true;
to allow the machine to respond to ping requests. (ICMPv6 pings are always allowed.)
NixOS will start wpa_supplicant for you if you enable this setting:
networking.wireless.enable = true;
networking.wireless.networks = {
echelon = {
psk = "abcdefgh";
};
"free.wifi" = {};
}
Be aware that keys will be written to the nix store in plaintext! When no networks are set, it will default to using a configuration file at /etc/wpa_sup
plicant.conf. You should edit this file yourself to define wireless networks, WPA keys and so on (see wpa_supplicant.conf(5)).
If you are using WPA2 the wpa_passphrase tool might be useful to generate the wpa_supplicant.conf.
After you have edited the wpa_supplicant.conf, you need to restart the wpa_supplicant service.
networking.localCommands =
''
ip -6 addr add 2001:610:685:1::1/64 dev eth0
'';
Chapter 12. Linux Kernel
You can override the Linux kernel and associated packages using the option boot.kernelPackages. For instance, this selects the Linux 3.10
kernel:
boot.kernelPackages = pkgs.linuxPackages_3_10;
Note that this not only replaces the kernel, but also packages that are specific to the kernel version, such as the NVIDIA video drivers. This ensures
that driver packages are consistent with the kernel.
The default Linux kernel configuration should be fine for most users. You can see the configuration of your current kernel with the following command:
zcat /proc/config.gz
If you want to change the kernel configuration, you can use the packageOverrides feature (see Section 6.1.1, Customising Packages (in
dex.html#sec-customising-packages)). For instance, to enable support for the kernel debugger KGDB:
nixpkgs.config.packageOverrides = pkgs:
{ linux_3_4 = pkgs.linux_3_4.override {
extraConfig =
''
KGDB y
'';
};
};
extraConfig takes a list of Linux kernel configuration options, one per line. The name of the option should not include the prefix CONFIG_. The op
tion value is typically y, n or m (to build something as a kernel module).
Kernel modules for hardware devices are generally loaded automatically by udev. You can force a module to be loaded via boot.kernelModules,
e.g.
If the module is required early during the boot (e.g. to mount the root file system), you can use boot.initrd.extraKernelModules:
boot.initrd.extraKernelModules = [ "cifs" ];
This causes the specified modules and their dependencies to be added to the initial ramdisk.
boot.kernel.sysctl."net.ipv4.tcp_keepalive_time" = 120;
sets the kernels TCP keepalive time to 120 seconds. To see the available parameters, run sysctl -a.
services.dnscrypt-proxy.enable = true;
Enabling the client proxy does not alter the system nameserver; to relay local queries, prepend 127.0.0.1 to networking.nameservers.
services.dnscrypt-proxy.localPort = 43;
13.2.1. dnsmasq
{
services.dnsmasq.enable = true;
services.dnsmasq.servers = [ "127.0.0.1#43" ];
}
13.2.2. unbound
{
services.unbound.enable = true;
services.unbound.forwardAddresses = [ "127.0.0.1@43" ];
}
14.1. Configuration
Taskserver does all of its authentication via TLS using client certificates, so you either need to roll your own CA or purchase a certificate from a known
CA, which allows creation of client certificates. These certificates are usually advertised as server certificates.
So in order to make it easier to handle your own CA, there is a helper tool called nixos-taskserver which manages the custom CA along with
Taskserver organisations, users and groups.
While the client certificates in Taskserver only authenticate whether a user is allowed to connect, every user has its own UUID which identifies it as an
entity.
With nixos-taskserver the client certificate is created along with the UUID of the user, so it handles all of the credentials needed in order to setup the
Taskwarrior client to work with a Taskserver.
The tool is designed to not interfere if the command is used to manually set up some organisations, users or groups.
For example if you add a new organisation using nixos-taskserver org add foo, the organisation is not modified and deleted no matter what you de
fine in services.taskserver.organisations, even if you're adding the same organisation in that option.
The tool is modelled to imitate the ocial taskd command, documentation for each subcommand can be shown by using the --help switch.
This is done using nixos-taskserver user export $orgname $username which is printing a shell script fragment to stdout which can either be used
verbatim or adjusted to import the user on the client machine.
{
services.taskserver.enable = true;
services.taskserver.fqdn = "server";
services.taskserver.listenHost = "::";
services.taskserver.organisations.my-company.users = [ "alice" ];
}
Now in order to import the alice user to another machine alicebox, all we need to do is something like this:
Of course, if no SSH daemon is available on the server you can also copy & paste it directly into a shell.
After this step the user should be set up and you can start synchronising your tasks for the first time with task sync init on alicebox.
Subsequent synchronisation requests merely require the command task sync after that stage.
15.1. Prerequisites
The gitlab service exposes only an Unix socket at /run/gitlab/gitlab-workhorse.socket. You need to configure a webserver to proxy HTTP
requests to the socket.
For instance, the following configuration could be used to use nginx as frontend proxy:
services.nginx = {
enable = true;
recommendedGzipSettings = true;
recommendedOptimisation = true;
recommendedProxySettings = true;
recommendedTlsSettings = true;
virtualHosts."git.example.com" = {
enableACME = true;
forceSSL = true;
locations."/".proxyPass = "http://unix:/run/gitlab/gitlab-workhorse.socket";
};
};
'';
15.2. Configuring
Gitlab depends on both PostgreSQL and Redis and will automatically enable both services. In the case of PostgreSQL, a database and a role will be
created.
The default state dir is /var/gitlab/state. This is where all data like the repositories and uploads will be stored.
A basic configuration with some custom settings could look like this:
services.gitlab = {
enable = true;
databasePassword = "eXaMpl3";
initialRootPassword = "UseNixOS!";
https = true;
host = "git.example.com";
port = 443;
user = "git";
group = "git";
smtp = {
enable = true;
address = "localhost";
port = 25;
};
secrets = {
db = "uPgq1gtwwHiatiuE0YHqbGa5lEIXH7fMsvuTNgdzJi8P0Dg12gibTzBQbq5LT7PNzcc3BP9P1snHVnduqtGF43PgrQtU7XL93ts6gqe9CBN
hjtaqUwutQUDkygP5NrV6";
secret = "devzJ0Tz0POiDBlrpWmcsjjrLaltyiAdS8TtgT9YNBOoUcDsfppiY3IXZjMVtKgXrFImIennFGOpPN8IkP8ATXpRgDD5rxVnKuTTwYQ
aci2NtaV1XxOQGjdIE50VGsR3";
otp = "e1GATJVuS2sUh7jxiPzZPre4qtzGGaS22FR50Xs1TerRVdgI3CBVUi5XYtQ38W4xFeS4mDqi5cQjExE838iViSzCdcG19XSL6qNsfokQP9
JugwiftmhmCadtsnHErBMI";
};
extraConfig = {
gitlab = {
email_from = "gitlab-no-reply@example.com";
email_display_name = "Example GitLab";
email_reply_to = "gitlab-no-reply@example.com";
default_projects_features = { builds = false; };
};
};
};
If you're setting up a new Gitlab instance, generate new secrets. You for instance use tr -dc A-Za-z0-9 < /dev/urandom | head -c 128 to
generate a new secret. Gitlab encrypts sensitive data stored in the database. If you're restoring an existing Gitlab instance, you must specify the se
crets secret from config/secrets.yml located in your Gitlab state folder.
Refer to Appendix A, Configuration Options (options.html) for all available configuration options for the services.gitlab module.
15.3. Maintenance
You can run Gitlab's rake tasks with gitlab-rake which will be available on the system when gitlab is enabled. You will have to run the command as
the user that you configured to run gitlab with.
Emacs runs within a graphical desktop environment using the X Window System, but works equally well on a text terminal. Under OS X, a "Mac port"
edition is available, which uses Apple's native GUI frameworks.
Nixpkgs provides a superior environment for running Emacs. It's simple to create custom builds by overriding the default packages. Chaotic collec
tions of Emacs Lisp code and extensions can be brought under control using declarative package management. NixOS even provides a systemd user
service for automatically starting the Emacs daemon.
emacs
emacs, emacs25
The latest stable version of Emacs 25 using the GTK+ 2 (http://www.gtk.org) widget toolkit.
emacs25-nox
Emacs 25 built without any dependency on X11 libraries.
emacs24Macport
Emacs 24 with the "Mac port" patches, providing a more native look and feel under OS X.
If those aren't suitable, then the following imitation Emacs editors are also available in Nixpkgs: Zile (https://www.gnu.org/software/zile/), mg
(http://homepage.boetes.org/software/mg/), Yi (http://yi-editor.github.io/).
Most extensions are gotten with the Emacs packaging system (package.el) from Emacs Lisp Package Archive (ELPA) (https://elpa.gnu.org/), MELPA
(https://melpa.org/), MELPA Stable (https://stable.melpa.org/), and Org ELPA (http://orgmode.org/elpa.html). Nixpkgs is regularly updated to mirror all
these archives.
Under NixOS, you can continue to use package-list-packages and package-install to install packages. You can also declare the set of
Emacs packages you need using the derivations from Nixpkgs. The rest of this section discusses declarative installation of Emacs packages through
nixpkgs.
Note: This documentation describes the new Emacs packages framework in NixOS 16.03 (emacsPackagesNg) which should not be
confused with the previous and deprecated framework (emacs24Packages).
The first step to declare the list of packages you want in your Emacs installation is to create a dedicated derivation. This can be done in a dedicated
emacs.nix file such as:
emacs.nix)
Example 16.1. Nix expression to build Emacs with packages (emacs.nix
/*
This is a nix expression to build Emacs and some Emacs packages I like
from source on any distribution where Nix is installed. This will install
all the dependencies from the nixpkgs repository and build the binary files
without interfering with the host distribution.
To build the project, type the following from the current directory:
$ nix-build emacs.nix
$ ./result/bin/emacs
*/
{ pkgs ? import <nixpkgs> {} }:
let
myEmacs = pkgs.emacs;
emacsWithPackages = (pkgs.emacsPackagesNgGen myEmacs).emacsWithPackages;
in
emacsWithPackages (epkgs: (with epkgs.melpaStablePackages; [
magit # ; Integrate git <C-x g>
zerodark-theme # ; Nicolas' theme
]) ++ (with epkgs.melpaPackages; [
undo-tree # ; <C-x u> to show the undo tree
zoom-frm # ; increase/decrease font size for all buffers %lt;C-x C-+>
]) ++ (with epkgs.elpaPackages; [
auctex # ; LaTeX mode
beacon # ; highlight my cursor when scrolling
nameless # ; hide current package name everywhere in elisp code
]) ++ [
pkgs.notmuch # From main packages set
])
The first non-comment line in this file ({ pkgs ? ... }) indicates that the whole file represents a function.
The let expression below defines a myEmacs binding pointing to the current stable version of Emacs. This binding is here to separate the
choice of the Emacs binary from the specification of the required packages.
This generates an emacsWithPackages function. It takes a single argument: a function from a package set to a list of packages (the pack
ages that will be available in Emacs).
The rest of the file specifies the list of packages to install. In the example, two packages (magit and zerodark-theme) are taken from
MELPA stable.
Two packages (undo-tree and zoom-frm) are taken from MELPA.
The result of this configuration will be an emacs command which launches Emacs with all of your chosen packages in the load-path.
$ nix-build emacs.nix
$ ./result/bin/emacs -q
and then typing M-x package-initialize. Check that you can use all the packages you want in this Emacs instance. For example, try switching
to the zerodark theme through M-x load-theme <RET> zerodark <RET> y.
Tip
A few popular extensions worth checking out are: auctex, company, edit-server, flycheck, helm, iedit, magit, multiple-cursors, projectile, and
yasnippet.
The list of available packages in the various ELPA repositories can be seen with the following commands:
If you are on NixOS, you can install this particular Emacs for all users by adding it to the list of system packages (see Section 6.1, Declarative Pack
age Management (index.html#sec-declarative-package-mgmt)). Simply modify your file configuration.nix to make it contain:
{
environment.systemPackages = [
# [...]
(import /path/to/emacs.nix { inherit pkgs; })
];
}
In this case, the next nixos-rebuild switch will take care of adding your emacs to the PATH environment variable (see Chapter 3, Changing the Con
figuration (index.html#sec-changing-config)).
If you are not on NixOS or want to install this particular Emacs only for yourself, you can do so by adding it to your ~/.config/nixpkgs/con
fig.nix (see Nixpkgs manual (http://nixos.org/nixpkgs/manual/#sec-modify-via-packageOverrides)):
{
packageOverrides = super: let self = super.pkgs; in {
myemacs = import /path/to/emacs.nix { pkgs = self; };
};
}
In this case, the next nix-env -f '<nixpkgs>' -iA myemacs will take care of adding your emacs to the PATH environment variable.
After building this file as shown in Example 16.1, Nix expression to build Emacs with packages (emacs.nix) (index.html#ex-emacsNix), you will get
an GTK3-based Emacs binary pre-loaded with your favorite packages.
Source: modules/services/editors/emacs.nix
services.emacs.enable = true;
services.emacs.package = import /home/cassou/.emacs.d { pkgs = pkgs; };
The services.emacs.package option allows a custom derivation to be used, for example, one created by emacsWithPackages.
Ensure that the Emacs server is enabled for your user's Emacs configuration, either by customizing the server-mode variable, or by adding
(server-start) to ~/.emacs.d/init.el.
emacsclient FILENAME
emacsclient --create-frame # opens a new frame (window)
emacsclient --create-frame --tty # opens a new frame on the current terminal
Any setting of EDITOR in the shell config files will override services.emacs.defaultEditor. To make sure EDITOR refers to the Emacs wrapper
script, remove any existing EDITOR assignment from .profile, .bashrc, .zshenv or any other shell config file.
If you have formed certain bad habits when editing files, these can be corrected with a shell alias to the wrapper script:
alias vi=$EDITOR
services.emacs.enable = false;
services.emacs.install = true;
To enable the systemd user service for just the currently logged in user, run:
(require 'package)
After the declarative emacs package configuration has been tested, previously downloaded packages can be cleaned up by removing ~/.emac
s.d/elpa (do make a backup first, in case you forgot a package).
To install the DocBook 5.0 schemas, either add pkgs.docbook5 to environment.systemPackages (NixOS (index.html#sec-declarative-package-
mgmt)), or run nix-env -i pkgs.docbook5 (Nix (index.html#sec-ad-hoc-packages)).
Then customize the variable rng-schema-locating-files to include ~/.emacs.d/schemas.xml and put the following text into that file:
~/.emacs.d/schemas.xml)
Example 16.7. nXML Schema Configuration (~/.emacs.d/schemas.xml
<?xml version="1.0"?>
<!--
To let emacs find this file, evaluate:
(add-to-list 'rng-schema-locating-files "~/.emacs.d/schemas.xml")
-->
<locatingRules xmlns="http://thaiopensource.com/ns/locating-rules/1.0">
<!--
Use this variation if pkgs.docbook5 is added to environment.systemPackages
-->
<namespace ns="http://docbook.org/ns/docbook"
uri="/run/current-system/sw/share/xml/docbook-5.0/rng/docbookxi.rnc"/>
<!--
Use this variation if installing schema with "nix-env -iA pkgs.docbook5".
<namespace ns="http://docbook.org/ns/docbook"
uri="../.nix-profile/share/xml/docbook-5.0/rng/docbookxi.rnc"/>
-->
</locatingRules>
17.1. Configuring
To enable PostgreSQL, add the following to your configuration.nix:
services.postgresql.enable = true;
services.postgresql.package = pkgs.postgresql94;
Note that you are required to specify the desired version of PostgreSQL (e.g. pkgs.postgresql94). Since upgrading your PostgreSQL version re
quires a database dump and reload (see below), NixOS cannot provide a default value for services.postgresql.package such as the most re
cent release of PostgreSQL.
By default, PostgreSQL stores its databases in /var/db/postgresql. You can override this using services.postgresql.dataDir, e.g.
services.postgresql.dataDir = "/data/postgresql";
17.2. Upgrading
FIXME: document dump/upgrade/load cycle.
17.3. Options
FIXME: auto-generated list of module options.
security.hideProcessInformation = true;
ensures that access to process information is restricted to the owning user. This implies, among other things, that command-line arguments remain
private. Unless your deployment relies on unprivileged users being able to inspect the process information of other users, this option should be safe to
enable.
Members of the proc group are exempt from process information hiding.
systemd.services.foo.serviceConfig.SupplementaryGroups = [ "proc" ];
The NixOS grsecurity/PaX module is designed with casual users in mind and is intended to be compatible with normal desktop usage, without unnec
essarily compromising security. The following sections describe the configuration and administration of a grsecurity/PaX enabled NixOS system. For
more comprehensive coverage, please refer to the grsecurity wikibook (https://en.wikibooks.org/wiki/Grsecurity) and the Arch Linux wiki page on grse
curity (https://wiki.archlinux.org/index.php/Grsecurity).
Note: grsecurity/PaX is only available for the latest linux -stable kernel; patches against older kernels are available from upstream only for a
fee.
Note: We standardise on a desktop oriented configuration primarily due to lack of resources. The grsecurity/PaX configuration state space is
huge and each configuration requires quite a bit of testing to ensure that the resulting packages work as advertised. Defining additional
package sets would likely result in a large number of functionally broken packages, to nobody's benefit.
security.grsecurity.enable = true;
followed by
# nixos-rebuild boot
# reboot
Note: Enabling the grsecurity module overrides boot.kernelPackages, to reduce the risk of misconfiguration. Section 19.5, Using a
custom grsecurity/PaX kernel (index.html#sec-grsec-custom-kernel) describes how to use a custom kernel package set.
For most users, further configuration should be unnecessary. All users are encouraged to look over Section 19.4, Security considerations (in
dex.html#sec-grsec-security) before using the system, however. If you experience problems, please refer to Section 19.7, Issues and work-arounds
(index.html#sec-grsec-issues).
Once booted into the new system, you can optionally use paxtest to exercise various PaX features:
The NixOS module exposes a limited number of options for tuning the behavior of grsecurity/PaX. These are options thought to be of particular inter
est to most users. For experts, further tuning is possible via boot.kernelParams (see Section 19.8, Grsecurity/PaX kernel parameters (in
dex.html#sec-grsec-kernel-params)) and boot.kernel.sysctl."kernel.grsecurity.*" (the wikibook contains an exhaustive listing of grsecu
rity sysctl tunables (https://en.wikibooks.org/wiki/Grsecurity/Appendix/Sysctl_Options)).
security.grsecurity.lockTunables = false;
Once booted into this system, grsecurity features that have a corresponding sysctl tunable can be changed without rebooting, either by switching into
a new system profile or via the sysctl utility.
Trusted path execution: a desirable feature, but requires some more work to operate smoothly on NixOS.
The NixOS module conditionally weakens chroot restrictions to accommodate NixOS lightweight containers and sandboxed Nix builds. This can
be problematic if the deployment also runs privileged network facing processes that rely on chroot for isolation.
The NixOS kernel is patched to allow usermode helpers from anywhere in the Nix store. A usermode helper is an executable called by the kernel in
certain circumstances, e.g., modprobe. Vanilla grsecurity only allows usermode helpers from paths typically owned by the super user. The NixOS
kernel allows an attacker to inject malicious code into the Nix store which could then be executed by the kernel as a usermode helper.
The following features are disabled because they overlap with vanilla kernel mechanisms:
/proc hardening: use security.hideProcessInformation instead. This trades weaker protection for greater compatibility.
To build a custom kernel using upstream's recommended settings for server deployments, while still using the NixOS module:
nixpkgs.config.packageOverrides = super: {
linux_grsec_nixos = super.linux_grsec_nixos.override {
extraConfig = ''
GRKERNSEC_CONFIG_AUTO y
GRKERNSEC_CONFIG_SERVER y
GRKERNSEC_CONFIG_SECURITY y
'';
};
};
The grsecurity/PaX wikibook provides an exhaustive listing of kernel configuration options (https://en.wikibooks.org/wiki/Grsecurity/Appendix/Grsecu
rity_and_PaX_Configuration_Options).
The NixOS module makes several assumptions about the kernel and so may be incompatible with your customised kernel. Currently, the only way to
work around these incompatibilities is to eschew the NixOS module.
If not using the NixOS module, a custom grsecurity package set can be specified inline instead, as in
boot.kernelPackages =
let
kernel = pkgs.linux_grsec_nixos.override {
extraConfig = /* as above */;
};
self = pkgs.linuxPackagesFor kernel self;
in self;
For executables installed outside of the Nix store, PaX flags can be set using the paxctl utility:
paxctl -czem foo
Access to EFI runtime services is disabled by default: this plugs a potential code injection attack vector; use security.grsecurity.disable
EfiRuntimeServices to override this behavior.
User initiated autoloading of modules (e.g., when using fuse or loop devices) is disallowed; either load requisite modules as root or add them to
boot.kernelModules.
Virtualization: KVM is the preferred virtualization solution. Xen, Virtualbox, and VMWare are unsupported and most likely require a custom kernel.
Attaching gdb to a running process is disallowed by default: unprivileged users can only ptrace processes that are children of the ptracing
process. To relax this restriction, set
boot.kernel.sysctl."kernel.grsecurity.harden_ptrace" = 0;
Overflows in boot critical code (e.g., the root filesystem module) can render the system unbootable. Work around by setting
boot.kernelParams = [ "pax_size_overflow_report_only" ];
The modify_ldt (2) syscall is disabled by default. This restriction can interfere with programs designed to run legacy 16-bit or segmented 32-bit
code. To support applications that rely on this syscall, set
boot.kernel.sysctl."kernel.modify_ldt" = 1;
The gitlab service (Chapter 15, Gitlab (index.html#module-services-gitlab)) requires a variant of the ruby interpreter built without `mprotect()` hard
ening, as in
services.gitlab.packages.gitlab = pkgs.gitlab.override {
ruby = pkgs.ruby.overrideAttrs (attrs: {
postFixup = "paxmark m $out/bin/ruby";
});
};
pax_weakuderef: enable a faster but weaker variant of UDEREF on 64-bit processors with PCID support (check grep pcid /proc/cpuinfo).
pax_size_overflow_report_only: log size overflow violations but leave the violating task running
grsec_sysfs_restrict=[0|1]: toggle sysfs restrictions. The NixOS module sets this to 0 for systemd compatibility
20.1. Prerequisites
You need to have a running HTTP server for verification. The server must have a webroot defined that can serve .well-known/acme-challenge.
This directory must be writeable by the user that will run the ACME client.
http {
server {
server_name _;
listen 80;
listen [::]:80;
location /.well-known/acme-challenge {
root /var/www/challenges;
}
location / {
return 301 https://$host$request_uri;
}
}
}
20.2. Configuring
To enable ACME certificate retrieval & renewal for a certificate for foo.example.com, add the following in your configuration.nix:
security.acme.certs."foo.example.com" = {
webroot = "/var/www/challenges";
email = "foo@example.com";
};
The private key key.pem and certificate fullchain.pem will be put into /var/lib/acme/foo.example.com. The target directory can be config
ured with the option security.acme.directory.
Refer to Appendix A, Configuration Options (options.html) for all available configuration options for the security.acme module.
At the moment you still have to restart Nginx after the ACME certs arrive.
21.1. IBus
IBus is an Intelligent Input Bus. It provides full featured and user friendly input method user interface.
i18n.inputMethod = {
enabled = "ibus";
ibus.engines = with pkgs.ibus-engines; [ anthy hangul mozc ];
};
Anthy (ibus-engines.anthy): Anthy is a system for Japanese input method. It converts Hiragana text to Kana Kanji mixed text.
m17n (ibus-engines.m17n): m17n is an input method that uses input methods and corresponding icons in the m17n database.
table-others (ibus-engines.table-others): Various table-based input methods. To use this, and any other table-based input methods, it
must appear in the list of engines along with table. For example:
To use any input method, the package must be added in the configuration, as shown above, and also (after running nixos-rebuild) the input
method must be added from IBus' preference dialog.
21.2. Fcitx
Fcitx is an input method framework with extension support. It has three built-in Input Method Engine, Pinyin, QuWei and Table-based input methods.
i18n.inputMethod = {
enabled = "fcitx";
fcitx.engines = with pkgs.fcitx-engines; [ mozc hangul m17n ];
};
Anthy (fcitx-engines.anthy): Anthy is a system for Japanese input method. It converts Hiragana text to Kana Kanji mixed text.
Chewing (fcitx-engines.chewing): Chewing is an intelligent Zhuyin input method. It is one of the most popular input methods among Tradi
tional Chinese Unix users.
m17n (fcitx-engines.m17n): m17n is an input method that uses input methods and corresponding icons in the m17n database.
21.3. Nabi
Nabi is an easy to use Korean X input method. It allows you to enter phonetic Korean characters (hangul) and pictographic Korean characters (hanja).
i18n.inputMethod = {
enabled = "nabi";
};
21.4. Uim
Uim (short for "universal input method") is a multilingual input method framework. Applications can use it through so-called bridges.
i18n.inputMethod = {
enabled = "uim";
};
This chapter describes various aspects of managing a running NixOS system, such as how to use the systemd service manager.
Chapter 22. Service Management
In NixOS, all system services are started and monitored using the systemd program. Systemd is the init process of the system (i.e. PID 1), the parent
of all other processes. It manages a set of so-called units, which can be things like system services (programs), but also mount points, swap files,
devices, targets (groups of units) and more. Units can have complex dependencies; for instance, one unit can require that another unit must be suc
cessfully started before the first unit can be started. When the system boots, it starts a unit named default.target; the dependencies of this unit
cause all system services to be started, file systems to be mounted, swap files to be activated, and so on.
The command systemctl is the main way to interact with systemd. Without any arguments, it shows the status of active units:
$ systemctl
-.mount loaded active mounted /
swapfile.swap loaded active active /swapfile
sshd.service loaded active running SSH Daemon
graphical.target loaded active active Graphical Interface
...
You can ask for detailed status information about a unit, for instance, the PostgreSQL database service:
Jan 07 15:55:55 hagbard postgres[2394]: [1-1] LOG: database system was shut down at 2013-01-07 15:55:05 CET
Jan 07 15:55:57 hagbard postgres[2390]: [1-1] LOG: database system is ready to accept connections
Jan 07 15:55:57 hagbard postgres[2420]: [1-1] LOG: autovacuum launcher started
Jan 07 15:55:57 hagbard systemd[1]: Started PostgreSQL Server.
Note that this shows the status of the unit (active and running), all the processes belonging to the service, as well as the most recent log messages
from the service.
These operations are synchronous: they wait until the service has finished starting or stopping (or has failed). Starting a unit will cause the dependen
cies of that unit to be started as well (if necessary).
# shutdown
which is equivalent to systemctl reboot. Alternatively, you can quickly reboot the system using kexec, which bypasses the BIOS by directly loading
the new kernel into memory:
# systemctl kexec
The machine can be suspended to RAM (if supported) using systemctl suspend, and suspended to disk using systemctl hibernate.
These commands can be run by any user who is logged in locally, i.e. on a virtual console or in X11; otherwise, the user is asked for authentication.
$ loginctl
SESSION UID USER SEAT
c1 500 eelco seat0
c3 0 root seat0
c4 500 alice
This shows that two users are logged in locally, while another is logged in remotely. (Seats are essentially the combinations of displays and input de
vices attached to the system; usually, there is only one seat.) To get information about a session:
$ loginctl session-status c3
c3 - root (0)
Since: Tue, 2013-01-08 01:17:56 CET; 4min 42s ago
Leader: 2536 (login)
Seat: seat0; vc3
TTY: /dev/tty3
Service: login; type tty; class user
State: online
CGroup: name=systemd:/user/root/c3
"# 2536 /nix/store/10mn4xip9n7y9bxqwnsx7xwx2v2g34xn-shadow-4.1.5.1/bin/login --
"#10339 -bash
$#10355 w3m nixos.org
This shows that the user is logged in on virtual console 3. It also lists the processes belonging to this session. Since systemd keeps track of this, you
can terminate a session in a way that ensures that all the sessions processes are gone:
# loginctl terminate-session c3
The command systemd-cgls lists all control groups in the systemd hierarchy, which is what systemd uses to keep track of the processes belonging
to each service or user session:
$ systemd-cgls
"#user
% $#eelco
% $#c1
% "# 2567 -:0
% "# 2682 kdeinit4: kdeinit4 Running...
% "# ...
% $#10851 sh -c less -R
$#system
"#httpd.service
% "#2444 httpd -f /nix/store/3pyacby5cpr55a03qwbnndizpciwq161-httpd.conf -DNO_DETACH
% $#...
"#dhcpcd.service
% $#2376 dhcpcd --config /nix/store/f8dif8dsi2yaa70n03xir8r653776ka6-dhcpcd.conf
$# ...
Similarly, systemd-cgls cpu shows the cgroups in the CPU hierarchy, which allows per-cgroup CPU scheduling priorities. By default, every systemd
service gets its own CPU cgroup, while all user sessions are in the top-level CPU cgroup. This ensures, for instance, that a thousand run-away pro
cesses in the httpd.service cgroup cannot starve the CPU for one process in the postgresql.service cgroup. (By contrast, it they were in the
same cgroup, then the PostgreSQL process would get 1/1001 of the cgroups CPU time.) You can limit a services CPU share in configura
tion.nix:
systemd.services.httpd.serviceConfig.CPUShares = 512;
By default, every cgroup has 1024 CPU shares, so this will halve the CPU allocation of the httpd.service cgroup.
There also is a memory hierarchy that controls memory allocation limits; by default, all processes are in the top-level cgroup, so any service or session
can exhaust all available memory. Per-cgroup memory limits can be specified in configuration.nix; for instance, to limit httpd.service to 512
MiB of RAM (excluding swap):
systemd.services.httpd.serviceConfig.MemoryLimit = "512M";
The command systemd-cgtop shows a continuously updated list of all cgroups with their CPU and memory usage.
$ journalctl -b
shows all journal entries since the last reboot. (The output of journalctl is piped into less by default.) You can use various options and match opera
tors to restrict output to messages of interest. For instance, to get all messages from PostgreSQL:
$ journalctl -u postgresql.service
-- Logs begin at Mon, 2013-01-07 13:28:01 CET, end at Tue, 2013-01-08 01:09:57 CET. --
...
Jan 07 15:44:14 hagbard postgres[2681]: [2-1] LOG: database system is shut down
-- Reboot --
Jan 07 15:45:10 hagbard postgres[2532]: [1-1] LOG: database system was shut down at 2013-01-07 15:44:14 CET
Jan 07 15:45:13 hagbard postgres[2500]: [1-1] LOG: database system is ready to accept connections
Or to get all messages since the last reboot that have at least a critical severity level:
$ journalctl -b -p crit
Dec 17 21:08:06 mandark sudo[3673]: pam_unix(sudo:auth): auth could not identify password for [alice]
Dec 29 01:30:22 mandark kernel[6131]: [1053513.909444] CPU6: Core temperature above threshold, cpu clock throttled (t
otal events = 1)
The system journal is readable by root and by users in the wheel and systemd-journal groups. All users have a private journal that can be read
using journalctl.
$ nix-collect-garbage
Alternatively, you can use a systemd unit that does the same in the background:
You can tell NixOS in configuration.nix to run this unit automatically at certain points in time, for instance, every night at 03:15:
nix.gc.automatic = true;
nix.gc.dates = "03:15";
The commands above do not remove garbage collector roots, such as old system configurations. Thus they do not remove the ability to roll back to
previous configurations. The following command deletes old roots, removing the ability to roll back to them:
$ nix-collect-garbage -d
Note that NixOS system configurations are stored in the profile /nix/var/nix/profiles/system.
Another way to reclaim disk space (often as much as 40% of the size of the Nix store) is to run Nixs store optimiser, which seeks out identical files in
the store and replaces them with hard links to a single copy.
$ nix-store --optimise
Since this command needs to read the entire Nix store, it can take quite a while to finish.
Warning: Currently, NixOS containers are not perfectly isolated from the host system. This means that a user with root access to the container
can do things that aect the host. So you should not give container root access to untrusted users.
NixOS containers can be created in two ways: imperatively, using the command nixos-container, and declaratively, by specifying them in your con
figuration.nix. The declarative approach implies that containers get upgraded along with your host system when you run nixos-rebuild, which is
often not what you want. By contrast, in the imperative approach, containers are configured and updated independently from the host system.
Creating a container does not start it. To start the container, run:
This command will return as soon as the container has booted and has reached multi-user.target. On the host, the container runs within a sys
temd unit called container@container-name.service. Thus, if something went wrong, you can get status info using systemctl:
If the container has started succesfully, you can log in as root using the root-login operation:
Note that only root on the host can do this (since there is no authentication). You can also get a regular login prompt using the login operation, which
is available to all users on the host:
With nixos-container run, you can execute arbitrary commands in the container:
There are several ways to change the configuration of the container. First, on the host, you can edit /var/lib/container/name/etc/nixos/con
figuration.nix, and run
This will build and activate the new configuration. You can also specify a new configuration on the command line:
Alternatively, you can change the configuration from within the container itself by running nixos-rebuild switch inside the container. Note that the con
tainer by default does not have a copy of the NixOS channel, so you should run nix-channel --update first.
Containers can be stopped and started using nixos-container stop and nixos-container start, respectively, or by using systemctl on the
containers service unit. To destroy a container, including its file system, do
containers.database =
{ config =
{ config, pkgs, ... }:
{ services.postgresql.enable = true;
services.postgresql.package = pkgs.postgresql92;
};
};
If you run nixos-rebuild switch, the container will be built. If the container was already running, it will be updated in place, without rebooting.
The container can be configured to start automatically by setting containers.database.autoStart = true in its configuration.
By default, declarative containers share the network namespace of the host, meaning that they can listen on (privileged) ports. However, they cannot
change the network configuration. You can give a container its own network as follows:
containers.database =
{ privateNetwork = true;
hostAddress = "192.168.100.10";
localAddress = "192.168.100.11";
};
This gives the container a private virtual Ethernet interface with IP address 192.168.100.11, which is hooked up to a virtual Ethernet interface on
the host with IP address 192.168.100.10. (See the next section for details on container networking.)
To disable the container, just remove it from configuration.nix and run nixos-rebuild switch. Note that this will not delete the root directory
of the container in /var/lib/containers. Containers can be destroyed using the imperative method: nixos-container destroy foo.
Declarative containers can be started and stopped using the corresponding systemd service, e.g. systemctl start container@database.
Networking is implemented using a pair of virtual Ethernet devices. The network interface in the container is called eth0, while the matching interface
in the host is called ve-container-name (e.g., ve-foo). The container has its own network namespace and the CAP_NET_ADMIN capability, so it
can perform arbitrary network configuration such as setting up firewall rules, without aecting or having access to the hosts network.
By default, containers cannot talk to the outside network. If you want that, you should set up Network Address Translation (NAT) rules on the host to
rewrite container trac to use your external IP address. This can be accomplished using the following configuration on the host:
networking.nat.enable = true;
networking.nat.internalInterfaces = ["ve-+"];
networking.nat.externalInterface = "eth0";
where eth0 should be replaced with the desired external interface. Note that ve-+ is a wildcard that matches all container interfaces.
If you are using Network Manager, you need to explicitly prevent it from managing container interfaces:
networking.networkmanager.unmanaged = [ "interface-name:ve-*" ];
Chapter 29. Troubleshooting
This chapter describes solutions to common problems you might encounter when you manage your NixOS system.
boot.shell_on_fail
Start a root shell if something goes wrong in stage 1 of the boot process (the initial ramdisk). This is disabled by default because there is no authenti
cation for the root shell.
boot.debug1
Start an interactive shell in stage 1 before anything useful has been done. That is, no modules have been loaded and no file systems have been
mounted, except for /proc and /sys.
boot.trace
Print every shell command executed by the stage 1 and 2 boot scripts.
single
Boot into rescue mode (a.k.a. single user mode). This will cause systemd to start nothing but the unit rescue.target, which runs sulogin to
prompt for the root password and start a root login shell. Exiting the shell causes the system to continue with the normal boot process.
systemd.log_level=debug systemd.log_target=console
Make systemd very verbose and send log messages to the console instead of the journal.
If no login prompts or X11 login screens appear (e.g. due to hanging dependencies), you can press Alt+ArrowUp. If youre lucky, this will start rescue
mode (described above). (Also note that since most units have a 90-second timeout before systemd gives up on them, the agetty login prompts
should appear eventually unless something is very wrong.)
# systemctl rescue
This will eventually give you a single-user root shell. Systemd will stop (almost) all system services. To get out of maintenance mode, just exit from the
rescue shell.
First, the GRUB boot manager allows you to boot into any previous configuration that hasnt been garbage-collected. These configurations can be
found under the GRUB submenu NixOS - All configurations. This is especially useful if the new configuration fails to boot. After the system has boot
ed, you can make the selected configuration the default for subsequent boots:
# /run/current-system/bin/switch-to-configuration boot
# /nix/var/nix/profiles/system-N-link/bin/switch-to-configuration switch
where N is the number of the NixOS system configuration. To get a list of the available configurations, do:
$ ls -l /nix/var/nix/profiles/system-*-link
...
lrwxrwxrwx 1 root root 78 Aug 12 13:54 /nix/var/nix/profiles/system-268-link -> /nix/store/202b...-nixos-13.07pre4932
_5a676e4-4be1055
If the corruption is in a path in the closure of the NixOS system configuration, you can fix it by doing
This will cause Nix to check every path in the closure, and if its cryptographic hash diers from the hash recorded in Nixs database, the path is rebuilt
or redownloaded.
You can also scan the entire Nix store for corrupt paths:
Any corrupt paths will be redownloaded if theyre available in a binary cache; otherwise, they cannot be repaired.
If you have an alternative binary cache at your disposal, you can use it instead:
This chapter describes how you can modify and extend NixOS.
This will check out the latest Nixpkgs sources to ./nixpkgs the NixOS sources to ./nixpkgs/nixos. (The NixOS source tree lives in a subdirecto
ry of the Nixpkgs repository.) The remote channels refers to a read-only repository that tracks the Nixpkgs/NixOS channels (see Chapter 4, Upgrad
ing NixOS (index.html#sec-upgrading) for more information about channels). Thus, the Git branch channels/nixos-17.03 will contain the latest
built and tested version available in the nixos-17.03 channel.
Its often inconvenient to develop directly on the master branch, since if somebody has just committed (say) a change to GCC, then the binary cache
may not have caught up yet and youll have to rebuild everything from source. So you may want to create a local branch based on your current NixOS
version:
$ nixos-version
17.09pre104379.6e0b727 (Hummingbird)
Or, to base your local branch on the latest version available in a NixOS channel:
(Replace nixos-17.03 with the name of the channel you want to use.) You can use git merge or git rebase to keep your local branch in sync with
the channel, e.g.
You can use git cherry-pick to copy commits from your local branch to the upstream branch.
If you want to rebuild your system using your (modified) sources, you need to tell nixos-rebuild about them using the -I flag:
If you want nix-env to use the expressions in /my/sources, use nix-env -f /my/sources /nixpkgs, or change the default by adding a symlink in
~/.nix-defexpr:
$ ln -s /my/sources/nixpkgs ~/.nix-defexpr/nixpkgs
You may want to delete the symlink ~/.nix-defexpr/channels_root to prevent roots NixOS channel from clashing with your own tree.
Each NixOS module is a file that handles one logical aspect of the configuration, such as a specific kind of hardware, a service, or network settings. A
module configuration does not have to handle everything from scratch; it can use the functionality provided by other modules for its implementation.
Thus a module can declare options that can be used by other modules, and conversely can define options provided by other modules in its own im
plementation. For example, the module pam.nix (https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/security/pam.nix) declares the op
tion security.pam.services that allows other modules (e.g. sshd.nix (https://github.com/NixOS/nixpkgs/blob/master/nixos/modules/ser
vices/networking/ssh/sshd.nix)) to define PAM services; and it defines the option environment.etc (declared by etc.nix (https://github.
com/NixOS/nixpkgs/blob/master/nixos/modules/system/etc/etc.nix)) to cause files to be created in /etc/pam.d.
In Chapter 5, Configuration Syntax (index.html#sec-configuration-syntax), we saw the following structure of NixOS modules:
{ config, pkgs, ... }:
{ option definitions
}
This is actually an abbreviated form of module that only defines options, but does not declare any. The structure of full NixOS modules is shown in Ex
ample 31.1, Structure of NixOS Modules (index.html#ex-module-syntax).
{
imports =
[ paths of other modules
];
options = {
option declarations
};
config = {
option definitions
};
}
This line makes the current Nix expression a function. The variable pkgs contains Nixpkgs, while config contains the full system configura
tion. This line can be omitted if there is no reference to pkgs and config inside the module.
This list enumerates the paths to other NixOS modules that should be included in the evaluation of the system configuration. A default set of
modules is defined in the file modules/module-list.nix. These don't need to be added in the import list.
The attribute config is a nested set of option definitions (also described below).
Example 31.2, NixOS Module for the locate Service (index.html#locate-example) shows a module that handles the regular update of the locate
database, an index of all files in the file system. This module declares two options that can be defined by other modules (typically the users config
uration.nix): services.locate.enable (whether the database should be updated) and services.locate.interval (when the update
should be done). It implements its functionality by defining two options declared by other modules: systemd.services (the set of all systemd ser
vices) and systemd.timers (the list of commands to be executed periodically by systemd).
with lib;
let
cfg = config.services.locate;
in {
options.services.locate = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
If enabled, NixOS will periodically update the database of
files used by the locate command.
'';
};
interval = mkOption {
type = types.str;
default = "02:15";
example = "hourly";
description = ''
Update the locate database at this interval. Updates by
default at 2:15 AM every day.
config = {
systemd.services.update-locatedb =
{ description = "Update Locate Database";
path = [ pkgs.su ];
script =
''
mkdir -m 0755 -p $(dirname ${toString cfg.output})
exec updatedb \
--localuser=${cfg.localuser} \
${optionalString (!cfg.includeStore) "--prunepaths='/nix/store'"} \
--output=${toString cfg.output} ${concatStringsSep " " cfg.extraFlags}
'';
};
options = {
name = mkOption {
type = type specification;
default = default value;
example = example value;
description = "Description for use in the NixOS manual.";
};
};
type
The type of the option (see Section 31.2, Options Types (index.html#sec-option-types)). It may be omitted, but thats not advisable since it may
lead to errors that are hard to diagnose.
default
The default value used if no value is defined by any module. A default is not required; in that case, if the option value is never used, an error will be
thrown.
example
An example value that will be shown in the NixOS manual.
description
A textual description of the option, in DocBook format, that will be included in the NixOS manual.
Extensible option types can be used for enum options that aects multiple modules, or as an alternative to related enable options.
As an example, we will take the case of display managers. There is a central display manager module for generic display manager options and a mod
ule file per display manager backend (slim, sddm, gdm ...).
Managing the display managers independently by adding an enable option to every display manager module backend. (NixOS)
Managing the display managers in the central module by adding an option to select which display manager backend to use.
Making backends independent can quickly become hard to manage. For display managers, there can be only one enabled at a time, but the type sys
tem can not enforce this restriction as there is no relation between each backend enable option. As a result, this restriction has to be done explicitely
by adding assertions in each display manager backend module.
On the other hand, managing the display managers backends in the central module will require to change the central module option every time a new
backend is added or removed.
By using extensible option types, it is possible to create a placeholder option in the central module (Example 31.3, Extensible type placeholder in the
service module (index.html#ex-option-declaration-eot-service)), and to extend it in each backend module (Example 31.4, Extending ser
vices.xserver.displayManager.enable in the slim module (index.html#ex-option-declaration-eot-backend-slim), Example 31.5, Extending
services.foo.backend in the sddm module (index.html#ex-option-declaration-eot-backend-sddm)).
As a result, displayManager.enable option values can be added without changing the main service module file and the type system automatically
enforce that there can only be a single display manager enabled.
services.xserver.displayManager.enable = mkOption {
type = with types; nullOr (enum [ "slim" ]);
};
services.xserver.displayManager.enable = mkOption {
type = with types; nullOr (enum [ "sddm" ]);
};
The placeholder declaration is a standard mkOption declaration, but it is important that extensible option declarations only use the type argument.
Extensible option types work with any of the composed variants of enum such as with types; nullOr (enum [ "foo" "bar" ]) or
with types; listOf (enum [ "foo" "bar" ]).
types.bool
A boolean, its values can be true or false.
types.int
An integer.
types.path
A filesystem path, defined as anything that when coerced to a string starts with a slash. Even if derivations can be considered as path, the more spe
cific types.package should be preferred.
types.package
A derivation or a store path.
types.str
A string. Multiple definitions cannot be merged.
types.lines
A string. Multiple definitions are concatenated with a new line "\n".
types.commas
A string. Multiple definitions are concatenated with a comma ",".
types.envVar
A string. Multiple definitions are concatenated with a collon ":".
types.enum l
One element of the list l, e.g. types.enum [ "left" "right" ]. Multiple definitions cannot be merged.
types.separatedString sep
A string with a custom separator sep, e.g. types.separatedString "|".
types.submodule o
A set of sub options o. o can be an attribute set or a function returning an attribute set. Submodules are used in composed types to create modular
options. Submodule are detailed in Section 31.2.4, Submodule (index.html#section-option-types-submodule).
types.listOf t
A list of t type, e.g. types.listOf int. Multiple definitions are merged with list concatenation.
types.attrsOf t
An attribute set of where all the values are of t type. Multiple definitions result in the joined attribute set.
types.loaOf t
An attribute set or a list of t type. Multiple definitions are merged according to the value.
types.nullOr t
null or type t. Multiple definitions are merged according to type t.
types.uniq t
Ensures that type t cannot be merged. It is used to ensure option definitions are declared only once.
types.either t1 t2
Type t1 or type t2, e.g. with types; either int str. Multiple definitions cannot be merged.
31.2.4. Submodule
Submodule is a very powerful type that defines a set of sub-options that are handled like a separate module. It is especially interesting when used
with composed types like attrsOf or listOf.
The submodule type take a parameter o, that should be a set, or a function returning a set with an options key defining the sub-options. The option
set can be defined directly (Example 31.6, Directly defined submodule (index.html#ex-submodule-direct)) or as reference (Example 31.7, Submod
ule defined as a reference (index.html#ex-submodule-reference)).
Submodule option definitions are type-checked accordingly to the options declarations. It is possible to declare submodule options inside a submod
ule sub-options for even higher modularity.
let
modOptions = {
options = {
foo = mkOption {
type = int;
};
bar = mkOption {
type = int;
};
};
};
in
options.mod = mkOption {
description = "submodule example";
type = with types; listOf (submodule modOptions);
};
options.mod = mkOption {
description = "submodule example";
type = with types; listOf (submodule {
options = {
foo = mkOption {
type = int;
};
bar = mkOption {
type = str;
};
};
});
};
Example 31.9. Definition of a list of submodules
config.mod = [
{ foo = 1; bar = "one"; }
{ foo = 2; bar = "two"; }
];
options.mod = mkOption {
description = "submodule example";
type = with types; attrsOf (submodule {
options = {
foo = mkOption {
type = int;
};
bar = mkOption {
type = str;
};
};
});
};
check
The function to type check the value. Takes a value as parameter and return a boolean. It is possible to extend a type check with the addCheck
function (Example 31.12, Adding a type check (index.html#ex-extending-type-check-1)), or to fully override the check function (Example 31.13,
Overriding a type check (index.html#ex-extending-type-check-2)).
byte = mkOption {
description = "An integer between 0 and 255.";
type = addCheck (x: x >= 0 && x <= 255) types.int;
};
merge
Function to merge the options values when multiple values are set. The function takes two parameters, loc the option path as a list of strings, and
defs the list of defined values as a list. It is possible to override a type merge function for custom needs.
name
A string representation of the type function name.
definition
Description of the type used in documentation. Give information of the type and any of its arguments.
check
A function to type check the definition value. Takes the definition value as a parameter and returns a boolean indicating the type check result, true
for success and false for failure.
merge
A function to merge multiple definitions values. Takes two parameters:
loc
The option path as a list of strings, e.g. ["boot" "loader "grub" "enable"].
defs
The list of sets of defined value and file where the value was defined, e.g.
[ { file = "/foo.nix"; value = 1; } { file = "/bar.nix"; value = 2 } ]. The merge function should return the merged value
or throw an error in case the values are impossible or not meant to be merged.
getSubOptions
For composed types that can take a submodule as type parameter, this function generate sub-options documentation. It takes the current option
prefix as a list and return the set of sub-options. Usually defined in a recursive manner by adding a term to the prefix, e.g.
prefix: elemType.getSubOptions (prefix ++ ["prefix"]) where "prefix" is the newly added prefix.
getSubModules
For composed types that can take a submodule as type parameter, this function should return the type parameters submodules. If the type parame
ter is called elemType, the function should just recursively look into submodules by returning elemType.getSubModules;.
substSubModules
For composed types that can take a submodule as type parameter, this function can be used to substitute the parameter of a submodule type. It
takes a module as parameter and return the type with the submodule options substituted. It is usally defined as a type function call with a recursive
call to substSubModules, e.g for a type composedType that take an elemtype type parameter, this function should be defined as
m: composedType (elemType.substSubModules m).
typeMerge
A function to merge multiple type declarations. Takes the type to merge functor as parameter. A null return value means that type cannot be
merged.
f
The type to merge functor.
Note: There is a generic defaultTypeMerge that work with most of value and composed types.
functor
An attribute set representing the type. It is used for type operations and has the following keys:
type
The type function.
wrapped
Holds the type parameter for composed types.
payload
Holds the value parameter for value types. The types that have a payload are the enum, separatedString and submodule types.
binOp
A binary operation that can merge the payloads of two same types. Defined as a function that take two payloads as parameters and return the pay
loads merged.
config = {
services.httpd.enable = true;
};
However, sometimes you need to wrap an option definition or set of option definitions in a property to achieve certain eects:
Delaying Conditionals
If a set of option definitions is conditional on the value of another option, you may need to use mkIf. Consider, for instance:
This definition will cause Nix to fail with an infinite recursion error. Why? Because the value of config.services.httpd.enable depends on the
value being constructed here. After all, you could also write the clearly circular and contradictory:
The special function mkIf causes the evaluation of the conditional to be pushed down into the individual definitions, as if you had written:
config = {
environment.systemPackages = if config.services.httpd.enable then [ ... ] else [];
...
};
Setting Priorities
A module can override the definitions of an option in other modules by setting a priority. All option definitions that do not have the lowest priority value
are discarded. By default, option definitions have priority 1000. You can specify an explicit priority by using mkOverride, e.g.
This definition causes all other definitions with priorities above 10 to be discarded. The function mkForce is equal to mkOverride 50.
Merging Configurations
In conjunction with mkIf, it is sometimes useful for a module to return multiple sets of option definitions, to be merged together as if they were de
clared in separate modules. This can be done using mkMerge:
config = mkMerge
[ # Unconditional stuff.
{ environment.systemPackages = [ ... ];
}
# Conditional stuff.
(mkIf config.services.bla.enable {
environment.systemPackages = [ ... ];
})
];
meta is a top level attribute like options and config. Available meta-attributes are maintainers and doc.
Each of the meta-attributes must be defined at most once per module file.
config = {
...
};
meta = {
maintainers = with lib.maintainers; [ ericsagnes ];
doc = ./default.xml;
};
}
$ cd /path/to/nixpkgs/nixos
$ nix-build -A config.option
where option is a NixOS option with type derivation (i.e. something that can be built). Attributes of interest include:
system.build.toplevel
The top-level option that builds the entire NixOS system. Everything else in your configuration is indirectly pulled in by this option. This is what
nixos-rebuild builds and what /run/current-system points to afterwards.
$ nix-build -A system
system.build.manual.manual
The NixOS manual.
system.build.etc
A tree of symlinks that form the static parts of /etc.
system.build.initialRamdisk
system.build.initialRamdisk, system.build.kernel
The initial ramdisk and kernel of the system. This allows a quick way to test whether the kernel and the initial ramdisk boot correctly, by using
QEMUs -kernel and -initrd options:
system.build.nixos-rebuild
system.build.nixos-rebuild, system.build.nixos-install
system.build.nixos-install, system.build.nixos-generate-config
These build the corresponding NixOS commands.
$ nix-build -A 'config.systemd.units."httpd.service".unit'
You can also test individual units, without rebuilding the whole system, by putting them in /run/systemd/system:
$ cp $(nix-build -A 'config.systemd.units."httpd.service".unit')/httpd.service \
/run/systemd/system/tmp-httpd.service
# systemctl daemon-reload
# systemctl start tmp-httpd.service
Note that the unit must not have the same name as any unit in /etc/systemd/system since those take precedence over /run/systemd/sys
tem. Thats why the unit is installed as tmp-httpd.service here.
When this command successfully finishes, it will tell you where the manual got generated. The HTML will be accessible through the result symlink at
./result/share/doc/nixos/index.html.
Emacs nXML Mode is very helpful for editing DocBook XML because it validates the document as you write, and precisely locates errors. To use it,
see Section 16.3.3, Editing DocBook 5 XML Documents (index.html#sec-emacs-docbook-xml).
Pandoc (http://pandoc.org) can generate DocBook XML from a multitude of formats, which makes a good starting point.
Pandoc can also quickly convert a single section.xml to HTML, which is helpful when drafting.
Sometimes writing valid DocBook is simply too dicult. In this case, submit your documentation updates in a GitHub Issue (https://github.
com/NixOS/nixpkgs/issues/new) and someone will handle the conversion to XML for you.
Keep the following guidelines in mind when you create and add a topic:
Store the topic file in the same directory as the part to which it belongs. If your topic is about configuring a NixOS module, then the XML file can
be stored alongside the module definition nix file.
If you include multiple words in the file name, separate the words with a dash. For example: ipv6-config.xml.
Make sure that the xml:id value is unique. You can use abbreviations if the ID is too long. For example: nixos-config.
Determine whether your topic is a chapter or a section. If you are unsure, open an existing topic file and check whether the main element is chap
ter or section.
If the topic is about configuring a NixOS module, it can be automatically included in the manual by using the meta.doc attribute. See Section 31.4,
Meta Attributes (index.html#sec-meta-attributes) for an explanation.
Chapter 34. Building Your Own NixOS CD
Building a NixOS CD is as easy as configuring your own computer. The idea is to use another module which will replace your configuration.nix
to configure the system that would be installed on the CD.
Default CD/DVD configurations are available inside nixos/modules/installer/cd-dvd. To build them you have to set NIXOS_CONFIG before
running nix-build to build the ISO.
Before burning your CD/DVD, you can check the content of the image by mounting anywhere like suggested by the following command:
import ./make-test.nix {
# Or a set of machines:
nodes =
{ machine1 =
{ config, pkgs, ... }: { };
machine2 =
{ config, pkgs, ... }: { };
};
testScript =
''
Perl code
'';
}
The attribute testScript is a bit of Perl code that executes the test (described below). During the test, it will start one or more virtual machines, the
configuration of which is described by the attribute machine (if you need only one machine in your test) or by the attribute nodes (if you need multiple
machines). For instance, login.nix (https://github.com/NixOS/nixpkgs/blob/master/nixos/tests/login.nix) only needs a single
machine to test whether users can log in on the virtual console, whether device ownership is correctly maintained when switching between consoles,
and so on. On the other hand, nfs.nix (https://github.com/NixOS/nixpkgs/blob/master/nixos/tests/nfs.nix), which tests NFS
client and server functionality in the Linux kernel (including whether locks are maintained across server crashes), requires three machines: a server and
two clients.
There are a few special NixOS configuration options for test VMs:
virtualisation.memorySize
The memory of the VM in megabytes.
virtualisation.vlans
The virtual networks to which the VM is connected. See nat.nix (https://github.com/NixOS/nixpkgs/blob/mas
ter/nixos/tests/nat.nix) for an example.
virtualisation.writableStore
By default, the Nix store in the VM is not writable. If you enable this option, a writable union file system is mounted on top of the Nix store to make it
appear writable. This is necessary for tests that run Nix operations that modify the store.
The test script is a sequence of Perl statements that perform various actions, such as starting VMs, executing commands in the VMs, and so on. Each
virtual machine is represented as an object stored in the variable $name, where name is the identifier of the machine (which is just machine if you
didnt specify multiple machines using the nodes attribute). For instance, the following starts the machine, waits until it has finished booting, then exe
cutes a command and checks that the output is more-or-less correct:
$machine->start;
$machine->waitForUnit("default.target");
$machine->succeed("uname") =~ /Linux/;
The first line is actually unnecessary; machines are implicitly started when you first execute an action on them (such as waitForUnit or succeed). If
you have multiple machines, you can speed up the test by starting them in parallel:
startAll;
start
Start the virtual machine. This method is asynchronous it does not wait for the machine to finish booting.
shutdown
Shut down the machine, waiting for the VM to exit.
crash
Simulate a sudden power failure, by telling the VM to exit immediately.
block
Simulate unplugging the Ethernet cable that connects the machine to the other machines.
unblock
Undo the eect of block.
screenshot
Take a picture of the display of the virtual machine, in PNG format. The screenshot is linked from the HTML log.
getScreenText
Return a textual representation of what is currently visible on the machine's screen using optical character recognition.
sendMonitorCommand
Send a command to the QEMU monitor. This is rarely used, but allows doing stu such as attaching virtual USB disks to a running machine.
sendKeys
Simulate pressing keys on the virtual keyboard, e.g., sendKeys("ctrl-alt-delete").
sendChars
Simulate typing a sequence of characters on the virtual keyboard, e.g., sendKeys("foobar\n") will type the string foobar followed by the Enter
key.
execute
Execute a shell command, returning a list (status, stdout).
succeed
Execute a shell command, raising an exception if the exit status is not zero, otherwise returning the standard output.
fail
Like succeed, but raising an exception if the command returns a zero status.
waitUntilSucceeds
Repeat a shell command with 1-second intervals until it succeeds.
waitUntilFails
Repeat a shell command with 1-second intervals until it fails.
waitForUnit
Wait until the specified systemd unit has reached the active state.
waitForFile
Wait until the specified file exists.
waitForOpenPort
Wait until a process is listening on the given TCP port (on localhost, at least).
waitForClosedPort
Wait until nobody is listening on the given TCP port.
waitForX
Wait until the X11 server is accepting connections.
waitForText
Wait until the supplied regular expressions matches the textual contents of the screen by using optical character recognition (see getScreenText).
waitForWindow
NixOS
Wait until an X11 window has appeared whose name matches the given regular expression, e.g., waitForWindow(qr/Terminal/).
You can run tests using nix-build. For example, to run the test login.nix (https://github.com/NixOS/nixpkgs/blob/mas
Security (../../../nixos/security.html)
ter/nixos/tests/login.nix), you just do:
Search nixos.org
$ nix-build '<nixpkgs/nixos/tests/login.nix>'
$ cd /my/nixpkgs/nixos/tests
$ nix-build login.nix
running the VM test script
machine: QEMU running (pid 8841)
6 out of 6 tests succeeded
After building/downloading all required dependencies, this will perform a build that starts a QEMU/KVM virtual machine containing a NixOS system.
The virtual machine mounts the Nix store of the host; this makes VM creation very fast, as no disk image needs to be created. Afterwards, you can
view a pretty-printed log of the test:
$ firefox result/log.html
35.3. Running Tests interactively
The test itself can be run interactively. This is particularly useful when developing or debugging a test:
> startAll
> testScript
> $machine->succeed("touch /tmp/foo")
The function testScript executes the entire test script and drops you back into the test driver command line upon its completion. This allows you to
inspect the state of the VMs after the test (e.g. to debug the test script).
The script nixos-run-vms starts the virtual machines defined by test. The root file system of the VMs is created on the fly and kept across VM restarts
in ./hostname.qcow2.
$ nix-build -A config.system.build.nixos-install
# mount -t tmpfs none /mnt
# ./result/bin/nixos-install
# ./result/bin/nixos-install --chroot
Discuss with Eelco Dolstra and the community (via IRC, ML) about what will reach the deadline. Any issue or Pull Request targeting the release
should have assigned milestone.
Lock the branch on github (so developers cant force push) (https://github.com/NixOS/nixpkgs/settings/branches)
Create an issue for tracking Zero Hydra Failures progress. ZHF is an eort to get build failures down to zero. (https://github.com/NixOS/nixp
kgs/issues/13559)
Create two Hydra jobsets: release-15.09 and release-15.09-small with stableBranch set to false
Get number of commits for the release: git log release-14.04..release-14.12 --format=%an|wc -l
Send an email to nix-dev to announce the release with above information. Best to check how previous email was formulated to see what needs to
be included.
Source (https://github.com/NixOS/nixpkgs/tree/master/nixos/doc/manual)