How to automatically update flakes

I want to check daily for new versions of flake, but upgrade them the next time I do nixos-rebuild. I did some looking up and didn’t find anything in particular. I could use systemd to run nix flake update daily.

system.autoUpgrade includes flake options.

Here’s my config

Edit: sorry, realized you actually asked about updating the flake and not the system. I run [this service] (nixos/hosts/office/services/nixos.nix at 38e6b7b410fe6fb3ecb8bada64a2efc88b3e6669 · firecat53/nixos · GitHub) on my desktop to update flake.lock. That gets propagated to the other machines with Syncthing. I know a lot of people keep flake.lock in version control, but I’ve found it works better for my use case to not track that since I don’t have hard requirements for pinning exact versions.

How could I use system.autoUpgrade to auto update the lock file though?

That’s why I edited my comment to show a flake-update service. It’s two separate operations.

Could I do both, autoupgrade and update it?

You have to update the lock file first and then upgrade. That’s just the way flakes work. Notice in the service for nixos-upgrade.service that it is required to run after the flake-update service.

Edit: I came back to this and have been checking this every daily for the past few days, both the last modified time on flake.lock and sudo systemctl status nixos-upgrade, to ensure this configuration works:

      systemd.services = {
        flake-update = {
          description = "Update flake inputs";
          unitConfig = {
            StartLimitIntervalSec = 300;
            StartLimitBurst = 5;
          };
          serviceConfig = {
            ExecStartPre = "${pkgs.networkmanager}/bin/nm-online";
            ExecStart = "${pkgs.nix}/bin/nix flake update --flake /home/user/.local/share/chezmoi";
            Restart = "on-failure";
            RestartSec = "30";
            Type = "oneshot";
            User = "user";
          };
          path = [
            pkgs.nix
            pkgs.git
            pkgs.host
            pkgs.networkmanager
          ];
        };
      };
    
      systemd.services.nixos-upgrade = {
        after = [ "flake-update.service" ];
        requires = [ "flake-update.service" ];
      };
    
      system.autoUpgrade = {
        enable = true;
        flags = [ "--print-build-logs" ];
        flake = "path:///home/user/.local/share/chezmoi";
      };
    
    # On my desktop its set to midnight, on other devices I set it to 1:00
    system.autoUpgrade.dates = "0:00";
2 Likes