Is this the most elegant use of an assert?

I set up a remote Borg backup, following the official documentation. On of the attributes refers to a path of a private key. I wanted to make sure that the backup does not fail silently and therefore added an assert to verify the existence of the file.

Since I am very new to nix, I am not sure if I implemented the most elegant expression. The original expression is

environment = { BORG_RSH = "ssh -i /run/keys/id_ed25519_my_borg_repo"; };

which I changed to

environment.BORG_RSH =
    private_key_path = "/run/keys/id_ed25519_my_borg_repo";
    "ssh -i ${assert builtins.pathExists private_key_path; private_key_path}";

Any suggestions to improve this?

I tend to avoid assert’s because they don’t have a nice error message, but since this is just personal code it doesn’t really matter.

Also generally this solution doesn’t work, because it’s not necessarily the case that the machine where you evaluate the configuration (that’s where the builtins.pathExists runs) is the same as the machine you’re deploying to (see the --target-host option in man nixos-rebuild). But again, since this is your personal config, you’ll know that that’s the case, so it seems fine to me :slight_smile:


Thank you for the explanation. How would you solve this problem of wanting to avoid the backup service to startup although a required file is missing? Maybe I am approaching this from the wrong angle. I considered that this might be a “bug” in the nix module that creates this service, because it does not verify the files existence itself.

I’d say it’s fairly standard for the service to fail at runtime in such a case. There’s ways to get failing services to send you emails, which might be nice to catch this somewhat reliably.

1 Like