Skip to content

Extra arguments

There will be a time when you want to pass extra arguments to your modules such as your own library or a set of packages. This is possible with by adding attributes to config._module.args.

Note

This mechanism is currently only documented in the module system code, and that documentation is incomplete and out of date.

In our options.nix file, we declare a greeting option that will take name and create a greeting using cowsay. But pkgs is not normally supplied automatically by the module system. We can fix that later in our eval.nix file.

options.nix
{
  pkgs,
  lib,
  config,
  ...
}: let
  cfg = config;
in {
  options = {
    name = lib.mkOption {
      type = lib.types.str;
    };
    greeting = lib.mkOption {
      type = lib.types.package;
    };
  };

  config = {
    greeting = let
      greet-name = pkgs.writeShellApplication {
        name = "greeting";
        runtimeInputs = [pkgs.cowsay];
        text = ''
          cowsay Hello ${cfg.name}!
        '';
      };
    in
      pkgs.runCommand
      "greeting-code-block"
      {}
      ''
        echo '```' > $out
        ${greet-name}/bin/greeting >> $out
        echo '```' >> $out
      '';
  };
}

In our config.nix we define our name per usual.

config.nix
{...}: {
  config = {
    name = "Boaty McBoatface";
  };
}

Setup an eval.nix to evaluate our modules and return the config.greeting attribute. However notice that we have included element in our modules list: ({...}: {config._module.args = {inherit pkgs;};}). This is where and how we provide a instance of nixpkgs to our modules.

eval.nix
{
  nixpkgs ?
    builtins.fetchTarball {
      url = "https://github.com/NixOS/nixpkgs/tarball/aa94fc78b0a49ed2a4a69b6f5082a1b286dd392d";
      sha256 = "1gkm7r07aqiyfgr32bzjmhvgsd543m2g3m43janmb6z1hz17ks1n";
    },
  pkgs ? import nixpkgs {},
}:
(
  pkgs.lib.evalModules {
    modules = [
      ./options.nix
      ./config.nix
      ({...}: {config._module.args = {inherit pkgs;};})
    ];
  }
)
.config
.greeting

Create a build.sh run script to build the eval.nix file.

build.sh
nix build -f eval.nix

And if we run the script (./build.sh), we have our greeting in result.

 _________________________ 
< Hello Boaty McBoatface! >
 ------------------------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||