# Nix Notes
High-level Nix notes.
## Videos
2h, Comprehensive "What is Nix": https://youtu.be/6Le0IbPRzOE
28m, Containerization with Nix: https://youtu.be/5XY3K8DH55M
15m, Everything Everywhere all at Once: https://youtu.be/CwfKlX3rA6E
[Vimjoyer]
9m, Nix Language Explained: https://youtu.be/UgrwoAGSPOQ
9m, Impermanence Setup: https://youtu.be/YPKwkWtK7l0
7m, NixOS Secrets Management: https://youtu.be/G5f6GC7SnhU
## Links
Structured Learning: https://nixos.org/guides/nix-pills/
Discuss: https://discourse.nixos.org/
Awesome-List: https://github.com/nix-community/awesome-nix
Wiki: https://nixos.wiki/wiki
ISO from Nix: https://nix.dev/tutorials/nixos/building-bootable-iso-image
## RTFM
Once you've read and seen enough and want to get going, I recommend using the following repo as a template for your nix configuration files. `grep` for "FIXME" and "TODO" for lines that need your attention and input before rubuilding your os with `sudo nixos-rebuild switch --flake .#hostname`.
All of the provided config files have detailed comments regarding features and best practices.
Getting Started:
- Starter Configs: https://github.com/Misterio77/nix-starter-configs
Narrower focus, handy references as you build your OS:
Zero to Nix:
- https://zero-to-nix.com/start
NixOS with Flakes:
- https://nixos-and-flakes.thiscute.world/introduction/
How to Upgrade Packages:
- https://discourse.nixos.org/t/how-to-upgrade-packages/6151/9
Configure Docker:
- https://nixos.wiki/wiki/Docker
Configure Zsh:
- https://nixos.wiki/wiki/Zsh
Configure OpenVPN:
- https://nixos.wiki/wiki/OpenVPN
NixOS Options (also, don't sleep on the `man` pages):
- https://nixos.org/manual/nixos/stable/options.html
NixOS Modules:
- https://nixos.wiki/wiki/NixOS_modules
## Opinions
- [Writing Custom NixOS Modules](https://www.reddit.com/r/NixOS/comments/um1ohu/how_do_you_write_custom_nixos_modules/)
## Nomenclature
**derivations** – precise descriptions of how contents of existing files are used to derive new files.
## Why nix?
Couldn't say it better myself: https://github.com/hlissner/dotfiles#frequently-asked-questions
> Should I use NixOS?
> Short answer: no.
> Long answer: no really. Don't.
> Long long answer: I'm not kidding. Don't.
> Unsigned long long answer: Alright alright. Here's why not:
>
> Its learning curve is steep.
>
> You will trial and error your way to enlightenment, if you survive long enough.
>
> NixOS is unlike other Linux distros. Your issues will be unique and difficult to google.
>
> If the words "declarative", "generational", and "immutable" don't make you fully erect, you're considering NixOS for the wrong reasons.
>
> The overhead of managing a NixOS config will rarely pay for itself with fewer than 3 systems (perhaps another distro with nix on top would suit you better?).
>
> Official documentation for Nix(OS) is vast, but shallow.
>
> Unofficial resources and example configs are sparse and tend to be either too simple or too complex (or outdated).
>
> The Nix language is obtuse and its toolchain is unintuitive. This is made infinitely worse if you've never touched the shell or a functional language before, but you'll need to learn it to do even a fraction of what makes NixOS worth all the trouble.
>
> A decent grasp of Linux and its ecosystem is a must, if only to distinguish Nix(OS) issues from Linux (or upstream) issues -- as well as to debug them or report them to the correct authority (and coherently).
>
> If you need somebody else to tell you whether or not you need NixOS, you don't need NixOS.
>
> If none of this has deterred you, then you didn't need my advice in the first place. Stop procrastinating and try NixOS!
## What is Nix
- About 20MB program written in C++
- An OS
- A programming language
- A package manager
- A method of compiling software from source
### What is Nixpkgs
- NixOS/nixpkgs
- "Derivations"
- Builds from source, 90k+ reproducible recipes
["I installed a library but my compiler is not finding it. Why?"](https://nixos.wiki/wiki/FAQ#I_installed_a_library_but_my_compiler_is_not_finding_it._Why.3F)
### What is NixOS
- Built from Nix and Nixpkgs
- The result of running `nix build` on the Nix code you've written
- Completely declarative
### What are Flakes?
```
WARNING: Since contents of flake files are copied to the world-readable Nix store folder, do not put any unencrypted secrets in flake files.
```
Other users on your machine can see your secrets if you include them in your config.
https://www.tweag.io/blog/2020-05-25-flakes/
> A flake is simply a source tree (such as a Git repository) containing a file named flake.nix that provides a standardized interface to Nix artifacts such as packages or NixOS modules. Flakes can have dependencies on other flakes, with a “lock file” pinning those dependencies to exact revisions to ensure reproducible evaluation.
I'm thinking that `nix modules` are similar to `terraform` modules, and the `flake` is the implementation, or root module, of one or more modules.
## How do I Handle Secrets?
I'm going with `sops-nix`.
### Setup
`sops-nix` Example: https://github.com/Mic92/sops-nix#deploy-example
Blog on Usage: https://samleathers.com/posts/2022-02-11-my-new-network-and-sops.html
#### Generate Keys
`mkdir -p ~/.config/sops/age`
`nix shell nixpkgs#age -c age-keygen -o ~/.config/sops/age/keys.txt`
This will provide a public key. You can review your public key with:
`nix shell nixpkgs#age -c age-keygen -y ~/.config/sops/age/keys.txt`
Alternatively, you can use your ssh private key to generate the sops key, ensuring the same output should you need to re-generate the key.
`nix run nixpkgs#ssh-to-age -- -private-key -i ~/.ssh/private > /.config/sops/age/keys.txt`
#### .sops.yaml
Somewhere with your nix configs:
```
keys:
- &primary <your-public-key>
creation_rules:
- path_regex: secrets/secrets.yaml$
key_groups:
- age:
- *primary
```
#### secrets.yaml
`sops secrets/secrets.yaml`
This will open your default editor to a short template for the secrets file. Your sops `secrets.yaml` can be pushed with the rest of your config since it is encrypted at rest. Make sure you back up your keys.
```
hello: Welcome to SOPS! Edit this file as you please!
example_key: example_value
# Example comment
example_array:
- example_value1
- example_value2
example_number: 1234.56789
example_booleans:
- true
- false
```
Add a secret or two and save, and you'll find encrypted text when you `cat` the file.
I use VSCode as my default editor and hit a snag here, circumventing it entirely after attempting a couple of failed workarounds.
`vi` or `nano` work fine.
`EDITOR=vim sops secrets/secrets.yaml`
#### Referencing Secrets w/ Nix Configs [WIP]
I'm **[CURRENTLY]** trying, and failing, to use sops-nix for my nix-config secrets.
https://github.com/Mic92/sops-nix?tab=readme-ov-file#templates
Using the example `secrets.yaml` above, let's reference `example_key` in `configuration.nix`:
```
sops.secrets.example_key = {};
```
This makes our secret accessible at `/run/secrets/example_key`, owned by `root:root` and readable by the `keys` group.
I do not know how to or if you can (or should try to) reference the value of a given variable. I assumed the following would work, but this just points to the secret's filepath. This is fine when the service can read the secret from a file.
```
...
# sops config
sops.defaultSopsFile = ../../secrets/secrets.yaml;
sops.defaultSopsFormat = "yaml";
sops.age.keyFile = /home/amaddox/.config/sops/age/keys.txt;
sops.secrets = {
ovpn_pw = {};
};
...
# OpenVPN
services.openvpn.servers = {
figgVPN = {
config = ''config /etc/openvpn/client/client.conf '';
updateResolvConf = true;
autoStart = false;
authUserPass.password = config.sops.secrets."ovpn_pw".path;
authUserPass.username = "amaddox";
};
};
...
```
`authUserPass.password` is of type `string`. `authUserPass` is a `null` type that could take our file, I think. Docs say that the creds are put in the world-readable Nix store, though.
I thought that I might point this to `/run/secrets/ovpn_pw` instead. You can't do this with nix. That file hasn't been generated yet, though I expect it to exist once the system is rebuilt. I need to be able to reference the secret from within the project, so the original value was correct, `config.sops.secrets."ovpn_pw".path`.
I needed to update my `ovpn_pw` secret to include the username and update the key name:
```
ovpn_auth: |
amaddox D3finiT3ly-MyR3alP@ssw0rd!
```
This shit still doesn't work.
## Services
[There are a lot of services](https://search.nixos.org/options?channel=23.11&from=0&size=50&sort=relevance&type=packages&query=services) that can be enabled with just a few lines in your `configuration.nix`.
Looking at `openvpn`, above, I've [configured the options](https://search.nixos.org/options?channel=23.11&from=0&size=50&sort=alpha_asc&type=packages&query=services.openvpn) to my linking. I don't want the service to auto-start, since it will prompt me for my MFA during `nixos-rebuild switch` every time. I'd prefer to start/stop this myself. I could configure multiple VPN services but I have only one named "figgVPN", and Nix names this service, `openvpn-figgVPN.service`. If you don't know your service name, look it up with `systemctl list-unit-files | grep -i <service>`.
### Configure Custom Services
TODO: Notes on configuring a custom service
## Containerization
Example Dockerfile:
```dockerfile
FROM ubuntu:jammy
RUN apt-get -qq update \
&& apt-get -qq install -y --no-install-recommends \
nginx=1.18.0-6ubuntu14.3 I
&& rm -rf/var/lib/apt/lists/*
COPY html/index.html /var/www/html/index.html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
```
With Nix:
```
{
description = "OpenTechLab Docker Example";
inputs = {
nixpkgs. url = github:Nix0S/nixpkgs/nixos-22.11;
};
outputs = { self, nixpkgs }: {
packages. "x86_64-linux" =
let
pkgs = import nixpkgs { system = "x86_64-linux"; };
in
rec {
dockerImage =
pkgs.dockerTools.buildLayeredImage (let
nginxPort = "80";
nginxConf = pkgs.writeText "nginx.conf" ''
user nginx nginx;
daemon off;
events {}
http {
server {
listen ${nginxPort};
location / {
root ${./html};
}
}
}
'';
in rec {
name = "otl-nix-demo";
}
...
```
Yeah.. It's much longer, but your image will have 0 fat, and byte-for-byte you can reproduce this on any machine at any time.
## Handy Commands
`nix repl` is a command-line tool that comes with the Nix package manager. It allows you to interactively explore and evaluate Nix expressions, which are used in Nix configurations. With nix-repl, you can load Nix expressions and see their results in real-time, making it useful for debugging and developing Nix configurations. It provides a read-eval-print loop (REPL) environment where you can enter expressions and view the output, helping you understand how Nix expressions work. `Ctrl+D` to exit.
`nix-collect-garbage` is used to clean up the Nix store by identifying and removing unused or outdated items, thereby optimizing disk space usage.
`nix-shell -p <package1> <package2` to install packages found at search.nixos.org and drop you into an ephemeral shell with those tools. `--run` will run the command and exit when it has finished, so that you can use commands that aren't installed on your machine.
If you want to use "unfree" packages with `nix-env`, `nix-build`, or `nix-shell`; add the following to your `configuration.nix`:
```
mkdir -p ~/.config/nixpkgs && \
echo '{ allowUnfree = true; }' >> ~/.config/nixpkgs/config.nix
```
## Adding New Hardware
I believe the gist for adding new hardware is to plug in and run `nixos-generate-config` again to produce an updated `hardware-configuration.nix`.
#### HDD/SSD
I added a disk, and had to partition it before getting started, though I'm confident that Nix could probably handle this part as well. Regardless, here's the process:
```
nix-shell -p parted
# ID new disk
sudo parted -l | grep Error
# partition
sudo parted /dev/sda mklabel gpt
sudo parted -a opt /dev/sda mkpart primary ext4 0% 100%
# create filesystem
sudo mkfs.ext4 -L datapartition /dev/sda1
# snag uuid
sudo lsblk --fs
```
We want the UUID so that we can add it via the `fileSystems` property.
```
...
fileSystems."/media/data" = {
device = "/dev/disk/by-uuid/2b13d130-3b5f-4d9d-8bf6-44fs6f44e8ec";
fsType = "ext4";
};
...
```
I did create `/media/data` before adding this to the config, but I'm sure that Nix would have provisioned it had I not.
## Tips
Try this:
cd into the directory with your flake.nix
run `nix repl`
in `nix repl`, type ``:lf .`` (this will load flake.nix into the repl)
hit the <tab> key to see possible completions (you should see inputs in there)
type `inputs`. and press <tab> and you should see all your inputs
For example, I have the Hyprland flake as an input, so I can then type:
6. `inputs.hyprland.` and press <tab> to explore from there.
7. `:?` for help. `:q` to quit the repl
This ability to browse around the structure of my flake gave me a better understanding of how it's all laid out. You can also dig into nixosConfigurations to explore your system config, check current value of options etc.
Another cool thing you can do with the repl: nix repl '<nixpkgs>' will load nixpkgs directly. Press <tab> and you will see all the packages (well the last few). Start typing the name of an application and then press <tab> to find the package you are looking for. You can explore all the packages using dot notation to see their meta data etc.