How do I set up a swap file?

NixOS 20.09
Linux Kernel 5.11.1

For those of you who are still having this problem, the following has worked well for me:

The proper way to create a Swap file on BTRFS is Btrfs - ArchWiki, so I set up a oneshot systemd service to create this file for me that is wanted by the NixOS swap-*.service defined in my hardware-configuration.nix file.

This will create the non-compressed, CoW disabled file in my /swap BTRFS subvolume. Then I leave the allocation and enabling of the swap file to NixOS in hardware-configuration.nix

configuration.nix

  systemd.services = {
    create-swapfile = {
      serviceConfig.Type = "oneshot";
      wantedBy = [ "swap-swapfile.swap" ];
      script = ''
        ${pkgs.coreutils}/bin/truncate -s 0 /swap/swapfile
        ${pkgs.e2fsprogs}/bin/chattr +C /swap/swapfile
        ${pkgs.btrfs-progs}/bin/btrfs property set /swap/swapfile compression none
      '';
    };
  };

hardware-configuration.nix

  fileSystems."/swap" = {
    device = "/dev/disk/by-uuid/545353bc-238b-4a5b-bb48-94832272e0b2";
    fsType = "btrfs";
    options = [ "subvol=swap" "compress=lzo" "noatime" ]; # Note these options effect the entire BTRFS filesystem and not just this volume, with the exception of `"subvol=swap"`, the other options are repeated in my other `fileSystem` mounts
  };

  swapDevices = [{
    device = "/swap/swapfile";
    size = (1024 * 16) + (1024 * 2); # RAM size + 2 GB
  }];

As you can see, my nixops deploy succeeds and upon verification the file is enabled and allocated according to my definition.

7 Likes