β importing hosts in NixOS
π― Objective
To add additional hosts in NixOS, itβs as simple as adding the following configuration:
{
networking.extraHosts = ''
${builtins.readFile ./hosts/hosts-work}
'';
}
However, I do not want to make my hosts public, so I used sops-nix where the secrets are stored in another git repository.
π£ Steps
β Create the hosts file with sops
# By default, if not setting the env variable `SOPS_AGE_KEY_FILE`, sops will look
# at the file ~/.config/sops/age/keys.txt.
SOPS_AGE_KEY_FILE=~/.config/sops/age/l-lin.age sops sops/hosts.yaml
with the content:
work-hosts: |
127.0.0.1 work.localhost
β Install sops-nix at system level
First, I need to install sops-nix at system level:
#
# Simple and flexible tool for managing secrets.
# src:
# - https://github.com/getsops/sops
# - https://github.com/Mic92/sops-nix
#
{ inputs, ... }: {
# Install sops-nix.
imports = with inputs; [ sops-nix.nixosModules.sops ];
}
β Add the private repository as flake input
In flake.nix
:
{
inputs = {
# ...
secrets = {
url = "git+ssh://git@github.com/l-lin/secrets.git?shallow=1";
flake = false;
};
};
}
If you need to update this flake
input, run the command:
nix flake lock --update-input secrets
This will update the flake.lock
with the latest git revision.
π§ Add the extra-hosts
Now add the extra-hosts:
{ config, secrets, ... }: {
sops.secrets.hosts-work.sopsFile = "${secrets}/sops/hosts.yaml";
networking = {
# ...
extraHosts = ''
${builtins.readFile config.sops.secrets.hosts-work.path}
'';
};
}
However, when updating the system, I got the following error:
$ nh os switch --hostname "nixos" --ask .
...
β error: access to absolute path '/run/secrets/hosts-work' is forbidden in pure evalβ¦
β£βββ
ββ β β Exited with 1 errors reported by nix at 09:23:23 after 9s
Error:
0: Command exited with status Exited(1)
Location:
src/commands.rs:151
According to this thread:
After studying the issue in more depth, i discovered that it was a misunderstanding on my part and that all subfolders do have to be in the same folder as the flake to keep it pure.
The secret file is located at /run/secrets/hosts-work
, which is not in the same path as my NixOSβ¦
Fail
I did not manage to import hosts in my
/etc/hosts
usingsops-nix
unfortunately. For now, I will only update the/etc/hosts
manually and not commit to my repositoryβ¦