About me: My name is Solène Rapenne, pronouns she/her. I like learning and sharing knowledge. Hobbies: '(BSD OpenBSD Qubes OS Lisp cmdline gaming security QubesOS internet-stuff). I love percent and lambda characters. OpenBSD developer solene@. No AI is involved in this blog.

Contact me: solene at dataswamp dot org or @solene@bsd.network (mastodon).

You can sponsor my work financially if you want to help me writing this blog and contributing to Free Software as my daily job.

Managing /etc/hosts on NixOS

Written by Solène, on 14 September 2021.
Tags: #nixos

Comments on Fediverse/Mastodon

1. Introduction §

This is a simple article explaining how to manage entries in /etc/hosts in a NixOS system. Modifying this file is quite useful when you need to make tests on a remote server while its domain name is still not updated so you can force a domain name to be resolved by a given IP address, bypassing DNS queries.

NixOS being what is is, you can't modify the /etc/hosts file directly.

NixOS stable documentation about the extraHosts variable

2. Configuration §

In your /etc/nixos/configuration.nix file, you have to declare the variable networking.extraHosts and use "\n" as separator for entries.

networking.extraHosts = "1.2.3.4 foobar.perso.pw\n1.2.3.5 foo.perso.pw";

or as suggested by @tokudan@chaos.social on Mastodon, you can use multiple lines in the string as follow (using two single quotes character):

networking.extraHosts = ''
1.2.3.4 foobar.perso.pw
1.2.3.5 foo.perso.pw
'';

The previous pieces of configuration will associate "foobar.perso.pw" to IP 1.2.3.4 and "foo.perso.pw" to IP 1.2.3.5.

Now, I need to rebuild my system configuration and use it, this can be done with the command nixos-rebuild switch as root.