NixOs Snippets

Build a Hugo website as part of configuration.nix

To deploy a Hugo website like this one, I could copy the generated file to my server by hand every time I make changes. But you can also build the website as part of the server’s configuration.nix.

To do that, in the Hugo website source directory (nielsegberts.nl/ in this case) I’ve created a default.nix file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{ pkgs ? import <nixpkgs> {} }:

pkgs.stdenv.mkDerivation rec {
    name = "hugo-nielsegberts.nl";
    version = "0.1";
    src = ./.;

    buildInputs = [pkgs.hugo];
    dontConfigure = true;

    # Copy source into working directory and 
    buildPhase = ''
        cp -r $src/* .
        # I need to specify the config because only more recent builds of hugo
        # look for a file named hugo.toml.
        ${pkgs.hugo}/bin/hugo --config hugo.toml
    '';

    installPhase = ''
        mkdir -p $out
        cp -r public/* $out/
    '';
}

And then in the services.nginx section of the configuration.nix, instead of providing a plain path we provide the package above. This snippet assumes the nielsegberts.nl is next to the configuration.nix of the server.

1
2
3
4
5
6
7
services.nginx = {
    enable = true;

    virtualHosts."nielsegberts.nl" = {
        root = pkgs.callPackage ./nielsegberts.nl { };
    };
};