Howto: sudo based keybinding to make ThinkPad fans spin up

ThinkPad laptops support spinning the fans to the maximum speed by running:

sudo -s
echo 'level disengaged' > /proc/acpi/ibm/fan  # spins up fan
echo 'level auto'       > /proc/acpi/ibm/fan  # back to normal

disengaged mode can help against downclocking due to overheating.

This requires root as shown, but I wanted to have a keybinding that does it without prompting for a password.

Here is my NixOS config for that (replace niklas by your user):

  # ThinkPad fan control without `sudo`

  # Putting these scripts into `systemPackages` links them into `/run/current-system/sw/bin`
  # with a distinct name, which allows us to create sudoers entries for them.
  environment.systemPackages = [
    (pkgs.writeScriptBin "fanspeed-disengaged" "echo 'level disengaged' > /proc/acpi/ibm/fan")
    (pkgs.writeScriptBin "fanspeed-auto"       "echo 'level auto'       > /proc/acpi/ibm/fan")
  # From:
  # *
  # Note: Using `extraConfig` instead of `extraRules` due to bug
  security.sudo.extraConfig = ''
    ${} ALL = (root) NOPASSWD: /run/current-system/sw/bin/fanspeed-disengaged
    ${} ALL = (root) NOPASSWD: /run/current-system/sw/bin/fanspeed-auto

Now you can run sudo fanspeed-disengaged and it won’t ask for a password.

You can bind that to a keybinding in your window manager, for example for me in i3:

# Fan control on the Thinkpad
# Commands provided by NixOS, requires `sudoers` entry like:
#     security.sudo.extraConfig = ''
#       ${} ALL = (root) NOPASSWD: /run/current-system/sw/bin/fanspeed-disengaged
#       ${} ALL = (root) NOPASSWD: /run/current-system/sw/bin/fanspeed-auto
#     '';
# Prior == PageUp, Next == PageDown
bindsym $mod+Prior exec sudo fanspeed-disengaged
bindsym $mod+Next exec sudo fanspeed-auto

Now I can press CapsLock+PgUp to spin up the fan (CapsLock is my $mod key).