Skip to main content

Conditional Modules

Make a module that does something based on configuration options.

Create a simple option that can be configured by setting customoption1=true.

Bonus Have a nested conditional statement that happens if option 2 is set inside of option 1.

 {config, pkgs, lib, ...}:

let
  option1 = config.customoptions.option1 ;
  option2 = config.customoptions.option2 ;
in
   with lib;
{

  options = {
    customoptions = {
      option1 = {
        enable = mkOption {
         default = false;
         type = with types; bool;
         description = ''
           Option 1 description
         '';
        };
      };

      option2 = {
        enable = mkOption {
        default = false;
        type = with types; bool;
        description = ''
          Option 2 description
        '';
        };
      };
    };
  };

   config = mkIf option1.enable {
     environment.etc."sample".text =
      if config.customoptions.option2.enable
      then "option2 enabled"
      else "option1 enabled";
   };
}

Using MkMerge

{config, lib, pkgs, ...}:

let
  option1 = config.customoptions.option1;
  option1 = config.customoptions.option2;
in
  with lib;
{
  
  config =lib.mkMerge [
    {
      environment = {
        etc = lib.mkMerge [
          (lib.mkIf (option1.enable && option2.enable) {
            output.txt = {
                text = ''Both options are enabled'';
            };
          })

          (lib.mkIf (option1.enable && !option2.enable) {
            output.txt = {
                text = ''Only Option 1 enabled'';
            };
          })

          (lib.mkIf (option1.enable) {
            output-different.txt = {
                text = ''Another way of only Option 1 enabled'';
            };
          })
        ];
      };
    }
  ];
}