Category: nix

  • Managing secrets in Nix using Agenix

    If tomorrow my laptop were to go in flames, I would lose two things. First I would lose my data, and this is what backups are for. The second thing I would lose is my configuration (software installed, network setup, …). Nix offers a way to preserve this (assuming the configuration is replicated externally like GitHub).

    But storing one’s configuration is Nix comes with challenges. One of those challenges is how to handle secrets. Some parts of the configuration is tied to secrets : passwords, keys, API tokens, … . The question is how to manage this. Usually it requires some form of cryptography.

    How I store my nix configuration

    Before I explain Agenix, I think it is worth to explain how I manage my Nix configuration on the various machines I have installed Nix. This is because Agenix integrates to my nix configuration, and Agenix makes more sense in context.

    There is the file layout of my Nix configuration over at (GitHub)[https://github.com/mparusinski/nix-config/]

    .
    ├── build.sh
    ├── flake.lock
    ├── flake.nix
    ├── modules
    │   ├── nixos
    │   │   ├── users.nix 
    │   │   ├── ...
    │   │   └── gc.nix
    │   └── home-manager
    │       ├── git.nix
    │       ├── ...
    │       └── zsh.nix
    └── hosts
        ├── dell-precision-7530
        │   ├── configuration.nix
        │   ├── hardware-configuration.nix
        │   └── home.nix
        └── wsl1
            ├── configuration.nix
            └── home.nix
    
    

    There are two parts each divided into two sub-parts : * The build system build on top of Nix and Flakes * flake.nix and flake.lock describe how to build a nix configuration on a given system. * build.sh which launches the appropriate Nix build command for the underlying system. * Nix modules which defines the system configuration * modules defines reusable configuration code across various systems * hosts defines configuration for given systems.

    Naively secrets (passwords, keys, API tokens, …) would be stored in plain text somewhere in the files mentioned here.

    Agenix explained

    To include secrets safely in a Git repository storing configuration there are multiple options. A common choice to externalize secrets. Essentially storing them not in Git. That could be simple files one has to place manually, key vaults, etc. But in that case you can’t simply replicate configuration unless you maintain those secrets. Another choice is to encrypt the secrets before hand, and, it has to be said, making sure the encryption key does not end up in Git.

    Agenix offers a way to include those secrets encrypted in Git. Furthermore Agenix is aware of actors involved. By actors I mean the repository maintainer, i.e. you, the systems that will have to decrypt the secrets, …

    Agenix is build on top of age which is an encryption tool. Its particularity is Age encrypted secrets can have multiple recipients and can use SSH asymmetric encryption (a key for encryption, a key for decryption). Agenix uses age to make the secret decryptable by authorized actors : you and the systems (which have their own SSH keys) that need to access the secrets and no one else.

    To be used Agenix needs to be installed to encrypt secrets but you also need to specify the nix configuration to setup agenix (so it can manage secrets) which amount of having it installed, the secrets specified and when to use them.

    Managing secrets

    The first step is to install Nix. In my case I am using flakes so I followed the steps from install guide for flakes.

    So more details about using flakes for your NixOS configuration see this link If you want to pass agenix to your configuration module file (usually named configuration.nix) you need to specify the specialArgs = { inherit inputs; } option when calling nixpkgs.lib.nixosSystem. To check if agenix is correctly installed run agenix -h.

    Now that agenix is installed the next step is to setup secrets. Inside your nix configuration folder do the following

    mkdir secrets
    cd secrets
    touch secrets.nix

    This means that the secrets.nix file will be version controlled. And start editing the secrets.nix file.

    let
      # SSH public keys of the users who will be adding secrets through agenix
      john = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJCizmOo5KevfHd6pqwxVjgvVYWv4Az5TbAclvuhF2AC";
      users = [ john ];
    
      # SSH public keys of the systems who will need to access the secrets
      webserver = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDA1+TbC/tXsVAKUjSzipoC0ibOgSWuNvzVdb8Xxwi0T";
      systems = [ webserver ];
    in
      {
        # Specify for each secret who has access to it
        "apikey.age".publicKeys = users ++ systems;
      }

    Once this is done you can create the secret files. In the above example that would agenix -e apikey.age. This file contains the encrypted secret to be used.

    Once you have done you will need to specify the secrets twice in the configuration nix files: once to declare the secret with the location of the age encrypted file, the second time to link the secret to some configuration item.

    {
      # configuration.nix
      # ...
      age.secrets.apikey.file = relativepathto/secrets/apikey.age;
      # ...
      # some service requiring the above secret
      services.special.config.adminFile = config.age.secrets.apikey.path;
    }

    Limitations

    From my experience sometimes Agenix does not always work smoothly with Nix. For instance in one case the nix build system would invalidate a prometheus configuration because the Agenix path would not exist yet. This had to with the prometheus Nix module validating the generate configuration yaml (see here).

  • Managing databases users using nix

    Recently I had the following challenge: manage database (robotic) users using nix. More specifically I wanted to declare a list of MariaDB/MySQL users, alongside passwords, and permissions using nix. And while nix has some options for this (e.g. services.mysql.ensureUsers.*.name). Some aspects can’t be declared with nix options like the credentials or its permissions for given databases.

    There is a way to solve this using nix using three steps: 1. Declaring the user configuration in an object 2. Creating nix packaged scripts that will apply a configuration to the database 3. Creating a systemd unit that runs the previous scripts when appropriate

    In this article I will go into details on how this is done. Note: although I focus on MySQL/MariaDB, the underlying principles can be applied for PostgreSQL, Redis, …

    Declaring the user configuration

    The first step is to encapsulate the information required for configuring a user in a nix object (key-value dictionary). In my case it looks like this

    dbUsecaseConfig = {
      database = "usecase_db";
      passwordFile = config.age.secrets.usecasePass.path;
      username = "usecase_username";
      hostname = "usecase_hostname";
    };

    Should be self explanatory. Note passwordFile is a path to a file, here I use agenix to manage secrets, which decrypts the password file with adequate permissions to prevent leaks (see article about agenix).

    Set up script to apply configuration

    The second step is to create a script that applies the configuration. This is done using pkgs.writeShellScript which generates a shell script and stores it as nix component (under /nix/store/).

    The syntax of the function

    writeShellScript "file-name"
      ''
      Content of the file
      '';

    The file name here is not very important. The content of the script, however, is. To make this modular, I use a function that takes a configuration as input and produces a corresponding shell script:

    applyMySQLConf = 
      {
        database,
        passwordFile,
        username,
        hostname
      }:
      pkgs.writeShellScript "applyMySQLConf"
        ''
          PASSWORD=$(cat ${passwordFile})
          ${pkgs.mariadb}/bin/mysql -u root -e "GRANT ALL PRIVILEGES ON ${database}.* TO '${username}'@'${hostname}' IDENTIFIED BY '$PASSWORD';"
        '';

    The details will depends on the use case. For instance for a PostgreSQL database the actual commands used in the script will change.

    To generate a script for a given configuration will look this:

    dbUsecaseConfig = {
      database = "usecase_db";
      passwordFile = config.age.secrets.usecasePass.path;
      username = "usecase_username";
      hostname = "usecase_hostname";
    };
    usecaseConfScript = applyMySQLConf dbUsecaseConfig;

    Automatically apply the configuration using systemd

    Now, we have a script which applies a configuration, but nothing actually runs the script. This is solved by using systemd services :

    systemd.services.apply-mysql-conf = {
      description = "Apply MySQL configurations";
      wants = [ "mysql.service" ];
      wantedBy = [ "multi-user.target" ];
      serviceConfig = {
        PremissionsStartOnly = true;
        RemainAfterExit = true;
        ExecStart = ''
          ${usecaseConfScript}
          ...
        '';
      };
    };

    I personally use one systemd service to apply all configurations for the database. You may prefer using multiple systemd unit files.

    Creating a Nix module

    It is good practice to create NixOS modules as it allows the code to be reusable and better organised.

    A NixOS module is created by adding path/to/module.nix file.

    {
      lib,
      config,
      pkgs,
      ...
    }:
    {
      # Content of the module
    }

    More specifically the module will define a NixOS option called mysqlInitialConfiguration so it can be used in the configuration.nix:

    {
      lib,
      config,
      pkgs,
      ...
    }:
    {
      options.mysqlInitialConfiguration = {
        enable = lib.mkEnableOption "Activate initial MySQL configuration";
        configurations = lib.mkOption = {
          default = [ ];
          description = ''
            List of initial MySQL configurations
            For instance :
            [
              {
                database = "usecase_db";
                passwordFile = config.age.secrets.usecasePass.path;
                username = "usecase_username";
                hostname = "usecase_hostname";
              }
            ]
          '';
        };
      };
    }

    Now this defines the NixOS option but not what happens when it is enabled and configured. To do so we need to add the config part of the option which applies a configuration based on option.

    {
      lib,
      config,
      pkgs,
      ...
    }:
    {
      options.mysqlInitialConfiguration = {
        enable = lib.mkEnableOption "Activate initial MySQL configuration";
        configurations = lib.mkOption = {
          default = [ ];
          description = ''
            List of initial MySQL configurations
            For instance :
            [
              {
                database = "usecase_db";
                passwordFile = config.age.secrets.usecasePass.path;
                username = "usecase_username";
                hostname = "usecase_hostname";
              }
            ]
          '';
        };
      };
    
      config = lib.mkIf config.mysqlInitialConfiguration {
        # Actual configuration
      };
    }

    Now we add the actual configuration (systemd files, scripts, …) and for practical reasons use the let ... in ... nix clause.

    {
      lib,
      config,
      pkgs,
      ...
    }:
    let
      applyMySQLConf =
        {
          database,
          passwordFile,
          username,
          hostname,
        }:
        pkgs.writeShellScript "applyMySQLConf" ''
          PASSWORD=$(cat ${passwordFile})
          ${pkgs.mariadb}/bin/mysql -u root -e "GRANT ALL PRIVILEGES ON ${database}.* TO '${username}'@'${hostname}' IDENTIFIED BY '$PASSWORD';"
        '';
    
      # Function taking a list as input and returns a string
      genSystemdScript = list: lib.strings.concatStrings (map (conf: applyMySQLConf conf + "\n") list);
      systemdScript = pkgs.writeShellScript "mysqlInitialConfiguration" ''
        ${genSystemdScript cfg.configurations}
      '';
    
      cfg = config.mysqlInitialConfiguration;
    in
    {
      options.mysqlInitialConfiguration = {
        # ...
      };
    
      config = lib.mkIf config.mysqlInitialConfiguration {
        systemd.services.mysqlInitialConfiguration = {
          description = "Initial MySQL configuration";
          wants = [ "mysql.service" ];
          wantedBy = [ "multi-user.target" ];
          serviceConfig = {
            PermissionsStartOnly = true;
            RemainAfterExit = true;
            ExecStart = "${systemdScript}";
          };
        };
      };
    }

    Note that config.mysqlInitialConfiguration is replaced with cfg in the config part.

    Now the new option can be used in the configuration.nix file as so:

    {
      # ...
    }:
    {
      # ...
      imports = [
        # ...
        ./path/to/mysql/module.nix
        # ...
      ];
      # ...
      mysqlInitialConfiguration.enable = true;
      mysqlInitialConfiguration.configurations = [
        {
          database = "usecase_db";
          passwordFile = config.age.secrets.usecasePass.path;
          username = "usecase_username";
          hostname = "usecase_hostname";
        }
      ];
    }

    Summary

    In this article I show to apply MySQL user configuration automatically using Nix and put all of this in a module.

  • Publishing a pelican website using nix

    This website is statically generated using pelican and development on the website is done via nix flakes. Here is how :

    Overview

    I use pelican to publish this website. Pelican is a python based command line tool to generate a static website. Pelican requires writing the articles in reStructuredText or Markdown and placing these files in a folder which I call content. To generate the website I simply run a command

    pelican -r content -o output -s pelicanconf.py

    I will not cover the details on how to install Pelican. In the above command I specify the source folder content, the output destination folder and finally a configuration file called pelicanconf.py that contain various website information like the name of website, the locale or the theming.

    While pelican is simple, it still requires a lot of small steps every time you want to publish an article. Which is why I use nix to automate as much as possible to leave as little friction.

    I will explain how I use Nix flakes to manage dependencies, build the website and run it locally. I will leave publishing for possible future article.

    Creating a development environment (nix-shell)

    The purpose of a nix shell is to have a shell environment where all the tooling is installed and one can develop various helper scripts (e.g. script to run the website locally).

    First I create the flake.nix file:

    {
        description = "Simple blog project";
        inputs = {
            nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
        }
        outputs = { self, nixpkgs }: let
            system = "x86_64-linux";
            pkgs = import nixpkgs { inherit system; }
            deps = with pkgs; [
                (python3.withPackages (ps: [ ps.pelican ps.markdown ]))
            ];
        in {
            devShells.${system} = pkgs.mkShell {
                buildInputs = deps;
            };
        };
    }

    Basically this tells how to make a shell environment with pelican installed and markdown support. It can be invoked like this:

    nix develop
    pelican -r ./content -o ./dev-output -s pelicanconf.py

    However, this may not work for everyone because I use an external theme.

    When it is not a flake project (i.e the project root does not have a flake.nix) we turn the external dependency into a derivation from scratch. This can be done using fetchFromGitHub:

    {
        description = "Simple blog project";
        inputs = {
            nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
        }
        outputs = { self, nixpkgs }: let
            system = "x86_64-linux";
            pkgs = import nixpkgs { inherit system; }
            pelican-flex-theme = pkgs.fetchFromGitHub {
                owner = "alexandrevicenzi";
                repo = "Flex";
                rev = "master";
                sha256 = "sha256-I/WEqFMZbnJvX4NMeqB+o9LzD4im1BwOwgaqqDqbL2s=";
            };
            deps = with pkgs; [
                pelican-flex-theme
                (python3.withPackages (ps: [ ps.pelican ps.markdown ]))
            ];
        in {
            devShells.${system} = pkgs.mkShell {
                buildInputs = deps;
                shellHook = ''
                  export PELICAN_THEME=${pelican-flex-theme}
                '';
            };
        };
    }
    
    

    Now after running nix develop I can access the path to the theme via the environment variable PELICAN_THEME (which happens to be what I use in pelicanconf.py).

    Building the website

    Next step is to implement the build step. This is done by specifying the packages.${system}.default output derivation. Now
    by building the website, I mean generating the static files, not running a local instance. Running the website locally will be explained later.

    {
        description = "Simple blog project";
        inputs = {
            nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
        }
        outputs = { self, nixpkgs }: let
            system = "x86_64-linux";
            pkgs = import nixpkgs { inherit system; }
            pelican-flex-theme = pkgs.fetchFromGitHub {
                owner = "alexandrevicenzi";
                repo = "Flex";
                rev = "master";
                sha256 = "sha256-I/WEqFMZbnJvX4NMeqB+o9LzD4im1BwOwgaqqDqbL2s=";
            };
            deps = with pkgs; [
                pelican-flex-theme
                (python3.withPackages (ps: [ ps.pelican ps.markdown ]))
            ];
        in {
            devShells.${system} = pkgs.mkShell {
                buildInputs = deps;
                shellHook = ''
                  export PELICAN_THEME=${pelican-flex-theme}
                '';
            };
            packages.${system}.default = pkgs.stdenv.mkDerivation {
                name = "my-website";
                src = ./.;
                nativeBuildInputs = deps;
                buildPhase = ''
                    export PELICAN_THEME=${pelican-flex-theme}
                    pelican content -o output -s pelicanconf.py
                '';
                installPhase = ''
                    mkdir -p $out
                    cp -r output/* $out
                '';
            };
        };
    }
    
    

    Just like a Makefile we specify how to build the project using the buildPhase and how to install using the installPhase; all of this within stdenv.mkDerivation.

    There is however one problem with this derivation. It fetches all the files instead of only the files it needs. To fix this I use gitignore.nix which filters the source folder using the .gitignore file.

    {
        description = "Simple blog project";
        inputs = {
            nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
            gitignore = {
                url = "github:hercules-ci/gitignore.nix";
                inputs.nixpkgs.follows = "nixpkgs";
            };
        }
        outputs = { self, nixpkgs, gitignore }: let
            # ... previous code omitted ...
            deps = with pkgs; [
                pelican-flex-theme
                (python3.withPackages (ps: [ ps.pelican ps.markdown ]))
            ];
            inherit (gitignore.lib) gitignoreSource;
        in {
            # ... previous code omitted ...
            packages.${system}.default = pkgs.stdenv.mkDerivation {
                name = "my-website";
                src = gitignoreSource ./.;
                nativeBuildInputs = deps;
                buildPhase = ''
                    export PELICAN_THEME=${pelican-flex-theme}
                    pelican content -o output -s pelicanconf.py
                '';
                installPhase = ''
                    mkdir -p $out
                    cp -r output/* $out
                '';
            };
        };
    }
    
    

    Now you can build the website by running the command

    nix build

    You can access the website in the result folder (which is a link to the created derivation in the nix store).

    Launching the website locally

    To run the locally we define an application in the Nix flake file. To run the website locally will be done in three steps : 1. Create a shell script to run the website (using nix of course) 2. Define an application in flake.nix 3. Make the shell script and the package a dependency of the application

    Here is how it is done:

    {
        # ... inputs ...
        outputs = { self, nixpkgs, gitignore }: let
            # ... previous code omitted ...
            deps = with pkgs; [
                pelican-flex-theme
                (python3.withPackages (ps: [ ps.pelican ps.markdown ]))
            ];
            inherit (gitignore.lib) gitignoreSource;
            static-website = pkgs.stdenv.mkDerivation {
                name = "my-website";
                src = gitignoreSource ./.;
                nativeBuildInputs = deps;
                buildPhase = ''
                    export PELICAN_THEME=${pelican-flex-theme}
                    pelican content -o output -s pelicanconf.py
                '';
                installPhase = ''
                    mkdir -p $out
                    cp -r output/* $out
                '';
            };
        in {
            # ... previous code omitted ...
            packages.${system}.default = static-website;
            apps.${system}.default = let
                serv = pkgs.writeShellApplication {
                    name = "serve";
                    runtimeInputs = [ static-website ] ++ deps;
                    text = ''
                        pelican --relative-urls -p 8080 -l ${static-website}
                    '';
                };
            in {
                type = "app";
                program =" ${serv}/bin/serve";
            }
        };
    }

    In the above code we refactor the code by moving the package definition into the static-website variable in the let ... in ... clause. We also create a sub-component as a shell application derivation called serv which simply run the pelican local server.

    To run the website locally simply do

    nix run

    Updating the website

    Now if you make changes to your website (e.g. add a new article markdown file) you may not see the changes after running nix run or nix build, the most likely reason for this is that flakes track the latest state of the git repository; meaning you may need to git add files for changes to be reflected.

    Summary

    In this article I show how to use Nix flakes to manage the development life-cycle of a statically generated website using pelican.

    Nix flakes are used to manage the development environment (like virtual environments in Python), build the website (like in make build) and run the website locally (like a docker run).