Search code examples
nixnixos

How do I create a file in the nix store?


I'd like to define/manage a config file within a nix file and have it end up in the nix store, how can I do this?

Currently I'm managing this (outside of the nix store) manually by having the file within a path like ~/example/config.json, and used like the below:

  systemd.services = {
   example = {
      description = "abcxyz";
      serviceConfig = {
        WorkingDirectory = "%h/example/";
        Type      = "simple";
        ExecStart = "${example-pkg}/bin/app -c config.json";
        Restart   = "always";
        RestartSec   = 60;
      };
      wantedBy = [ "default.target" ];
    };

For example Nixos defines a postgresql service that has a config file located at /nix/store/pcp1r7f8mylwvri381an01r64knj1wwb-postgresql.conf/postgresql.conf - how could I replicate this functionality in my own service above?

Taking a look at https://github.com/NixOS/nixpkgs/blob/226ff16bd6fbe6d47e714379eeba8598cd61a90a/nixos/modules/services/databases/postgresql.nix#L21

configFile = pkgs.writeTextDir "postgresql.conf" (concatStringsSep "\n" (mapAttrsToList (n: v: "${n} = ${toStr v}") cfg.settings));

It's not clear to me what configFile is? Will it be the path to the postgresql.conf file?

Either way pkgs.writeTextDir "config.ini" seems to create a directory instead, should I be using pkgs.writeText instead?


Solution

  • The above seems to work:

      configFile = pkgs.writeText "config.json" 
        ''
        example config file bla bla
        '';
    

    And then you can use configFile via string interpolation:

    ExecStart = "${example-pkg}/bin/app -c ${configFile}";