cachix / devenv

Fast, Declarative, Reproducible, and Composable Developer Environments
https://devenv.sh
Apache License 2.0
3.47k stars 252 forks source link

How to start services in a flake? #1124

Closed shishkin closed 3 weeks ago

shishkin commented 3 weeks ago

I'm trying to setup a dev shell with a postgres service. I'm using flake-utils, but otherwise tried to follow the devenv flake guidance. I also have direnv, which has use flake . --impure line.

When direnv activates the shell there is no postgres running and devenv up complains that my flake doesn't provide devenv-up. What am I doing wrong?

Here is my flake:

{
    description = "Nix project configuration";

    inputs = {
        nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
        flake-utils.url = "github:numtide/flake-utils";
        devenv.url = "github:cachix/devenv";
    };

    outputs = { nixpkgs, flake-utils, devenv, ... }@inputs: flake-utils.lib.eachDefaultSystem (system:
        let
            pkgs = nixpkgs.legacyPackages.${system};
        in {
            devShells.default = devenv.lib.mkShell {
                inherit inputs pkgs;
                modules = [
                    ({ pkgs, ... }: {
                        services.postgres = {
                            enable = true;
                            package = pkgs.postgresql_16;
                            initialDatabases = [{ name = "postgres"; }];
                        };
                    })
                ];
            };
        }
    );
}
domenkozar commented 3 weeks ago

Please use flake template from the documentation

shishkin commented 3 weeks ago

To avoid cargo-culting, would you mind pointing out to the significant difference that I missed?

shishkin commented 3 weeks ago

Ok, I figured it out after blending the template with my setup. I just missed the devenv-up package. It was present in the template, but absent in the docs.

Here is a full working example in case anyone finds it useful:

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    flake-utils.url = "github:numtide/flake-utils";
    devenv.url = "github:cachix/devenv";
    devenv.inputs.nixpkgs.follows = "nixpkgs";
  };

  outputs =
    { self, nixpkgs, devenv, flake-utils, ... }@inputs:
    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = nixpkgs.legacyPackages.${system};
      in {
        packages = {
          devenv-up = self.devShells.${system}.default.config.procfileScript;
        };

        devShells.default = devenv.lib.mkShell {
          inherit inputs pkgs;
          modules = [{
            services.postgres = {
              enable = true;
              initialDatabases = [{ name = "postgres"; }];
            };
          }];
        };
      });
}