Add a post abou usb automount in nixos

This commit is contained in:
Konstantin Nazarov 2023-08-15 22:21:29 +01:00
parent 29fb6aa1eb
commit 7d41626e4b
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22

View file

@ -0,0 +1,36 @@
X-Date: 2023-08-15T22:20:00Z
X-Note-Id: d96dfea4-6e36-4505-858c-3c0c0f7d565b
Subject: Auto-mount USB drives in NixOS
X-Slug: automount_usb_drives_in_nixos
One day I've purchased a simple MP3 player, which is recognized by the computer
as a USB drive when plugged. Since I use a tiling window manager, and not a desktop
environment, I don't have an easy way to access it from the file manager as you
would do in, say, Gnome. I don't even use file managers, and mostly operate in the
terminal.
So, I thought it would be cool if the MP3 player would be automatically mounted to
a specific place in the filesystem when plugged in. And the permissions would
be set correctly right away, so my default user would not need any additional action.
I did some research, but there turned out to be surprisingly little information on
how to do it. So, here you go.
```
services.udev.extraRules =
''ACTION=="add", SUBSYSTEMS=="usb", SUBSYSTEM=="block", '' +
''ENV{ID_FS_USAGE}=="filesystem", ENV{ID_SERIAL_SHORT}=="<your_device_id>>", '' +
''RUN{program}+="${pkgs.systemd}/bin/systemd-mount --owner <username> '' +
''--no-block --automount=yes --collect $devnode /path/to/mount/to"'';
```
In this line, you need to replace the `<your_device_id>`, `<username>` and `/path/to/mount/to`.
The `ID_SERIAL_SHORT` can be acquired by doing `udevadm info --query=all --name=/dev/<your_device> | grep ID_SERIAL_SHORT`.
This ID is based on the filesystem header, so unless you reformat the drive, it should stay the same.
What this thing does is it creates a udev rule that would trigger for your specific device id. It uses systemd-mount, because
this leads to clean interactions between system services (so you get fewer surprises).
There are many things you can do with this. You can do automated backups of important information for example,
or sync podcasts (which is what I intend to do).