Module option to add a package

In my NixOS configuration, I have a module packages.nix that defines environment.systemPackages. There’s a basic set of packages included on all of my machines. But I want an option to add some packages to the set for a particular machine.

Here’s packages.nix:

{ config, pkgs, options, inputs, ... }:

with pkgs;
{

  options = {
    extraPackages = lib.mkOption {
  	  type = lib.types.listOf lib.types.package;
  default = [ ];
    };
  };

  config =
    let
      extra = config.extraPackages;
    in
    {
      environment.systemPackages = extra ++ [
    . . . LIST OF PACKAGES HERE . . .
      ];
    }; # config
}

However, when I try to use the option in flake.nix, I have a problem:

nixosConfigurations = {

  wombat11k = let hostnameNew = "wombat11k"; in nixpkgs.lib.nixosSystem {
    specialArgs = {
      inherit inputs;
    };
    modules =
      [
    . . .
        ./packages.nix { extraPackages = [ kodi ]; }
      ];
  }; # wombat11k

. . . 
}

I get the message error: undefined variable 'kodi'. I’ve tried nixpkgs.kodi, pkgs.kodi and nixpkgs.lib.pkgs.kodi, but they don’t work either. What’s the magic incantation?

There is no need to write extraPackages. Just use another module which adds packages to environment.systemPackages, modules would be merged so that packages from each list would be included.

nixpkgs.legacyPackages.${system}.kodi

or better: ({pkgs, ...}: {extraPackages = [pkgs.kodi];})

Thanks, this helped me too. I had the same confusion about where pkgs comes from, and the extra module idea is much simpler than the option I was trying to write.

Sometimes it helps to understand how the implementation works. If that’s useful to you, it’s enough to know that the systemPackages option is of the listOf option type which per the manual merges multiple definitions using list concatenation. Indeed the way multiple definitions are merged across multiple modules depends on the option type.

In practice this means you can define the systemPackages any number of times and all the packages set in there will be accumulated in the final configuration.