Skip to content

Instantly share code, notes, and snippets.

@joachifm
Created March 7, 2015 16:58
Show Gist options
  • Save joachifm/3b875c68550686a4cd71 to your computer and use it in GitHub Desktop.
Save joachifm/3b875c68550686a4cd71 to your computer and use it in GitHub Desktop.
Automount LUKS encrypted external drives on NixOS
## A hack for automounting LUKS encrypted external drives.
##
## Parameters:
##
## devAttrs - set of sysfs attributes, e.g., { attr1 = value1; attr2 = value2; }
## devName - name of stable device node allocated by udev
## keyFile - absolute path to LUKS container key file
## mountPoint - file system mount point
## fsType - file system type
## fsLabel - file system label
## fsOptions - file system options
{
pkgs ? import <nixpkgs>{}
, lib ? pkgs.lib
, devAttrs
, devName
, keyFile
, mountPoint
, fsType
, fsLabel
, fsOptions ? ""
}:
let
escapeSystemdPath = s:
lib.replaceChars ["/" "-" " "] ["-" "\\x2d" "\\x20"]
(if lib.hasPrefix "/" s then lib.substring 1 (lib.stringLength s) s else s);
mountPoint' = escapeSystemdPath mountPoint;
blkDev = "/dev/${devName}";
blkDev' = escapeSystemdPath blkDev;
luksName = "${devName}_luks";
luksDev = "/dev/mapper/${luksName}";
formatUdevAttrs = attrs: lib.concatStringsSep "," (lib.mapAttrsToList (name: value: ''ATTRS{${name}}=="${value}"'') attrs);
in
{
systemd.services."${mountPoint'}-luks" = {
requiredBy = [ "${mountPoint'}.mount" ];
before = [ "${mountPoint'}.mount" ];
unitConfig = {
ConditionPathIsMountPoint = "${mountPoint}";
ConditionPathExists = "${keyFile}";
RequiresMountsFor = "${dirOf keyFile}";
};
serviceConfig = {
Type = "oneshot";
RemainAfterExit = "true";
ExecStart = ''${pkgs.cryptsetup}/bin/cryptsetup open "${blkDev}" "${luksName}" -d "${keyFile}"'';
ExecStop = ''${pkgs.cryptsetup}/bin/cryptsetup close "${luksName}"'';
};
};
fileSystems."${mountPoint}" = {
label = fsLabel;
fsType = fsType;
options = "defaults,${fsOptions},noauto,nofail,x-systemd.automount";
};
services.udev.extraRules = ''
SUBSYSTEMS=="scsi",\
KERNEL=="sd?[0-9]",\
${formatUdevAttrs devAttrs},\
SYMLINK+="usbhd%n ${devName}"
'';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment