Auto-mount 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).