Way to fail rebuild when home-manager activation fails?

I have home-manager set as a NixOS module, this means running nixos-rebuild switch --sudo additionally activates home-manager services for each user

The issue being: When home-manager activation fails, the switch still happens !
Is there a way to make it so a failing activation also stops the switch ?

Confirmed by running nixos-rebuild switch --sudo, having HM fail, and then havind a new line in nixos-rebuild list-generation, plus this is also hinted at by:

warning: the following units failed: home-manager-qube.service

(since it would be an error otherwise)

These might be helpful reading:

nixos-rebuild page on the wiki
What happens during a system switch?

One important bit:

If the action is switch or boot, the bootloader is updated first so the
configuration will be the next one to boot.

So for a single nixos-rebuild boot/switch command, you’ll always get the new boot entry before knowing whether HM is all green.

One approach might be to (1) run nixos-rebuild test which activates the new system without changing the boot stuff. You get a temporary system profile, not a new numbered generation. If everything looks good, (2) run nixos-rebuild switch/boot as normal. If that’s too much typing, you could make your own aliases, or a script that does step 1 then pauses and waits for you to check and hit enter before step 2, gates the switch on systemctl --failed, etc.

Oh I see, of course

I don’t mind the boot entry as much, is there a way to make the switch throw an error code ?
boot couldn’t as you explained, but switch and test should be able to

Not out of the box as far as I know. A small wrapper checking systemctl --failed (or systemctl status on specific units you care about) after the switch is the most direct way to get there that I’m aware of.

Edit: Wait, there’s one thing. You can customize activationScripts if you need to. Same basic method as the wrapper above, except a nonzero exit code from the activation script itself I believe will get a nonzero out of nixos-rebuild. Those are also run on boot, so don’t go too crazy with them.

Oh nice, I think I’ll try that !

I’ll mark solved for now, and change in case it doesn’t work