How to turn home-manager into an option

I import home manager in my flake through nixosConfigurations.modules = [ ... home-manager.nixosModules.home-manager { ... } ];, how could I turn that into an option?

I’ve tried two things so far: using an if statement, in which case I get an error saying “unexpected if statement”. I’ve also tried using “lib.mkIf”, but I then get an error saying that this is not a module. Any suggestions or tips are highly appreciated!

I think effectively what you are trying to do amounts to a conditional module import, which isn’t possible AFAIK.

The config in NixOS is a merge of all of the NixOS modules, their options and their configs. The home-manager NixOS module is just one of those modules; it is not special. Therefore any option that could appear anywhere else can also appear in the home-manager NixOS module, and the entire merged config depends on all of the modules, including the NixOS home-manager module itself. It can’t be possible for the import of a given NixOS module to depend on the config merge, because the config merge is determined by the set of NixOS modules to import. It makes sense that this isn’t possible, as if it were, a module could contain an option that would prevent it from being imported, which doesn’t make any sense.

(As for why I am talking about imports specifically, as far as I understand it, setting modules in a nixosSystem is effectively the same as setting imports inside of a NixOS module. This may be a little confusing if you are like me and have/had trouble grokking exactly what things were modules and what were not. The shape of a NixOS module can vary a fair bit, which makes it confusing…)

Generally speaking, you don’t conditionally import modules, you just import everything and then flip options on and off. For home-manager I imagine doing a lib.mkIf over your entire home-manager config module (e.g. wherever you are setting home-manager.users) ought to do the trick. Unfortunately though, lacking a single home-manager.enable option does mean that you may not be able to actually fully disable every side-effect of home-manager. If that does happen to be true, it might make sense to actually add this upstream as an option.

If you don’t necessarily need the condition to depend on the config merge, e.g. you could do it at a higher level, like having some of your nixosConfiguration attributes importing home-manager and some not, then it might make sense to just formulate it that way.

I hope this helps. Sorry if it’s a bit confusing, I’m having a hard time writing this out concisely!

Thanks a lot, this has clarified to me that I was going about it wrong. I’ve implemented it instead by using mkIf within the home-manager.nixosModules.home-manager attrset.