From c2ffc91b08b3a0f48734b7eaf3e1a21980e2731c Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Tue, 13 Oct 2026 08:42:45 -0400 Subject: [PATCH 1/8] refactor: simplify training flake inputs and tooling --- flake.lock | 57 +++------------------------------------------------ flake.nix | 60 +++++++++++++++++++----------------------------------- 2 files changed, 24 insertions(+), 93 deletions(-) diff --git a/flake.lock b/flake.lock index 6b0124e..f4e8ec7 100644 --- a/flake.lock +++ b/flake.lock @@ -176,21 +176,6 @@ "type": "github" } }, - "mk-shell-bin": { - "locked": { - "lastModified": 1677004959, - "narHash": "sha256-/uEkr1UkJrh11vD02aqufCxtbF5YnhRTIKlx5kyvf+I=", - "owner": "rrbutani", - "repo": "nix-mk-shell-bin", - "rev": "ff5d8bd4d68a347be5042e2f16caee391cd75887", - "type": "github" - }, - "original": { - "owner": "rrbutani", - "repo": "nix-mk-shell-bin", - "type": "github" - } - }, "nix": { "inputs": { "flake-compat": [ @@ -231,26 +216,6 @@ "type": "github" } }, - "nix2container": { - "inputs": { - "nixpkgs": [ - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1790918497, - "narHash": "sha256-tHQzYcg3iAVhUE5dtRL5KweJXbcZ7UEQG/XFGsHtQsI=", - "owner": "nlewo", - "repo": "nix2container", - "rev": "4e83e6724dcb9eb1b3e855426fa4c8cd19f5ce5a", - "type": "github" - }, - "original": { - "owner": "nlewo", - "repo": "nix2container", - "type": "github" - } - }, "nixd": { "inputs": { "flake-parts": [ @@ -305,28 +270,10 @@ "type": "github" } }, - "nixpkgs_2": { - "locked": { - "lastModified": 1790149054, - "narHash": "sha256-FfjXg6mAzKQBCY+7V9keGWOXG4DV2Eym/qA987lFl8A=", - "owner": "nixos", - "repo": "nixpkgs", - "rev": "8825bebf6324e0579d012936eff73379af284b6d", - "type": "github" - }, - "original": { - "owner": "nixos", - "ref": "nixpkgs-unstable", - "repo": "nixpkgs", - "type": "github" - } - }, "root": { "inputs": { "devenv": "devenv", "flake-parts": "flake-parts_2", - "mk-shell-bin": "mk-shell-bin", - "nix2container": "nix2container", "nixpkgs": "nixpkgs", "treefmt-nix": "treefmt-nix_2" } @@ -376,7 +323,9 @@ }, "treefmt-nix_2": { "inputs": { - "nixpkgs": "nixpkgs_2" + "nixpkgs": [ + "nixpkgs" + ] }, "locked": { "lastModified": 1791490544, diff --git a/flake.nix b/flake.nix index 63924b2..c1438fb 100644 --- a/flake.nix +++ b/flake.nix @@ -11,14 +11,10 @@ flake-parts.url = "github:hercules-ci/flake-parts"; - treefmt-nix.url = "github:numtide/treefmt-nix"; - - nix2container = { - url = "github:nlewo/nix2container"; + treefmt-nix = { + url = "github:numtide/treefmt-nix"; inputs.nixpkgs.follows = "nixpkgs"; }; - - mk-shell-bin.url = "github:rrbutani/nix-mk-shell-bin"; }; outputs = @@ -35,30 +31,22 @@ ]; systems = nixpkgs.lib.systems.flakeExposed; - flake.nixosConfigurations = { - training-vm = nixpkgs.lib.nixosSystem { - system = "x86_64-linux"; - modules = [ ./nixos/training-vm.nix ]; - }; - training-image = nixpkgs.lib.nixosSystem { - system = "x86_64-linux"; - modules = [ - ./nixos/training-vm.nix - ./nixos/training-image.nix - ]; - }; - training-vm-aarch64 = nixpkgs.lib.nixosSystem { - system = "aarch64-linux"; - modules = [ ./nixos/training-vm.nix ]; - }; - training-image-aarch64 = nixpkgs.lib.nixosSystem { - system = "aarch64-linux"; - modules = [ - ./nixos/training-vm.nix - ./nixos/training-image.nix - ]; + flake.nixosConfigurations = + let + mkTrainingSystem = + system: extraModules: + nixpkgs.lib.nixosSystem { + inherit system; + modules = [ ./nixos/training-vm.nix ] ++ extraModules; + }; + vmModule = nixpkgs + "/nixos/modules/virtualisation/qemu-vm.nix"; + in + { + training-vm = mkTrainingSystem "x86_64-linux" [ vmModule ]; + training-image = mkTrainingSystem "x86_64-linux" [ ./nixos/training-image.nix ]; + training-vm-aarch64 = mkTrainingSystem "aarch64-linux" [ vmModule ]; + training-image-aarch64 = mkTrainingSystem "aarch64-linux" [ ./nixos/training-image.nix ]; }; - }; perSystem = { @@ -68,12 +56,6 @@ ... }: { - # This sets `pkgs` to a nixpkgs with allowUnfree option set. - _module.args.pkgs = import nixpkgs { - inherit system; - config.allowUnfree = true; - }; - packages = lib.optionalAttrs (system == "x86_64-linux") { qemu-image = self.nixosConfigurations.training-image.config.system.build.image; @@ -89,10 +71,10 @@ programs.nixfmt.enable = true; }; - # Native Nix devShells replacement + # Tool-only environment used by the image workflow. devShells = { # nix develop .#ci - ci = pkgs.mkShell { + ci = pkgs.mkShellNoCC { name = "ci-shell"; packages = [ pkgs.gnumake @@ -114,9 +96,9 @@ in if workingDirectory == "" then builtins.toString ./. else workingDirectory; - # OCI packaging is defined above; disable devenv's implicit shell - # containers so flake checks do not require unrelated container inputs. + # Disable implicit containers: repository tooling only needs a shell. containers = lib.mkForce { }; + stdenv = pkgs.stdenvNoCC; packages = with pkgs; [ bash From 51ea9b97d879e090b7fe9b14dc1f7bd3bab5a7a5 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Tue, 13 Oct 2026 10:11:35 -0400 Subject: [PATCH 2/8] feat: introduce flakes with buildable derivation exercises --- 00-getting-started/README.md | 55 +++++++++++++++++++ 00-getting-started/flake.lock | 24 ++++++++ 00-getting-started/flake.nix | 20 +++++++ 01-nix-language/README.md | 4 +- 02-nix-store/README.md | 14 +++++ 03-derivations/00-raw-derivation/README.md | 23 ++++++++ 03-derivations/00-raw-derivation/flake.lock | 24 ++++++++ 03-derivations/00-raw-derivation/flake.nix | 23 ++++++++ 03-derivations/00-raw-derivation/greeting.nix | 12 ++++ 03-derivations/01-gnu-hello/README.md | 40 ++++++++++++++ 03-derivations/01-gnu-hello/flake.lock | 24 ++++++++ 03-derivations/01-gnu-hello/flake.nix | 30 ++++++++++ 03-derivations/01-gnu-hello/hello.nix | 16 ++++++ 03-derivations/02-static-site/README.md | 25 +++++++++ 03-derivations/02-static-site/flake.lock | 24 ++++++++ 03-derivations/02-static-site/flake.nix | 28 ++++++++++ 03-derivations/02-static-site/render.jq | 1 + 03-derivations/02-static-site/site.json | 4 ++ 03-derivations/02-static-site/site.nix | 6 ++ 03-derivations/README.md | 20 +++++-- 03-derivations/debugging.md | 5 +- 03-derivations/derivations.md | 25 +++++---- README.md | 13 +++-- README.pt-br.md | 33 +++++++++++ 24 files changed, 471 insertions(+), 22 deletions(-) create mode 100644 00-getting-started/README.md create mode 100644 00-getting-started/flake.lock create mode 100644 00-getting-started/flake.nix create mode 100644 03-derivations/00-raw-derivation/README.md create mode 100644 03-derivations/00-raw-derivation/flake.lock create mode 100644 03-derivations/00-raw-derivation/flake.nix create mode 100644 03-derivations/00-raw-derivation/greeting.nix create mode 100644 03-derivations/01-gnu-hello/README.md create mode 100644 03-derivations/01-gnu-hello/flake.lock create mode 100644 03-derivations/01-gnu-hello/flake.nix create mode 100644 03-derivations/01-gnu-hello/hello.nix create mode 100644 03-derivations/02-static-site/README.md create mode 100644 03-derivations/02-static-site/flake.lock create mode 100644 03-derivations/02-static-site/flake.nix create mode 100644 03-derivations/02-static-site/render.jq create mode 100644 03-derivations/02-static-site/site.json create mode 100644 03-derivations/02-static-site/site.nix diff --git a/00-getting-started/README.md b/00-getting-started/README.md new file mode 100644 index 0000000..0a8674e --- /dev/null +++ b/00-getting-started/README.md @@ -0,0 +1,55 @@ +# 00 · Getting started with a flake + +**Goal:** build and run a package before unpacking the language behind it. Allow 10–15 minutes. + +Use the [training VM](../README.md#training-vm), or an existing Nix installation with `nix-command` and `flakes` enabled. On another installation, add `experimental-features = nix-command flakes` to `~/.config/nix/nix.conf` (create the file if needed). The supplied VM already enables both. + +## Run the example + +From the repository root: + +```sh +cd 00-getting-started +nix flake show +nix run +nix run -- --greeting="Hello, Gambiconf!" +nix build +./result/bin/hello +nix flake metadata +``` + +Expected: `nix flake show` lists a default package for each supported system; `nix run` prints `Hello, world!`; the next command prints your greeting. `nix build` creates a `result` symlink into `/nix/store`. Nix can download an existing output instead of compiling it. + +Commands here run from this directory. The repository root has a separate flake for building training images and maintaining the course. Each exercise has its own flake and can be copied independently. + +## Four things to recognize + +| Part | Meaning | +|---|---| +| `inputs.nixpkgs` | Where the package collection comes from | +| `flake.lock` | The exact resolved dependency, including its revision and hash | +| `packages..default` | What `nix build` selects on your architecture | +| `result` | A symlink to the realised output, not the build recipe | + +The URL names a moving channel, but the **supplied lock file pins its resolution**. Keep it; do not update it during the workshop. The exercises use the same nixpkgs source and revision to reuse downloads. A remote command such as `nix run nixpkgs#hello` does not automatically use this directory's lock. + +`forAllSystems` repeats the package definition for x86_64 Linux, ARM64 Linux and Apple Silicon macOS. This nixpkgs pin no longer supports Intel macOS; use the x86_64 Linux training VM on an Intel Mac. Treat the loop as supplied scaffolding for now; [module 01](../01-nix-language/README.md) explains the language and [module 05](../05-flakes/README.md) explores the output structure. + +## A small experiment + +1. Run `nix build` again. Already available outputs are reused. +2. Change the argument to `--greeting`. This changes program execution, not the build inputs. +3. Inspect `result` with `readlink result`. Module 02 explains that path. + +The default package here comes from nixpkgs. In module 03 you will write your own recipe and compile GNU Hello from source. + +## Git and new files + +Inside a Git repository, Nix normally sees tracked files, including their current edits. When adding a file, run `git add ` before referring to it from the flake. A commit is not required to try it. A dirty-tree warning is normal while experimenting. + +**Next:** [01 · Nix language](../01-nix-language/README.md). + +--- +Sources: +- +- diff --git a/00-getting-started/flake.lock b/00-getting-started/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/00-getting-started/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/00-getting-started/flake.nix b/00-getting-started/flake.nix new file mode 100644 index 0000000..9a0132a --- /dev/null +++ b/00-getting-started/flake.nix @@ -0,0 +1,20 @@ +{ + description = "First steps: build and run a locked package"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + packages = forAllSystems (system: { + default = nixpkgs.legacyPackages.${system}.hello; + }); + }; +} diff --git a/01-nix-language/README.md b/01-nix-language/README.md index aedf769..0492633 100644 --- a/01-nix-language/README.md +++ b/01-nix-language/README.md @@ -11,6 +11,8 @@ The Nix language exists to create and compose **derivations**, which are precise ## Reading Order +**Prerequisite:** [00 · Getting started](../00-getting-started/README.md). Keep its `flake.nix` open: `inputs` is an attribute set, `outputs` is a function, and `forAllSystems` applies another function to each supported system. You can use the supplied scaffold while learning these pieces. + 1. [types.md](types.md): the ten value types, and why paths are special 2. [syntax.md](syntax.md): literals, sets, `let`/`inherit`, functions, `if`/`assert`/`with`, and identifiers 3. [operators.md](operators.md): the precedence table, `//`, `?`, and `+` on paths and strings @@ -30,7 +32,7 @@ x: x + 1 x: y: x + y { a, b ? 2, ... }@args: a + b import ./foo.nix map (x: x * 2) [ 1 2 3 ] ``` -Try everything interactively with `nix repl`. +Try expressions interactively with `nix repl`. From `00-getting-started/`, use `:lf .` to load the locked flake, then inspect `inputs.nixpkgs` and `outputs.packages`. Lookup paths such as `` are language reference material; the exercises resolve dependencies through flake inputs. **Next:** [02 · The Nix Store](../02-nix-store/README.md). Once you know the language, see where its values end up. diff --git a/02-nix-store/README.md b/02-nix-store/README.md index 315c177..151e5ad 100644 --- a/02-nix-store/README.md +++ b/02-nix-store/README.md @@ -4,6 +4,20 @@ The Nix store is an abstraction for **immutable file system data that can depend **Prerequisite:** [01 · The Nix Language](../01-nix-language/README.md) +## Inspect something you already built + +From `00-getting-started/`: + +```sh +nix build +readlink result +nix path-info --closure-size ./result +nix store ls ./result/bin +nix-store --query --references ./result +``` + +The result is immutable and references other store objects. The `nix-store` query is a low-level inspection tool; builds and dependency selection throughout this course use the flake CLI. Do not collect the workshop's preloaded dependencies while following the exercises. + ## Reading order The store model, bottom-up: 1. [file-system-objects.md](file-system-objects.md): files, directories, and symlinks; flat vs NAR hashing diff --git a/03-derivations/00-raw-derivation/README.md b/03-derivations/00-raw-derivation/README.md new file mode 100644 index 0000000..aab437e --- /dev/null +++ b/03-derivations/00-raw-derivation/README.md @@ -0,0 +1,23 @@ +# A raw derivation · 5 minutes + +From this directory: + +```sh +nix derivation show +nix build -L +cat result +readlink result +``` + +Expected: a JSON description containing the builder, arguments and environment, followed by an output containing `Hello from a derivation!`. The output is a **file**, not a directory. + +Open `greeting.nix`. `system` comes from the flake's per-system scaffold, and the builder is Bash in the store. Its builtin `printf` needs no external command or `PATH`. `GREETING` becomes an environment variable; Nix supplies `$out`. + +Change `GREETING`, inspect `nix derivation show`, then build again. Both the derivation and output paths change. An unchanged build reuses its result. + +**Troubleshoot:** replace the build command with `exit 1`, run `nix build -L`, and inspect the failure. Restore the command before continuing. Host paths such as `/bin/sh` are not a portable substitute for a declared builder in the store. + +**Next:** [GNU Hello](../01-gnu-hello/README.md). + +--- +Source: diff --git a/03-derivations/00-raw-derivation/flake.lock b/03-derivations/00-raw-derivation/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/03-derivations/00-raw-derivation/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/03-derivations/00-raw-derivation/flake.nix b/03-derivations/00-raw-derivation/flake.nix new file mode 100644 index 0000000..b4c26da --- /dev/null +++ b/03-derivations/00-raw-derivation/flake.nix @@ -0,0 +1,23 @@ +{ + description = "A primitive derivation that writes a greeting"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + packages = forAllSystems (system: { + default = import ./greeting.nix { + inherit system; + inherit (nixpkgs.legacyPackages.${system}) bash; + }; + }); + }; +} diff --git a/03-derivations/00-raw-derivation/greeting.nix b/03-derivations/00-raw-derivation/greeting.nix new file mode 100644 index 0000000..683b073 --- /dev/null +++ b/03-derivations/00-raw-derivation/greeting.nix @@ -0,0 +1,12 @@ +{ bash, system }: + +builtins.derivation { + name = "greeting"; + inherit system; + builder = "${bash}/bin/bash"; + GREETING = "Hello from a derivation!"; + args = [ + "-c" + ''printf '%s\n' "$GREETING" > "$out"'' + ]; +} diff --git a/03-derivations/01-gnu-hello/README.md b/03-derivations/01-gnu-hello/README.md new file mode 100644 index 0000000..ae285c5 --- /dev/null +++ b/03-derivations/01-gnu-hello/README.md @@ -0,0 +1,40 @@ +# Build GNU Hello · 10–15 minutes + +This recipe is adapted from [Hausdorff Labs' GNU Hello example](https://github.com/hausdorff-labs/nixos-presentation/tree/main/examples/hello): the same version, source archive, hash and enabled checks, with a standalone flake supplying dependencies. + +```sh +nix flake show +nix build -L +./result/bin/hello +nix run -- --greeting="Hello, Gambiconf!" +nix log .#hello +``` + +Expected: `Hello, world!`, then your greeting. The build logs show unpacking, configuring, compiling, checking and installing. Checks are enabled **inside `mkDerivation`**, not as a top-level flake output. + +## Follow the dependency chain + +`flake.nix` takes the locked nixpkgs package set and explicitly passes `stdenv` and `fetchurl` to `hello.nix`. That function returns a derivation. `stdenv` recognizes Hello's Autotools project, so no custom build phases are needed. + +Look for `configure`, `make`, the test results and installation under `$out`. Running `nix build` again reuses the available output. Changing the runtime greeting does not change the derivation. + +## Hash experiment + +In `hello.nix`, temporarily replace `sha256` with `""`, then run `nix build -L`. The fetcher reports a mismatch and the hash it actually computed. Restore the supplied hash and build again. A cached archive with the correct hash is not evidence that arbitrary network access is available to normal builders. + +## Enter the build environment + +```sh +nix develop .#hello +type -a cc make +exit +``` + +This enters the package's build environment without running its complete build. It is different from installing Hello as a shell tool. Module 04 returns to this distinction. + +**Next:** [build a static site](../02-static-site/README.md). + +--- +Sources: +- +- diff --git a/03-derivations/01-gnu-hello/flake.lock b/03-derivations/01-gnu-hello/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/03-derivations/01-gnu-hello/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/03-derivations/01-gnu-hello/flake.nix b/03-derivations/01-gnu-hello/flake.nix new file mode 100644 index 0000000..afd6638 --- /dev/null +++ b/03-derivations/01-gnu-hello/flake.nix @@ -0,0 +1,30 @@ +{ + description = "Build GNU Hello from the Hausdorff Labs presentation recipe"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + packages = forAllSystems ( + system: + let + pkgs = nixpkgs.legacyPackages.${system}; + hello = import ./hello.nix { + inherit (pkgs) stdenv fetchurl; + }; + in + { + inherit hello; + default = hello; + } + ); + }; +} diff --git a/03-derivations/01-gnu-hello/hello.nix b/03-derivations/01-gnu-hello/hello.nix new file mode 100644 index 0000000..0e87092 --- /dev/null +++ b/03-derivations/01-gnu-hello/hello.nix @@ -0,0 +1,16 @@ +{ stdenv, fetchurl }: + +let + version = "2.12"; +in +stdenv.mkDerivation { + pname = "hello"; + inherit version; + + src = fetchurl { + url = "https://ftp.gnu.org/gnu/hello/hello-${version}.tar.gz"; + sha256 = "1ayhp9v4m4rdhjmnl2bq3cibrbqqkgjbl3s7yk2nhlh8vj3ay16g"; + }; + + doCheck = true; +} diff --git a/03-derivations/02-static-site/README.md b/03-derivations/02-static-site/README.md new file mode 100644 index 0000000..70f6aec --- /dev/null +++ b/03-derivations/02-static-site/README.md @@ -0,0 +1,25 @@ +# Build a static site · 5–10 minutes + +```sh +nix build -L +cat result/index.html +readlink result +``` + +Expected: an HTML page with `Hello, Gambiconf!` and three topics. A derivation can produce data or a website, not just an executable. `nix run` is not appropriate here: this output has no program to run. + +Open `site.nix`: `runCommand` uses a standard environment **without a compiler**; `nativeBuildInputs` provides the build-time `jq` tool; `${./site.json}` and `${./render.jq}` declare local file inputs. + +## Experiments + +1. Edit the title in `site.json` and rebuild. Observe the changed store path. +2. Include `&` or `<` in the title. The renderer HTML-escapes the data. +3. Temporarily remove `jq` from `nativeBuildInputs`. The build fails with a missing command even if jq is installed on your host. Restore it. +4. Put malformed JSON in the fixture and read the failure with `nix build -L`. Restore valid JSON. + +The fixture and renderer are version-controlled local files; building the page itself makes no network requests. The first invocation can still fetch nixpkgs and tools if they are not already present. + +Module 04 performs this same transformation in a writable development environment. Module 07 serves a self-contained copy with nginx. + +--- +Source: diff --git a/03-derivations/02-static-site/flake.lock b/03-derivations/02-static-site/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/03-derivations/02-static-site/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/03-derivations/02-static-site/flake.nix b/03-derivations/02-static-site/flake.nix new file mode 100644 index 0000000..f9e3760 --- /dev/null +++ b/03-derivations/02-static-site/flake.nix @@ -0,0 +1,28 @@ +{ + description = "Build a static page from local JSON with jq"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + packages = forAllSystems ( + system: + let + pkgs = nixpkgs.legacyPackages.${system}; + site = import ./site.nix { inherit (pkgs) runCommand jq; }; + in + { + inherit site; + default = site; + } + ); + }; +} diff --git a/03-derivations/02-static-site/render.jq b/03-derivations/02-static-site/render.jq new file mode 100644 index 0000000..39c82db --- /dev/null +++ b/03-derivations/02-static-site/render.jq @@ -0,0 +1 @@ +"\n\n\n\(.title | @html)\n

\(.title | @html)

\n
    \(.topics | map("
  • \(. | @html)
  • ") | join(""))
\n" diff --git a/03-derivations/02-static-site/site.json b/03-derivations/02-static-site/site.json new file mode 100644 index 0000000..7158627 --- /dev/null +++ b/03-derivations/02-static-site/site.json @@ -0,0 +1,4 @@ +{ + "title": "Hello, Gambiconf!", + "topics": ["Derivations", "Shells", "NixOS"] +} diff --git a/03-derivations/02-static-site/site.nix b/03-derivations/02-static-site/site.nix new file mode 100644 index 0000000..1c8e5b4 --- /dev/null +++ b/03-derivations/02-static-site/site.nix @@ -0,0 +1,6 @@ +{ runCommand, jq }: + +runCommand "training-site" { nativeBuildInputs = [ jq ]; } '' + mkdir -p "$out" + jq --exit-status --raw-output --from-file ${./render.jq} ${./site.json} > "$out/index.html" +'' diff --git a/03-derivations/README.md b/03-derivations/README.md index 235f609..fbc9561 100644 --- a/03-derivations/README.md +++ b/03-derivations/README.md @@ -17,13 +17,25 @@ A **derivation** is the bridge between the language and the store. A Nix express 5. [debugging.md](debugging.md): `--show-trace`, `nix repl`, tracing, and keeping failed builds ## Try it + +Run these standalone flakes in order, using their supplied locks: + +| Exercise | Time | Result | +|---|---|---| +| [00 · Raw derivation](00-raw-derivation/README.md) | 5 min | A text file built by a declared Bash | +| [01 · GNU Hello](01-gnu-hello/README.md) | 10–15 min | A compiled and checked executable | +| [02 · Static site](02-static-site/README.md) | 5–10 min | HTML generated from local JSON | + +From the raw-derivation directory: + ```sh -nix repl -nix-repl> d = derivation { name = "hi"; system = builtins.currentSystem; builder = "/bin/sh"; args = [ "-c" "echo hi > $out" ]; } -nix-repl> d.drvPath -nix-repl> :b d +nix derivation show +nix build -L +cat result ``` +Keep advanced attributes, IFD and distributed builds as reference or extension material after the core exercises. [Module 06](../06-nixpkgs/README.md) deepens the packaging model with `callPackage` and an optional `icat` challenge from nix.dev. + **Next:** [04 · Shells](../04-shells/README.md) shows how to use derivations as development environments. --- diff --git a/03-derivations/debugging.md b/03-derivations/debugging.md index 2f33a91..91011a1 100644 --- a/03-derivations/debugging.md +++ b/03-derivations/debugging.md @@ -12,9 +12,10 @@ nix log /nix/store/…-pkg.drv # the log of a past build ## 2. Explore with `nix repl` ```sh -nix repl -f '' # needs NIX_PATH -nix repl -f flake:nixpkgs # works without NIX_PATH +nix repl +# At the prompt: :lf . ``` +Start in an exercise directory. `:lf .` loads that exercise's locked inputs and outputs, without a channel or registry lookup. Useful REPL commands: | Cmd | Does | diff --git a/03-derivations/derivations.md b/03-derivations/derivations.md index 103887a..a4b8ab3 100644 --- a/03-derivations/derivations.md +++ b/03-derivations/derivations.md @@ -6,8 +6,8 @@ | Attr | Type | Meaning | |---|---|---| | `name` | string | Gives `/nix/store/-.drv` and output `/nix/store/-[-]` | -| `system` | string | Where it can be built: `"x86_64-linux"`, or `builtins.currentSystem` | -| `builder` | path/string | The executable to run: `"/bin/bash"`, `./builder.sh` (copied to the store), or `"${pkgs.python}/bin/python"` | +| `system` | string | Where it can be built: e.g. `"x86_64-linux"`; pass it from the flake's per-system definition | +| `builder` | path/string | An executable in the store, e.g. `"${pkgs.bash}/bin/bash"`; copying a script alone does not declare its interpreter | ## Optional attributes - `args`: a list of strings passed to the builder. Default `[ ]`. @@ -37,22 +37,27 @@ This is how dependencies are wired up. Referring to another derivation (directly ## Minimal example ```nix -derivation { +{ bash, system }: +builtins.derivation { name = "hello-txt"; - system = builtins.currentSystem; - builder = "/bin/sh"; - args = [ "-c" "echo hello > $out" ]; + inherit system; + builder = "${bash}/bin/bash"; + args = [ "-c" ''printf 'hello\n' > "$out"'' ]; } ``` ```sh -nix-build hello.nix # or: nix build -f hello.nix -nix derivation show ./result # inspect the .drv as JSON +cd 00-raw-derivation +nix derivation show # inspect before realisation +nix build -L +cat result ``` +The runnable [raw derivation flake](00-raw-derivation/README.md) supplies Bash and `system` explicitly. `builtins.currentSystem` is unavailable during pure flake evaluation; a host `/bin/sh` is not a portable sandboxed builder. + ## Evaluation → instantiation → realisation 1. **Evaluate** the Nix expression → a derivation value. -2. **Instantiate** → the `.drv` file is written to the store (`nix-instantiate`). -3. **Realise** → the builder runs in a sandbox, or outputs are substituted (`nix-store --realise`, `nix build`). +2. **Instantiate** → the `.drv` file is written to the store (`nix derivation show` exposes its description). +3. **Realise** → the builder runs in a sandbox, or outputs are substituted (`nix build`). ## See also - [advanced-attributes.md](advanced-attributes.md): output checks, fixed-output and CA derivations diff --git a/README.md b/README.md index c9da433..e898a79 100644 --- a/README.md +++ b/README.md @@ -32,21 +32,24 @@ Nix runs on Linux, macOS and even Windows [Through NixOS-WSL](https://github.com | # | Module | You'll learn | |---|---|---| +| 00 | [Getting started](00-getting-started/README.md) | run a flake, build a package, inspect its locked inputs | | 01 | [Nix Language](01-nix-language/README.md) | types, syntax, operators, scoping, strings and context, builtins | | 02 | [Nix Store](02-nix-store/README.md) | file system objects, store objects and paths, store types, profiles, GC, substituters | -| 03 | [Derivations](03-derivations/README.md) | `derivation`, advanced attributes, IFD, remote builds, debugging | -| 04 | [Shells](04-shells/README.md) | `nix-shell -p`, `shell.nix`, `nix develop`, shebang scripts | -| 05 | [Flakes](05-flakes/README.md) | `flake.nix`, inputs/outputs, `flake.lock`, flakerefs, the new CLI | +| 03 | [Derivations](03-derivations/README.md) | build a raw derivation, GNU Hello and a static page; debug builds | +| 04 | [Development shells](04-shells/README.md) | `devShells`, `nix develop`, lightweight tools and package build environments | +| 05 | [Flakes in depth](05-flakes/README.md) | compose flakes, align inputs, update locks, expose checks | | 06 | [Nixpkgs](06-nixpkgs/README.md) | `callPackage`, packaging, `stdenv`, overrides and overlays | | 07 | [NixOS](07-nixos/README.md) | system configuration, VMs, the module system, VM integration tests | | 08 | [Declarative Infra](08-declarative-infra/README.md) | nixos-anywhere + disko, Terraform, running a binary cache | ## How to use this repo -- Work through the modules **in order**. Each README gives a reading order for its notes and links to the next module. +- Start at **00** and work through the modules in order. Flakes are the course's interface from the first exercise; module 05 explores them in depth. +- Each runnable exercise has a standalone `flake.nix` and `flake.lock`. Run its commands **inside its directory**. The root flake maintains this repository and builds the training VM. +- Keep the supplied locks during the workshop. Examples share the root nixpkgs source and revision so cached dependencies can be reused. This pin supports x86_64 Linux, ARM64 Linux and Apple Silicon macOS; Intel Mac participants use the x86_64 guest. - Every note ends with the upstream **Source** links. The notes are condensed summaries, and the manual remains the authority. - Nix manual pages are cited at version **2.34**. -- Try the examples in `nix repl` or a scratch directory as you go. +- Use `nix build`, `nix run`, `nix develop` and `nix repl` (`:lf .`) as you go. Traditional commands appear only where they help explain an existing interface or inspect low-level state. ## Training VM diff --git a/README.pt-br.md b/README.pt-br.md index 51c42a2..7bd4cf5 100644 --- a/README.pt-br.md +++ b/README.pt-br.md @@ -1,2 +1,35 @@ # Nix Training +🌐 [🇺🇸 English](README.md) | [🇧🇷 Português](README.pt-br.md) + +Material do treinamento de Nix criado para a [Gambiconf 2026](https://gambiconf.dev/). + +## Como seguir o curso + +Comece pelo módulo **00**. Usamos flakes desde o primeiro exercício, com `nix build`, `nix run` e `nix develop`. O módulo 05 aprofunda o que você já terá utilizado. + +Cada exemplo executável tem seu próprio `flake.nix` e `flake.lock` e pode ser copiado separadamente. Execute os comandos **dentro do diretório do exemplo**. O flake da raiz serve para manter o repositório e construir a VM do curso. + +Mantenha os arquivos de lock fornecidos: todos os exemplos usam a mesma revisão do nixpkgs para reaproveitar downloads. A revisão suporta Linux x86_64, Linux ARM64 e macOS Apple Silicon. Em um Mac Intel, faça os exercícios na VM Linux x86_64. + +## Módulos + +Os textos dos módulos estão em inglês. + +| # | Módulo | Conteúdo | +|---|---|---| +| 00 | [Primeiros passos](00-getting-started/README.md) | executar um flake, construir um pacote e inspecionar o lock | +| 01 | [Linguagem Nix](01-nix-language/README.md) | tipos, funções, escopo, strings e builtins | +| 02 | [Nix store](02-nix-store/README.md) | caminhos, dependências, perfis e caches | +| 03 | [Derivações](03-derivations/README.md) | derivação básica, GNU Hello e geração de HTML | +| 04 | [Ambientes de desenvolvimento](04-shells/README.md) | `devShells`, ferramentas leves e ambientes de compilação | +| 05 | [Flakes em profundidade](05-flakes/README.md) | composição, atualização de inputs, sistemas e checks | +| 06 | [Nixpkgs](06-nixpkgs/README.md) | empacotamento, `callPackage`, overrides e overlays | +| 07 | [NixOS](07-nixos/README.md) | configuração, servidor web, gerações e rollback | +| 08 | [Infraestrutura declarativa](08-declarative-infra/README.md) | instalação remota, Terraform e cache binário | + +## VM do treinamento + +As [releases](https://github.com/PerplexSystems/nix-training/releases/latest) oferecem imagens qcow2 para x86_64 e ARM64. O comando `make run` seleciona a arquitetura, inicia a VM e encaminha SSH para `127.0.0.1:2222`. Usuário e senha: `gambi` / `gambi`. As alterações da VM são descartadas ao sair. + +Consulte [Training VM](README.md#training-vm) para os comandos de construção, requisitos do QEMU e configuração de SSH. From 6ca4c87ff536af3a8e0a8d8778cbc74310129c9a Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Tue, 13 Oct 2026 11:00:44 -0400 Subject: [PATCH 3/8] feat: teach lightweight flake development shells --- .gitignore | 4 + 04-shells/README.md | 36 +-- 04-shells/ad-hoc-shells.md | 46 ++-- 04-shells/declarative-shells.md | 55 ++--- 04-shells/devenv-shell/README.md | 26 ++ 04-shells/devenv-shell/devenv.nix | 19 ++ 04-shells/devenv-shell/flake.lock | 292 +++++++++++++++++++++++ 04-shells/devenv-shell/flake.nix | 30 +++ 04-shells/devenv-shell/render.jq | 1 + 04-shells/devenv-shell/site.json | 4 + 04-shells/nix-shell-vs-nix-develop.md | 81 +++---- 04-shells/plain-flake-shell/README.md | 41 ++++ 04-shells/plain-flake-shell/devshell.nix | 9 + 04-shells/plain-flake-shell/flake.lock | 24 ++ 04-shells/plain-flake-shell/flake.nix | 20 ++ 04-shells/plain-flake-shell/render.jq | 1 + 04-shells/plain-flake-shell/report.sh | 3 + 04-shells/plain-flake-shell/site.json | 4 + 18 files changed, 574 insertions(+), 122 deletions(-) create mode 100644 04-shells/devenv-shell/README.md create mode 100644 04-shells/devenv-shell/devenv.nix create mode 100644 04-shells/devenv-shell/flake.lock create mode 100644 04-shells/devenv-shell/flake.nix create mode 100644 04-shells/devenv-shell/render.jq create mode 100644 04-shells/devenv-shell/site.json create mode 100644 04-shells/plain-flake-shell/README.md create mode 100644 04-shells/plain-flake-shell/devshell.nix create mode 100644 04-shells/plain-flake-shell/flake.lock create mode 100644 04-shells/plain-flake-shell/flake.nix create mode 100644 04-shells/plain-flake-shell/render.jq create mode 100644 04-shells/plain-flake-shell/report.sh create mode 100644 04-shells/plain-flake-shell/site.json diff --git a/.gitignore b/.gitignore index 23253f9..67443cf 100644 --- a/.gitignore +++ b/.gitignore @@ -64,3 +64,7 @@ result-* # Ignore NixOS interactive test driver history **/.nixos-test-history + +# Writable development-environment state and rendered workspace pages +.devenv/ +/04-shells/*/index.html diff --git a/04-shells/README.md b/04-shells/README.md index 687e4ba..89cc7b5 100644 --- a/04-shells/README.md +++ b/04-shells/README.md @@ -1,27 +1,35 @@ -# 04 · Shells +# 04 · Development shells -Nix shells give you **per-project, reproducible development environments**. No global installs are needed, and every teammate gets the same tool versions. A shell is really a derivation's build environment with its dependencies realised. +Use the same locked flake interface to enter a development environment: **`nix develop`**. A shell provides tools and environment variables for working on files; it does not build your project's final artifact or sandbox your interactive session. -**Prerequisites:** [03 · Derivations](../03-derivations/README.md) (a shell is a derivation you *enter* rather than build) +**Prerequisites:** [03 · Derivations](../03-derivations/README.md). + +## Hands-on order + +1. [Plain flake shell](plain-flake-shell/README.md), 10 minutes: a compiler-free jq workspace with local data. +2. From the GNU Hello exercise, `nix develop .#hello`: enter an existing package's build environment and reuse its dependencies. +3. [Devenv flake shell](devenv-shell/README.md), optional 5–10 minutes: the same task with named project commands. + +The core shell adds only jq. Avoid language toolchains, dependency installation from npm/PyPI, API calls and background services during this introduction. The supplied locks share the training image's nixpkgs revision; devenv has additional framework dependencies and should be warmed separately. ## Reading order -1. [ad-hoc-shells.md](ad-hoc-shells.md): `nix-shell -p`, `--run`, `--pure`, and pinning with `-I` -2. [declarative-shells.md](declarative-shells.md): `shell.nix` with `mkShellNoCC`, env vars, and `shellHook` -3. [nix-shell-vs-nix-develop.md](nix-shell-vs-nix-develop.md): classic vs flake CLI, phases, and shebang scripts + +1. [declarative-shells.md](declarative-shells.md): `devShells`, `mkShellNoCC`, variables and hooks. +2. [ad-hoc-shells.md](ad-hoc-shells.md): temporary tools with `nix shell` and explicit input selection. +3. [nix-shell-vs-nix-develop.md](nix-shell-vs-nix-develop.md): package environments, CLI distinctions and legacy reference. ## Quick reference + ```sh -nix-shell -p jq curl # throwaway tools -nix-shell # enter ./shell.nix -nix develop # enter the flake's devShells..default -nix shell nixpkgs#jq # just add to PATH (new CLI) +nix develop # default devShell of the current exercise +nix develop --command bash report.sh +nix develop .#hello # environment of a package output named hello +nix shell --inputs-from . nixpkgs#jq # temporary tools using this flake's input ``` -**Next:** [05 · Flakes](../05-flakes/README.md): replace `fetchTarball` pins with a lock file. +**Next:** [05 · Flakes in depth](../05-flakes/README.md): compose and maintain the flakes you have been using. --- Sources: -- -- -- - +- diff --git a/04-shells/ad-hoc-shells.md b/04-shells/ad-hoc-shells.md index 2129f57..21f81a2 100644 --- a/04-shells/ad-hoc-shells.md +++ b/04-shells/ad-hoc-shells.md @@ -1,44 +1,28 @@ -# Ad hoc Shell Environments +# Ad hoc tools with `nix shell` -> `nix-shell -p pkg…` gives you a temporary shell with any packaged program, and nothing is installed permanently. Pin nixpkgs with `-I` to make it reproducible. +For a temporary tool, use `nix shell`. It adds executables to `PATH`; it does not run a development shell's activation hook or provide a package's complete build environment. -## Key concepts -- Programs are available **only inside** the shell. After `exit` or Ctrl-D they're gone from your `PATH`, though they stay cached in the store until GC. -- Find package names at . The package name can differ from the binary name, e.g. `nvim` comes from `neovim`. -- Shells nest. Running `nix-shell -p python3` inside another shell *adds* to the environment. +From an exercise flake with a locked nixpkgs input: -## Examples ```sh -nix-shell -p cowsay lolcat # interactive shell -nix-shell -p cowsay --run "cowsay Nix" # run one command and exit -nix-shell -p hello --run hello # no quotes needed for a bare program name -nix-shell -p git neovim nodejs # several tools at once -which git # → /nix/store/…-git-2.38.3/bin/git +nix shell --inputs-from . nixpkgs#jq --command jq --version ``` -## Towards reproducibility -```sh -nix-shell -p git --run "git --version" --pure \ - -I nixpkgs=https://github.com/NixOS/nixpkgs/tarball/2a601aafdc5605a5133a2ca506a34a3a73377247 -``` -- `--run CMD` runs a non-interactive command, then exits. -- `--pure` clears most of the environment (it keeps `HOME`, `USER`, `DISPLAY`, …), so only Nix-provided tools are visible. It's great for one-liners but annoying for development, since your editor disappears. -- `-I nixpkgs=` pins **exactly** which nixpkgs revision supplies the packages. +`--inputs-from .` makes the indirect `nixpkgs` reference use this flake's input. In contrast: -## New CLI equivalents (flakes) ```sh -nix shell nixpkgs#cowsay nixpkgs#lolcat # like nix-shell -p (but no stdenv setup) -nix run nixpkgs#hello # like --run for a package's main program +nix shell nixpkgs#jq ``` -## Gotchas -- Without pinning, the same command gives different versions on different machines, depending on the local channel. -- Free space afterwards with `nix-collect-garbage`. +uses the registry's nixpkgs resolution, which need not match the exercise lock and may download a different package set. + +For a repeatable project environment, put its tools in `devShells` and use `nix develop`. For a one-off executable, `nix run` can build and launch it without opening a shell. + +## Legacy equivalent -## See also -- [declarative-shells.md](declarative-shells.md): put this in a file -- [nix-shell-vs-nix-develop.md](nix-shell-vs-nix-develop.md) -- [../01-nix-language/scope.md](../01-nix-language/scope.md): how `-I` and `NIX_PATH` work +You may encounter `nix-shell -p jq` in older documentation. It uses the lookup-path package set rather than this exercise's flake inputs. We use the flake CLI for the course's main workflow. --- -Source: +Sources: +- +- diff --git a/04-shells/declarative-shells.md b/04-shells/declarative-shells.md index 7facb9b..b7f9c2a 100644 --- a/04-shells/declarative-shells.md +++ b/04-shells/declarative-shells.md @@ -1,43 +1,40 @@ -# Declarative Shells with `shell.nix` +# Declarative development shells -> Put the environment in a version-controlled `shell.nix`: pinned nixpkgs, packages, env vars, and a startup hook. Anyone gets the same shell by running `nix-shell`. +Expose an environment as `devShells..` in a flake. The [complete plain-shell example](plain-flake-shell/flake.nix) supplies the supported systems and locked nixpkgs; its environment is: -## A basic `shell.nix` ```nix -let - nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-24.05"; - pkgs = import nixpkgs { config = {}; overlays = []; }; # ignore global user config -in +{ pkgs }: pkgs.mkShellNoCC { - packages = with pkgs; [ cowsay lolcat ]; - - GREETING = "Hello, Nix!"; # any extra attribute becomes an env var - + packages = [ pkgs.jq ]; + REPORT_TITLE = "Gambiconf training"; shellHook = '' - echo $GREETING | cowsay | lolcat + printf 'Try: bash report.sh\n' ''; } ``` + +The flake imports this function with its per-system `pkgs` and assigns the result to `devShells.${system}.default`. + ```sh -nix-shell # picks up ./shell.nix (or default.nix if there's no shell.nix) +nix develop +nix develop --command bash report.sh ``` ## Key concepts -- **`mkShell` vs `mkShellNoCC`:** `mkShell` includes a C compiler toolchain (stdenv). `NoCC` skips it and is lighter for tool-only shells. -- Both are wrappers around `mkDerivation`, so they accept `buildInputs`, `nativeBuildInputs`, and so on. **`packages` is an alias for `nativeBuildInputs`.** -- **Env vars:** any unreserved attribute that can be coerced to a string is exported. -- **Protected vars:** `nix-shell` sets some variables itself, such as `PS1`. Set those in `shellHook` instead. -- **`shellHook`:** a bash snippet run after `$stdenv/setup` is sourced. It runs *only* in shells, never in real builds. -- Pin nixpkgs, either to a release branch tarball or better to a commit, and set `config = {}` and `overlays = []` so user-global settings can't leak in. - -## Next steps -- Auto-activate the shell on `cd` with [direnv](https://nix.dev/guides/recipes/direnv) (`use nix` / `use flake`). -- Manage pins with `npins`, or switch to flakes and a lock file ([../05-flakes/](../05-flakes/README.md)). - -## See also -- [ad-hoc-shells.md](ad-hoc-shells.md) -- [nix-shell-vs-nix-develop.md](nix-shell-vs-nix-develop.md) -- [../06-nixpkgs/stdenv.md](../06-nixpkgs/stdenv.md): what `mkDerivation` provides + +- **`mkShellNoCC`:** a standard shell environment without a compiler. Prefer it for tools such as jq. Use `mkShell` when a compiler is needed. +- **`packages`:** adds tools through `nativeBuildInputs`. +- **Environment variables:** extra unreserved, string-coercible attributes become environment variables. +- **`shellHook`:** runs on shell entry, including `nix develop --command`; it is not a package build phase. +- **`inputsFrom`:** shares build dependencies from existing derivations. It does not install their resulting executables. +- **Lock:** `nix develop` uses the current flake's resolved inputs. It is not necessary to import `` or fetch a separate tarball inside the shell definition. +- **Isolation:** interactive commands can access your home directory, network and inherited tools. This is not the build sandbox. + +For automatic activation, an optional `.envrc` containing `use flake` works with nix-direnv. Read it before running `direnv allow`. + +The older `shell.nix` / `nix-shell` interface remains useful when working with projects that use it; see the [comparison](nix-shell-vs-nix-develop.md). --- -Source: +Sources: +- +- diff --git a/04-shells/devenv-shell/README.md b/04-shells/devenv-shell/README.md new file mode 100644 index 0000000..c5946f2 --- /dev/null +++ b/04-shells/devenv-shell/README.md @@ -0,0 +1,26 @@ +# The same workspace with devenv · optional, 5–10 minutes + +From this directory: + +```sh +nix develop --no-pure-eval +report +render > index.html +exit +nix develop --no-pure-eval --command report +``` + +Expected: the same title, topics and HTML as the plain flake shell. `devenv.nix` adds named scripts, an environment variable and a startup message; the flake exposes it as a `devShell` through `devenv.lib.mkShell`. No separate devenv installation is needed for these commands. + +The integration needs `--no-pure-eval` to discover the project working directory. This is specific to this example; the plain shell uses normal pure flake evaluation. `follows` makes devenv use our nixpkgs input. We disable implicit containers and use a compiler-free environment. + +**Change:** add another topic to `site.json` and run `report` again. Then change the startup message in `devenv.nix` and re-enter. + +**Troubleshoot:** try without `--no-pure-eval` and read the root-directory error. Also make sure your current directory is this exercise: the scripts intentionally read workspace files relative to it. + +Devenv has its own framework and transitive inputs. A small `packages` list does not make its cold start as small as the plain shell's. Use this comparison after warming its inputs; it is not part of the minimal-download core lab or the default VM preload. + +--- +Sources: +- +- diff --git a/04-shells/devenv-shell/devenv.nix b/04-shells/devenv-shell/devenv.nix new file mode 100644 index 0000000..a37ee4a --- /dev/null +++ b/04-shells/devenv-shell/devenv.nix @@ -0,0 +1,19 @@ +{ pkgs, lib, ... }: + +{ + stdenv = pkgs.stdenvNoCC; + containers = lib.mkForce { }; + packages = [ pkgs.jq ]; + env.REPORT_TITLE = "Gambiconf training"; + + scripts.report.exec = '' + jq --exit-status --raw-output '.title, (.topics[] | "- " + .)' site.json + ''; + scripts.render.exec = '' + jq --exit-status --raw-output --from-file render.jq site.json + ''; + + enterShell = '' + printf 'Run report, or render > index.html\n' + ''; +} diff --git a/04-shells/devenv-shell/flake.lock b/04-shells/devenv-shell/flake.lock new file mode 100644 index 0000000..78312f2 --- /dev/null +++ b/04-shells/devenv-shell/flake.lock @@ -0,0 +1,292 @@ +{ + "nodes": { + "cachix": { + "inputs": { + "devenv": [ + "devenv" + ], + "flake-compat": [ + "devenv", + "flake-compat" + ], + "git-hooks": [ + "devenv", + "git-hooks" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788181969, + "narHash": "sha256-OUB6hPlFBB9FRdZgZXSye4lDOg+fbrqKe8ePv2IM7NY=", + "owner": "cachix", + "repo": "cachix", + "rev": "98093e8eea6c1635ef1337a576fa76f3e8bd4f39", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "latest", + "repo": "cachix", + "type": "github" + } + }, + "crate2nix": { + "flake": false, + "locked": { + "lastModified": 1772186516, + "narHash": "sha256-8s28pzmQ6TOIUzznwFibtW1CMieMUl1rYJIxoQYor58=", + "owner": "rossng", + "repo": "crate2nix", + "rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e", + "type": "github" + }, + "original": { + "owner": "rossng", + "repo": "crate2nix", + "rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e", + "type": "github" + } + }, + "devenv": { + "inputs": { + "cachix": "cachix", + "crate2nix": "crate2nix", + "flake-compat": "flake-compat", + "flake-parts": "flake-parts", + "ghostty": "ghostty", + "git-hooks": "git-hooks", + "nix": "nix", + "nixd": "nixd", + "nixpkgs": [ + "nixpkgs" + ], + "rust-overlay": "rust-overlay" + }, + "locked": { + "lastModified": 1791549372, + "narHash": "sha256-5Vu2oKeImB5wQWLFSEcWXsF0Oajm4/5MV7UlnOdelmg=", + "owner": "cachix", + "repo": "devenv", + "rev": "a73c5b84c9527760f009232988466763068f9f61", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788306937, + "narHash": "sha256-lbrI1UYVpFgKSsyrU9oeF7FHfnu8nLD9ja0ou9f2rxk=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "f16b25b8c3d2809b87925d0b76652d7821a75c68", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "ghostty": { + "flake": false, + "locked": { + "lastModified": 1786026742, + "narHash": "sha256-tRtgTg/i3w1nFdRHU2IGekfJN8EyP+HARW4MtoUZyqk=", + "owner": "ghostty-org", + "repo": "ghostty", + "rev": "22d13172cde98a0a4dda05d3d6a3fcb0dd8ed018", + "type": "github" + }, + "original": { + "owner": "ghostty-org", + "repo": "ghostty", + "rev": "22d13172cde98a0a4dda05d3d6a3fcb0dd8ed018", + "type": "github" + } + }, + "git-hooks": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788267358, + "narHash": "sha256-nt+lUqYVpc9Y6JeMd2WmXzCDojasdadKo0mWcluvY2Y=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "27555e2624241fb116b49095df4caaee85a25691", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, + "nix": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "flake-parts": [ + "devenv", + "flake-parts" + ], + "git-hooks-nix": [ + "devenv", + "git-hooks" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-23-11": [ + "devenv" + ], + "nixpkgs-regression": [ + "devenv" + ] + }, + "locked": { + "lastModified": 1790176416, + "narHash": "sha256-acP7QvsB+dHghUeL9AwSSZ3qS//skpqjv484aveg1EQ=", + "owner": "cachix", + "repo": "nix", + "rev": "bd10d7f563420c6034b9d1dc75c4168fc01e5afc", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "devenv-2.35", + "repo": "nix", + "type": "github" + } + }, + "nixd": { + "inputs": { + "flake-parts": [ + "devenv", + "flake-parts" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "treefmt-nix": "treefmt-nix" + }, + "locked": { + "lastModified": 1788165251, + "narHash": "sha256-ITHt6eU6DuwQqlNV1/wehvKYPE6J8sZIlv75CpDjcHI=", + "owner": "nix-community", + "repo": "nixd", + "rev": "e2ca72c353cfbc3d63e942fe9aeae4ec497863bf", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixd", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "nixpkgs": "nixpkgs" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788332415, + "narHash": "sha256-BTFrmyh0oaVDsvA9NNw0YpbbeppTwU0t70iVx672Ew8=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "860d7c835ab91bfc8972b67092f5f2db8e9390a0", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "devenv", + "nixd", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1786901030, + "narHash": "sha256-WSFCsDSE5ffgD2MqzkM2CYjeFiKhRF/dJUN8uedb6YE=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "27b3b12a8e6375f28ebe122f07d230ca5459bbfa", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/04-shells/devenv-shell/flake.nix b/04-shells/devenv-shell/flake.nix new file mode 100644 index 0000000..950a429 --- /dev/null +++ b/04-shells/devenv-shell/flake.nix @@ -0,0 +1,30 @@ +{ + description = "The JSON workspace using devenv's flake integration"; + + inputs = { + nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + devenv = { + url = "github:cachix/devenv"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + inputs@{ nixpkgs, devenv, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + devShells = forAllSystems (system: { + default = devenv.lib.mkShell { + inherit inputs; + pkgs = nixpkgs.legacyPackages.${system}; + modules = [ ./devenv.nix ]; + }; + }); + }; +} diff --git a/04-shells/devenv-shell/render.jq b/04-shells/devenv-shell/render.jq new file mode 100644 index 0000000..39c82db --- /dev/null +++ b/04-shells/devenv-shell/render.jq @@ -0,0 +1 @@ +"\n\n\n\(.title | @html)\n

\(.title | @html)

\n
    \(.topics | map("
  • \(. | @html)
  • ") | join(""))
\n" diff --git a/04-shells/devenv-shell/site.json b/04-shells/devenv-shell/site.json new file mode 100644 index 0000000..7158627 --- /dev/null +++ b/04-shells/devenv-shell/site.json @@ -0,0 +1,4 @@ +{ + "title": "Hello, Gambiconf!", + "topics": ["Derivations", "Shells", "NixOS"] +} diff --git a/04-shells/nix-shell-vs-nix-develop.md b/04-shells/nix-shell-vs-nix-develop.md index 1e83b7d..b82d43b 100644 --- a/04-shells/nix-shell-vs-nix-develop.md +++ b/04-shells/nix-shell-vs-nix-develop.md @@ -1,61 +1,46 @@ -# `nix-shell` vs `nix develop` (and `nix shell`) +# `nix develop`, `nix shell`, and the legacy interface -> Both `nix-shell` and `nix develop` build a derivation's **dependencies**, not the derivation itself, and drop you into its build environment. `nix-shell` is the classic, `NIX_PATH`-based CLI. `nix develop` is the flake-based one. `nix shell` is different: it just puts packages on your `PATH`. +| Command | Selects | Provides | +|---|---|---| +| `nix develop` | Current flake's default devShell, falling back to a default package | A development/build environment, including hooks | +| `nix develop .#hello` | Named devShell or package | The selected environment; for a package, its build dependencies | +| `nix shell --inputs-from . nixpkgs#jq` | A package from the current flake's nixpkgs input | Tools on `PATH`, without `shellHook` | +| `nix run` | Default app or runnable package | Executes a program | +| `nix-shell` | Legacy `shell.nix`, then `default.nix` | A development/build environment | -## Comparison -| | `nix-shell` | `nix develop` | `nix shell` | -|---|---|---|---| -| CLI generation | classic | new (experimental `nix-command`) | new | -| Input | `shell.nix` → `default.nix`, `-p`, `-E`, URL tarball | a flake installable: `.`, `nixpkgs#hello` | a flake installable | -| Environment | the derivation's env + `$stdenv/setup` sourced | the same, recorded by a modified build of the drv | only `PATH` additions | -| `shellHook` | ✅ | ✅ | ❌ | -| Default lookup | `shell.nix`, then `default.nix` | `devShells..default`, then `packages..default` | `packages..default` | +## Package build environments + +From the [GNU Hello exercise](../03-derivations/01-gnu-hello/README.md): -## `nix-shell` essentials -```sh -nix-shell '' -A pan # build env of a package -nix-shell -p sqlite xorg.libX11 # ad hoc (-p also takes expressions) -nix-shell -p 'git.override { withManual = false; }' -nix-shell --pure --keep MY_VAR # clean env, keep selected vars -nix-shell --run 'make test' # non-interactive -nix-shell --command 'export X=1; return' # interactive; `return` keeps the shell open -``` -Inside a package's build env, replay the build phases: ```sh -eval ${unpackPhase:-unpackPhase}; cd $sourceRoot -eval ${configurePhase:-configurePhase} -eval ${buildPhase:-buildPhase} +nix develop .#hello +type -a cc make +exit ``` -(The `${x:-x}` form runs an overridden phase string if there is one, and the default function otherwise.) - -### Shebang scripts -```python -#! /usr/bin/env nix-shell -#! nix-shell -i python3 -p python3 python3Packages.prettytable -#! nix-shell -I nixpkgs=https://github.com/NixOS/nixpkgs/archive/.tar.gz -import prettytable -``` -- The first line goes to the OS. The following `#! nix-shell` lines add options (they merge), and `-i` picks the real interpreter. -- Quote any Nix expressions: `-p 'terraform.withPlugins (p: [ p.openstack ])'`. -- ⚠️ `--pure` doesn't make the *shell binary* reproducible. It comes from `NIX_BUILD_SHELL` or ``. -## `nix develop` essentials +`hello` is a **package output**, so Nix provides its build environment. It does not simply add `hello` to your path. `nix develop` records a modified derivation's environment and makes its dependencies available; normal package compilation is not required to enter it. + +To inspect the source interactively, from that same directory: + ```sh -nix develop # devShells..default of ./flake.nix -nix develop nixpkgs#hello # build env of GNU Hello -nix develop --command bash -c "cmake .. && make" -nix develop --unpack | --configure | --build | --check | --install # run one phase -nix develop --profile /tmp/env nixpkgs#hello # save the env as a GC-rooted profile -nix develop /tmp/env # reuse it later, even offline -nix develop --redirect nixpkgs#glibc.dev ~/my-glibc/outputs/dev # swap in a writable path +nix develop .#hello +work=$(mktemp -d) +cd "$work" +unpackPhase +cd "$sourceRoot" +configurePhase +buildPhase +exit ``` -Customize the prompt with `bash-prompt`, `bash-prompt-prefix`, and `bash-prompt-suffix` in `nix.conf` or the flake's `nixConfig`. -## See also -- [ad-hoc-shells.md](ad-hoc-shells.md), [declarative-shells.md](declarative-shells.md) -- [../05-flakes/flake-schema.md](../05-flakes/flake-schema.md): `devShells` outputs +These commands use Hello's default phases. Custom phase attributes can contain shell strings rather than function names; inspect them before replaying another package's phases. + +## Legacy reference + +Older projects may use `nix-shell`, `shell.nix`, or `#! nix-shell` scripts. They are separate entry points, not prerequisites for flakes. `nix-shell --pure` reduces inherited environment variables but does not sandbox interactive commands. Likewise, `nix develop` does not isolate arbitrary shell commands from the host. --- Sources: -- - +- +- diff --git a/04-shells/plain-flake-shell/README.md b/04-shells/plain-flake-shell/README.md new file mode 100644 index 0000000..aabb9a9 --- /dev/null +++ b/04-shells/plain-flake-shell/README.md @@ -0,0 +1,41 @@ +# JSON tools with `nix develop` · 10 minutes + +Run from this directory: + +```sh +nix develop +printf '%s\n' "$REPORT_TITLE" +jq -r .title site.json +bash report.sh +jq -r -f render.jq site.json > index.html +exit +``` + +Expected: the hook prints suggested commands, `REPORT_TITLE` is `Gambiconf training`, the report lists the title and three topics, and `index.html` appears in your **working directory**. It uses the same fixture and renderer as the derivation exercise. + +Run a command without opening an interactive shell: + +```sh +nix develop --command bash report.sh +nix develop --command bash -c 'jq -r -f render.jq site.json > index.html' +``` + +`devshell.nix` uses `mkShellNoCC`: jq is the only extra tool, with no compiler, language package manager or background service. The supplied lock reuses the course's nixpkgs pin. First entry can download missing environment dependencies; subsequent entry reuses them. + +## Experiments + +- Change `REPORT_TITLE`, exit, and re-enter. Observe the new environment variable. +- Edit `site.json` and rerun the renderer. No store build is required to edit workspace files. +- Exit and inspect `command -v jq` and `REPORT_TITLE`. A pre-existing host jq can remain; leaving the shell removes its environment additions, not host-installed tools. +- Temporarily remove jq from `packages`. `nix develop` can inherit host tools, so a successful host-assisted command is not a sandboxed build. Compare with module 03's missing-dependency failure. + +## Package build environments + +From `03-derivations/01-gnu-hello/`, run `nix develop .#hello`. Unlike this tool-only shell, that environment contains a compiler and Hello's build dependencies. These should already be available after module 03. + +**Next:** optional [devenv comparison](../devenv-shell/README.md). + +--- +Sources: +- +- diff --git a/04-shells/plain-flake-shell/devshell.nix b/04-shells/plain-flake-shell/devshell.nix new file mode 100644 index 0000000..9006125 --- /dev/null +++ b/04-shells/plain-flake-shell/devshell.nix @@ -0,0 +1,9 @@ +{ pkgs }: + +pkgs.mkShellNoCC { + packages = [ pkgs.jq ]; + REPORT_TITLE = "Gambiconf training"; + shellHook = '' + printf 'Try: bash report.sh, or jq -r -f render.jq site.json\n' + ''; +} diff --git a/04-shells/plain-flake-shell/flake.lock b/04-shells/plain-flake-shell/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/04-shells/plain-flake-shell/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/04-shells/plain-flake-shell/flake.nix b/04-shells/plain-flake-shell/flake.nix new file mode 100644 index 0000000..be95e30 --- /dev/null +++ b/04-shells/plain-flake-shell/flake.nix @@ -0,0 +1,20 @@ +{ + description = "A lightweight JSON development environment"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + devShells = forAllSystems (system: { + default = import ./devshell.nix { pkgs = nixpkgs.legacyPackages.${system}; }; + }); + }; +} diff --git a/04-shells/plain-flake-shell/render.jq b/04-shells/plain-flake-shell/render.jq new file mode 100644 index 0000000..39c82db --- /dev/null +++ b/04-shells/plain-flake-shell/render.jq @@ -0,0 +1 @@ +"\n\n\n\(.title | @html)\n

\(.title | @html)

\n
    \(.topics | map("
  • \(. | @html)
  • ") | join(""))
\n" diff --git a/04-shells/plain-flake-shell/report.sh b/04-shells/plain-flake-shell/report.sh new file mode 100644 index 0000000..8e43971 --- /dev/null +++ b/04-shells/plain-flake-shell/report.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +jq --exit-status --raw-output '.title, (.topics[] | "- " + .)' site.json diff --git a/04-shells/plain-flake-shell/site.json b/04-shells/plain-flake-shell/site.json new file mode 100644 index 0000000..7158627 --- /dev/null +++ b/04-shells/plain-flake-shell/site.json @@ -0,0 +1,4 @@ +{ + "title": "Hello, Gambiconf!", + "topics": ["Derivations", "Shells", "NixOS"] +} From 0b0f7c84dcd4f7151647725a02cb7f475e52fdee Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Tue, 13 Oct 2026 12:18:34 -0400 Subject: [PATCH 4/8] feat: add flake composition and packaging workshops --- 05-flakes/README.md | 38 ++++++----- 05-flakes/composition/README.md | 47 +++++++++++++ 05-flakes/composition/flake.lock | 41 ++++++++++++ 05-flakes/composition/flake.nix | 58 ++++++++++++++++ 05-flakes/composition/site/flake.lock | 24 +++++++ 05-flakes/composition/site/flake.nix | 22 +++++++ 05-flakes/composition/site/render.jq | 1 + 05-flakes/composition/site/site.json | 4 ++ 05-flakes/composition/site/site.nix | 6 ++ 05-flakes/flake-schema.md | 6 +- 06-nixpkgs/README.md | 2 +- 06-nixpkgs/callpackage.md | 7 +- 06-nixpkgs/icat/README.md | 27 ++++++++ 06-nixpkgs/icat/flake.lock | 24 +++++++ 06-nixpkgs/icat/flake.nix | 26 ++++++++ 06-nixpkgs/icat/icat.nix | 31 +++++++++ 06-nixpkgs/icat/sample.ppm | 5 ++ 06-nixpkgs/packaging.md | 95 +++++++++------------------ 18 files changed, 377 insertions(+), 87 deletions(-) create mode 100644 05-flakes/composition/README.md create mode 100644 05-flakes/composition/flake.lock create mode 100644 05-flakes/composition/flake.nix create mode 100644 05-flakes/composition/site/flake.lock create mode 100644 05-flakes/composition/site/flake.nix create mode 100644 05-flakes/composition/site/render.jq create mode 100644 05-flakes/composition/site/site.json create mode 100644 05-flakes/composition/site/site.nix create mode 100644 06-nixpkgs/icat/README.md create mode 100644 06-nixpkgs/icat/flake.lock create mode 100644 06-nixpkgs/icat/flake.nix create mode 100644 06-nixpkgs/icat/icat.nix create mode 100644 06-nixpkgs/icat/sample.ppm diff --git a/05-flakes/README.md b/05-flakes/README.md index 8bc213c..45c4949 100644 --- a/05-flakes/README.md +++ b/05-flakes/README.md @@ -1,27 +1,31 @@ -# 05 · Flakes +# 05 · Flakes in depth -Flakes standardize **how Nix projects declare dependencies and expose results**. A `flake.nix` has `inputs` and `outputs`, and a `flake.lock` pins every input. The new `nix` CLI (`nix build`, `nix run`, `nix develop`) is built around them. Flakes are still *experimental*, but they are widely used. +You have used flakes since [module 00](../00-getting-started/README.md). Now maintain their dependency graph and compose their outputs. -**Prerequisites:** [04 · Shells](../04-shells/README.md) (for `nix develop`) and [01 · Language](../01-nix-language/README.md) +**Prerequisites:** [01 · Language](../01-nix-language/README.md), [03 · Derivations](../03-derivations/README.md), [04 · Development shells](../04-shells/README.md). -## Reading order -1. [flakes-concepts.md](flakes-concepts.md): what flakes solve, classic vs new CLI, pros, cons, and controversy -2. [flake-schema.md](flake-schema.md): `inputs`/`follows`, output conventions, and `flake.lock` -3. [flake-commands.md](flake-commands.md): flakeref syntax, `#attr` installables, and `nix flake …` +## Workshop -## Starter -```sh -mkdir hello-flake && cd hello-flake && git init -nix flake init # default template -git add flake.nix -nix flake show -nix build && ./result/bin/hello -``` +Work through the standalone [composition example](composition/README.md), 15–20 minutes: -**Next:** [06 · Nixpkgs](../06-nixpkgs/README.md): what's inside `nixpkgs.legacyPackages`, and how to package software. +1. Inspect the dependency graph with `nix flake metadata`. +2. Consume the bundled static-site flake through an input. +3. Use `follows` to share nixpkgs. +4. Build a package, run an app and execute a content check. +5. Change the page and repair a failing check. +6. Optionally update one input, inspect the lock diff and restore it. + +## Reference order + +1. [flake-schema.md](flake-schema.md): output conventions, systems, inputs and the lock graph. +2. [flake-commands.md](flake-commands.md): references, updates, archives and command selection. +3. [flakes-concepts.md](flakes-concepts.md): design trade-offs and the legacy interfaces you may encounter. + +Keep early flake wrappers thin. Package recipes remain ordinary functions; flake-parts is useful once output organization warrants another abstraction. + +**Next:** [06 · Nixpkgs](../06-nixpkgs/README.md): simplify explicit package arguments with `callPackage` and package software with dependencies. --- Sources: - - -- diff --git a/05-flakes/composition/README.md b/05-flakes/composition/README.md new file mode 100644 index 0000000..88c6dd5 --- /dev/null +++ b/05-flakes/composition/README.md @@ -0,0 +1,47 @@ +# Compose two flakes · 15–20 minutes + +This directory contains a consumer flake and a bundled `site/` flake copied from module 03. Copy the **whole directory** to keep the example standalone. Relative path inputs in this form require the course's Nix 2.34 or newer. + +```sh +nix flake metadata +nix flake show +nix build +nix run +nix flake check -L +``` + +Expected: metadata shows `site/nixpkgs` following `nixpkgs`; the default package contains the page, the default app prints it, and the `page` check verifies its heading. + +## Follow the graph + +Open `flake.nix`. `site.packages.${system}.default` consumes another flake's output. `site.inputs.nixpkgs.follows` selects the parent's package collection. The local `site/flake.lock` still lets the producer work independently; the consumer's lock governs its dependency graph when it is used as an input. + +The wrapper app contains an explicit store reference to the page. Changing its source rebuilds the dependent app and check. + +## Make a check fail + +Change the title in `site/site.json`, then run `nix flake check -L`. The content check fails. Update the expected heading in the consumer's check and run again. Restore both edits when finished. + +## Practice an input update + +Do this separately from the core offline workshop; it needs network access and may download a new package set: + +```sh +cp flake.lock flake.lock.before-update +nix flake update nixpkgs +diff -u flake.lock.before-update flake.lock +mv flake.lock.before-update flake.lock +``` + +Inspect the revision, hash and date before restoring the supplied pin. `nix flake lock` fills missing entries; it does not request a general dependency upgrade. + +## Systems and abstractions + +Inspect the three keys under `packages`, `apps` and `checks`. `forAllSystems` is `lib.genAttrs` applied to a list of system strings. It does not cross-compile packages; each system needs a matching builder. Cross-system **evaluation** is enough to inspect most of these outputs. + +Larger repositories can use flake-parts to organize these per-system outputs. The repository root is a real example; the teaching flakes stay small enough to read directly. + +--- +Sources: +- +- diff --git a/05-flakes/composition/flake.lock b/05-flakes/composition/flake.lock new file mode 100644 index 0000000..51f3872 --- /dev/null +++ b/05-flakes/composition/flake.lock @@ -0,0 +1,41 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs", + "site": "site" + } + }, + "site": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "path": "./site", + "type": "path" + }, + "original": { + "path": "./site", + "type": "path" + }, + "parent": [] + } + }, + "root": "root", + "version": 7 +} diff --git a/05-flakes/composition/flake.nix b/05-flakes/composition/flake.nix new file mode 100644 index 0000000..36e160c --- /dev/null +++ b/05-flakes/composition/flake.nix @@ -0,0 +1,58 @@ +{ + description = "Compose a site flake, share nixpkgs, and check the result"; + + inputs = { + nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + site = { + url = "path:./site"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = + { nixpkgs, site, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + packages = forAllSystems (system: { + default = site.packages.${system}.default; + }); + + apps = forAllSystems ( + system: + let + pkgs = nixpkgs.legacyPackages.${system}; + showSite = pkgs.writeShellApplication { + name = "show-site"; + runtimeInputs = [ pkgs.coreutils ]; + text = "cat ${site.packages.${system}.default}/index.html"; + }; + in + { + default = { + type = "app"; + program = "${showSite}/bin/show-site"; + meta.description = "Print the HTML supplied by the site input"; + }; + } + ); + + checks = forAllSystems ( + system: + let + pkgs = nixpkgs.legacyPackages.${system}; + in + { + page = pkgs.runCommand "check-training-page" { } '' + grep -F '

Hello, Gambiconf!

' ${site.packages.${system}.default}/index.html + touch "$out" + ''; + } + ); + }; +} diff --git a/05-flakes/composition/site/flake.lock b/05-flakes/composition/site/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/05-flakes/composition/site/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/05-flakes/composition/site/flake.nix b/05-flakes/composition/site/flake.nix new file mode 100644 index 0000000..7c167b3 --- /dev/null +++ b/05-flakes/composition/site/flake.nix @@ -0,0 +1,22 @@ +{ + description = "A bundled copy of the static-site exercise, usable independently"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + in + { + packages = forAllSystems (system: { + default = import ./site.nix { + inherit (nixpkgs.legacyPackages.${system}) runCommand jq; + }; + }); + }; +} diff --git a/05-flakes/composition/site/render.jq b/05-flakes/composition/site/render.jq new file mode 100644 index 0000000..39c82db --- /dev/null +++ b/05-flakes/composition/site/render.jq @@ -0,0 +1 @@ +"\n\n\n\(.title | @html)\n

\(.title | @html)

\n
    \(.topics | map("
  • \(. | @html)
  • ") | join(""))
\n" diff --git a/05-flakes/composition/site/site.json b/05-flakes/composition/site/site.json new file mode 100644 index 0000000..7158627 --- /dev/null +++ b/05-flakes/composition/site/site.json @@ -0,0 +1,4 @@ +{ + "title": "Hello, Gambiconf!", + "topics": ["Derivations", "Shells", "NixOS"] +} diff --git a/05-flakes/composition/site/site.nix b/05-flakes/composition/site/site.nix new file mode 100644 index 0000000..1c8e5b4 --- /dev/null +++ b/05-flakes/composition/site/site.nix @@ -0,0 +1,6 @@ +{ runCommand, jq }: + +runCommand "training-site" { nativeBuildInputs = [ jq ]; } '' + mkdir -p "$out" + jq --exit-status --raw-output --from-file ${./render.jq} ${./site.json} > "$out/index.html" +'' diff --git a/05-flakes/flake-schema.md b/05-flakes/flake-schema.md index 01b3f5a..764b371 100644 --- a/05-flakes/flake-schema.md +++ b/05-flakes/flake-schema.md @@ -3,6 +3,8 @@ > `flake.nix` is an attribute set with `description`, `inputs`, `outputs` (a function of the resolved inputs), and optionally `nixConfig`. ## Minimal flake + +You first used this shape in [module 00](../00-getting-started/README.md). The [composition exercise](composition/README.md) provides a complete locked multi-system version with a producer input and a check. ```nix { description = "My example flake"; @@ -29,7 +31,7 @@ ## Inputs ```nix inputs = { - nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05"; + nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; home-manager = { url = "github:nix-community/home-manager"; inputs.nixpkgs.follows = "nixpkgs"; # reuse OUR nixpkgs; avoids duplicates @@ -57,7 +59,7 @@ nixosModules. # NixOS modules nixosConfigurations. # nixos-rebuild --flake .#host templates. # nix flake init -t ``` -Flakes have no `system` argument, so you generate per-system outputs yourself, e.g. with `nixpkgs.lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] (system: …)`, `flake-utils`, or `flake-parts`. +Flakes have no `system` argument, so you generate per-system outputs yourself. The exercises use `nixpkgs.lib.genAttrs [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ] (system: …)`. The root maintenance flake uses flake-parts. `builtins.currentSystem` is not available in pure evaluation. ## `flake.lock` - JSON describing a **graph** of nodes: `root` → inputs → their inputs… diff --git a/06-nixpkgs/README.md b/06-nixpkgs/README.md index 4634780..9cda7c5 100644 --- a/06-nixpkgs/README.md +++ b/06-nixpkgs/README.md @@ -6,7 +6,7 @@ ## Reading order 1. [callpackage.md](callpackage.md): recipes as functions, automatic arguments, `callPackageWith` -2. [packaging.md](packaging.md): a guided walkthrough that packages `hello` and `icat`, with the typical errors +2. [packaging.md](packaging.md): refactor module 03's Hello wrapper, then build the optional standalone [icat flake](icat/README.md) and diagnose missing dependencies 3. [stdenv.md](stdenv.md): `mkDerivation`, phases and hooks, `nativeBuildInputs` vs `buildInputs`, `finalAttrs` 4. [overrides-and-overlays.md](overrides-and-overlays.md): `override` / `overrideAttrs` / overlays (`final` vs `prev`) diff --git a/06-nixpkgs/callpackage.md b/06-nixpkgs/callpackage.md index 0ee3d5d..e1770ab 100644 --- a/06-nixpkgs/callpackage.md +++ b/06-nixpkgs/callpackage.md @@ -11,15 +11,14 @@ writeShellScriptBin "hello" '' '' ``` ```nix -# default.nix -let pkgs = import { }; in +# Inside a flake's per-system package definition, with pkgs from its nixpkgs input: rec { hello = pkgs.callPackage ./hello.nix { audience = "people"; }; # explicit args win hello-folks = hello.override { audience = "folks"; }; # re-call with new args } ``` ```sh -nix-build -A hello-folks && ./result/bin/hello # Hello, folks! +nix run .#hello-folks # Hello, folks! ``` - For each function argument, `callPackage` passes `pkgs.` if it exists. The second argument supplies or overrides specific values. - Real-world use: `callPackage ./go-program.nix { buildGoModule = buildGo121Module; }` swaps the toolchain. @@ -29,7 +28,7 @@ nix-build -A hello-folks && ./result/bin/hello # Hello, folks! When packages depend on each other, don't thread them through by hand: ```nix let - pkgs = import { }; + pkgs = nixpkgs.legacyPackages.${system}; callPackage = pkgs.lib.callPackageWith (pkgs // packages); packages = { a = callPackage ./a.nix { }; diff --git a/06-nixpkgs/icat/README.md b/06-nixpkgs/icat/README.md new file mode 100644 index 0000000..9450ef2 --- /dev/null +++ b/06-nixpkgs/icat/README.md @@ -0,0 +1,27 @@ +# Package icat · optional, 15–20 minutes + +This Linux exercise adapts the second package in the [official nix.dev packaging tutorial](https://nix.dev/tutorials/packaging-existing-software.html#a-package-with-dependencies). On macOS, use the training guest. + +```sh +nix build -L +nix run -- sample.ppm +``` + +The build produces `result/bin/icat`. Run it in a UTF-8, color-capable terminal to display the tiny local image. Rendering depends on the terminal; the important packaging result is the installed executable. + +## From explicit application to `callPackage` + +In module 03 the flake explicitly supplied `stdenv` and `fetchurl`. Here `pkgs.callPackage ./icat.nix { }` fills function arguments by matching their names in `pkgs`. + +## Reproduce the packaging failures + +Start from the working recipe, making one temporary edit at a time: + +1. Remove `imlib2` from `buildInputs`; build and find the missing header. +2. Restore it; remove `libx11` to explore the X11 header dependency. +3. Restore both; remove `installPhase`. Compilation succeeds but `make install` has no target. +4. Restore the install phase and its pre/post hooks. Build again. + +The tutorial uses the older `xorg.libX11` name; this pin provides `libx11`. Fetching from GitHub hashes the unpacked source tree, unlike `fetchurl`'s archive-byte hash in Hello. + +This example downloads image and X11 libraries, so it is an extension rather than part of the small-download core or default VM preload. diff --git a/06-nixpkgs/icat/flake.lock b/06-nixpkgs/icat/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/06-nixpkgs/icat/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/06-nixpkgs/icat/flake.nix b/06-nixpkgs/icat/flake.nix new file mode 100644 index 0000000..794f7d9 --- /dev/null +++ b/06-nixpkgs/icat/flake.nix @@ -0,0 +1,26 @@ +{ + description = "Optional packaging exercise: icat from the nix.dev tutorial"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + ]; + in + { + packages = forAllSystems ( + system: + let + icat = nixpkgs.legacyPackages.${system}.callPackage ./icat.nix { }; + in + { + inherit icat; + default = icat; + } + ); + }; +} diff --git a/06-nixpkgs/icat/icat.nix b/06-nixpkgs/icat/icat.nix new file mode 100644 index 0000000..556a5e2 --- /dev/null +++ b/06-nixpkgs/icat/icat.nix @@ -0,0 +1,31 @@ +{ + stdenv, + fetchFromGitHub, + imlib2, + libx11, +}: + +stdenv.mkDerivation { + pname = "icat"; + version = "0.5"; + + src = fetchFromGitHub { + owner = "atextor"; + repo = "icat"; + rev = "v0.5"; + sha256 = "0wyy2ksxp95vnh71ybj1bbmqd5ggp13x3mk37pzr99ljs9awy8ka"; + }; + + buildInputs = [ + imlib2 + libx11 + ]; + + installPhase = '' + runHook preInstall + install -Dm755 icat "$out/bin/icat" + runHook postInstall + ''; + + meta.mainProgram = "icat"; +} diff --git a/06-nixpkgs/icat/sample.ppm b/06-nixpkgs/icat/sample.ppm new file mode 100644 index 0000000..5388b9e --- /dev/null +++ b/06-nixpkgs/icat/sample.ppm @@ -0,0 +1,5 @@ +P3 +4 2 +255 +255 0 0 0 255 0 0 0 255 255 255 0 +0 255 255 255 0 255 255 255 255 0 0 0 diff --git a/06-nixpkgs/packaging.md b/06-nixpkgs/packaging.md index 40c6036..05dd06c 100644 --- a/06-nixpkgs/packaging.md +++ b/06-nixpkgs/packaging.md @@ -1,79 +1,48 @@ -# Packaging Existing Software (walkthrough) +# Packaging existing software -> Package `hello` (autotools, no extra dependencies) and then `icat` (GitHub source, missing libraries, no `make install`). Along the way you'll see the typical errors and how to fix them. +You already compiled [GNU Hello](../03-derivations/01-gnu-hello/README.md) with a standalone flake. Its `hello.nix` is a function of `stdenv` and `fetchurl`; the flake supplies those arguments explicitly. + +## Simplify the wrapper + +Inside that flake's per-system definition, replace: -## 1. Skeleton + source ```nix -# hello.nix -{ stdenv, fetchzip }: -stdenv.mkDerivation { - pname = "hello"; - version = "2.12.1"; # without pname+version (or name): "derivation name missing" - src = fetchzip { - url = "https://ftp.gnu.org/gnu/hello/hello-2.12.1.tar.gz"; - sha256 = ""; # leave it empty → the error tells you the right hash - }; -} +hello = import ./hello.nix { + inherit (pkgs) stdenv fetchurl; +}; ``` + +with: + ```nix -# default.nix: supplies the arguments -let - nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-24.05"; - pkgs = import nixpkgs { config = {}; overlays = []; }; -in { - hello = pkgs.callPackage ./hello.nix { }; - icat = pkgs.callPackage ./icat.nix { }; -} +hello = pkgs.callPackage ./hello.nix { }; ``` -| Error | Meaning | Fix | -|---|---|---| -| `cannot evaluate a function that has an argument without a value ('stdenv')` | you ran `nix-build hello.nix` on a bare function | use `callPackage` in `default.nix`, then `nix-build -A hello` | -| `hash mismatch in fixed-output derivation … got: sha256-…` | expected, since the hash was empty | paste the `got:` hash | +Run `nix build` and `nix run`. The derivation is the same: dependency injection changed, not the package's build inputs. Continue with [callpackage.md](callpackage.md) for overrides. -`stdenv` recognizes autotools, so `hello` needs **no build instructions**: configure, make, and make install run automatically. +## A package with dependencies -## 2. A package with dependencies (`icat`) -```nix -{ stdenv, fetchFromGitHub, imlib2, xorg }: -stdenv.mkDerivation { - pname = "icat"; - version = "v0.5"; - src = fetchFromGitHub { - owner = "atextor"; repo = "icat"; rev = "v0.5"; - sha256 = "0wyy2ksxp95vnh71ybj1bbmqd5ggp13x3mk37pzr99ljs9awy8ka"; - }; - buildInputs = [ imlib2 xorg.libX11 ]; - installPhase = '' - runHook preInstall - mkdir -p $out/bin - cp icat $out/bin - runHook postInstall - ''; -} -``` -Get a hash up front with `nix-prefetch-url --unpack --type sha256`. You need `--unpack` because fetchers hash the *unpacked* tree. +The standalone [icat exercise](icat/README.md) is adapted from nix.dev. Its working recipe includes: -| Error | Fix | -|---|---| -| `fatal error: Imlib2.h: No such file` | add `imlib2` to the args and to `buildInputs` | -| `fatal error: X11/Xlib.h: No such file` | add `xorg` and use `xorg.libX11` (laziness means the rest of `xorg` is never evaluated) | -| `make: *** No rule to make target 'install'` | write your own `installPhase` that copies into `$out` | +- `fetchFromGitHub` with a fixed revision and unpacked-tree hash. +- `imlib2` and `libx11` in `buildInputs` for target headers/libraries. +- An explicit `installPhase` because the upstream Makefile has no install target. +- `runHook preInstall` and `runHook postInstall` around that custom phase. + +```sh +cd icat +nix build -L +nix run -- sample.ppm +``` -## Finding the right package -- , filtered by package set (e.g. `xorg`) -- Search the nixpkgs source: `rg -i "libx11 =" pkgs` in a shallow clone -- `nix-locate` (from `nix-index`) to find which package provides a file +Remove dependencies or the install phase one at a time, inspect the errors, then restore the recipe. This optional exercise has a larger closure than the core examples. -## Habits -- Always wrap custom phases in `runHook pre` / `runHook post` so others can hook in. -- `nix-build` with no `-A` builds every attribute, giving `result`, `result-2`, … -- Read failures with `nix log /nix/store/…drv`. +## Finding dependencies -## See also -- [stdenv.md](stdenv.md): phases and dependency types in depth -- [callpackage.md](callpackage.md) -- [../03-derivations/debugging.md](../03-derivations/debugging.md) +- Search for the package providing a missing library. +- Inspect the **pinned** nixpkgs source, since names change: this pin uses `libx11`, while the tutorial uses `xorg.libX11`. +- Use nix-index's `nix-locate` when you need to map a header or library filename to a package. +- Read `nix build -L` output or `nix log .#icat`; fix the first meaningful failure. --- Source: From 48e71cfa6f3ba98706f63c1d1b623ea90d60ae94 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Tue, 13 Oct 2026 13:12:00 -0400 Subject: [PATCH 5/8] feat: add NixOS web lab with fully offline training image Add the standalone 30-minute web-server lab (nginx serving the course static site, two prebuilt system versions, switch and rollback), share its guest settings with the training VMs, and preload the guest image: - register the preloaded closure in the guest Nix database at boot and copy a writable workspace for the gambi user - ship the exact locked nixpkgs source path so Nix >= 2.35 resolves the pin from the store with no download, and pin the guest to nixVersions.nix_2_35 accordingly - prebuild both workshop web systems plus the exercise packages and build environments instead of retaining the whole NixOS build closure - extend the image check to run the core exercises and the web-lab switch/rollback cycle with guest networking restricted, on both x86_64 and aarch64 images --- .github/workflows/qemu-image.yml | 5 +- 07-nixos/web-server/README.md | 78 +++++++++++++++++ 07-nixos/web-server/configuration.nix | 8 ++ 07-nixos/web-server/disk.nix | 22 +++++ 07-nixos/web-server/flake.lock | 24 ++++++ 07-nixos/web-server/flake.nix | 26 ++++++ 07-nixos/web-server/guest.nix | 50 +++++++++++ 07-nixos/web-server/render.jq | 1 + 07-nixos/web-server/site.json | 4 + 07-nixos/web-server/site.nix | 14 +++ 07-nixos/web-server/test.nix | 18 ++++ 07-nixos/web-server/web-server.nix | 14 +++ flake.nix | 1 + nixos/training-image.nix | 59 +++++++------ nixos/training-preload.nix | 118 ++++++++++++++++++++++++++ nixos/training-vm.nix | 34 +------- scripts/check-vm-image.sh | 17 +++- scripts/check-web-lab.sh | 31 +++++++ scripts/check-workshop.sh | 31 +++++++ scripts/run-vm.sh | 6 +- 20 files changed, 494 insertions(+), 67 deletions(-) create mode 100644 07-nixos/web-server/README.md create mode 100644 07-nixos/web-server/configuration.nix create mode 100644 07-nixos/web-server/disk.nix create mode 100644 07-nixos/web-server/flake.lock create mode 100644 07-nixos/web-server/flake.nix create mode 100644 07-nixos/web-server/guest.nix create mode 100644 07-nixos/web-server/render.jq create mode 100644 07-nixos/web-server/site.json create mode 100644 07-nixos/web-server/site.nix create mode 100644 07-nixos/web-server/test.nix create mode 100644 07-nixos/web-server/web-server.nix create mode 100644 nixos/training-preload.nix create mode 100644 scripts/check-web-lab.sh create mode 100644 scripts/check-workshop.sh diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml index ddeffd6..55562cf 100644 --- a/.github/workflows/qemu-image.yml +++ b/.github/workflows/qemu-image.yml @@ -45,11 +45,12 @@ jobs: gc-max-store-size-linux: 4G - name: Build image run: nix build .#qemu-image --out-link result - - name: Check image, boot, and SSH login + - name: Check image, offline exercises, and web rollback env: VM_ARCH: ${{ matrix.arch }} VM_BOOT_TIMEOUT: ${{ matrix.boot_timeout }} VM_SSH_TIMEOUT: ${{ matrix.ssh_timeout }} + VM_MEMORY: 2048 run: nix develop .#ci --command bash scripts/check-vm-image.sh result/nix-training-${{ matrix.arch }}.qcow2 - uses: actions/upload-artifact@v4 with: @@ -81,5 +82,5 @@ jobs: --repo "$GITHUB_REPOSITORY" \ --target "$GITHUB_SHA" \ --title "Nix training QEMU image" \ - --notes "Built and boot-tested from commit $GITHUB_SHA. Login: gambi / gambi. Nix flakes enabled." \ + --notes "Built and boot-tested from commit $GITHUB_SHA. Offline core exercises and web-server switch/rollback checked. Login: gambi / gambi. Nix flakes enabled; workspace: ~/nix-training." \ --latest diff --git a/07-nixos/web-server/README.md b/07-nixos/web-server/README.md new file mode 100644 index 0000000..c597823 --- /dev/null +++ b/07-nixos/web-server/README.md @@ -0,0 +1,78 @@ +# A web server, two generations, and rollback · 30 minutes + +Run this lab **inside the downloadable training guest**, logged in as `gambi`. It describes that guest's disk layout and credentials. It is not a configuration for your host. The directory is standalone and includes its own page recipe, fixture and lock. + +The prepared image provides `/home/gambi/nix-training`, nixpkgs, the core build environments, rebuild tooling and **both exact web-system versions** used below. Boot it before starting the clock. Existing images published before this lab need rebuilding or a new release. + +## 0–5 minutes: inspect the configuration + +```sh +cd ~/nix-training/07-nixos/web-server +host="web-lab-$(uname -m)" +nix flake show --offline +nix eval --offline ".#nixosConfigurations.$host.config.services.nginx.enable" +``` + +Read `configuration.nix` and its imports. `guest.nix` preserves access and the installed state version; `disk.nix` matches the image's partitions; `web-server.nix` adds nginx and a firewall rule. `root = site` passes a built store directory to a system service. + +## 5–15 minutes: activate version one + +```sh +sudo nixos-rebuild switch --offline --flake ".#$host" +systemctl status nginx --no-pager +curl --fail http://localhost/ +readlink /run/current-system +``` + +Expected: nginx is active and the response contains `

Hello, Gambiconf!

`. A system generation now refers to the page's immutable store path. + +Optional browser access from your host, using the SSH alias in the main README: + +```sh +ssh -N -L 8080:127.0.0.1:80 gambiconf +``` + +Open `http://localhost:8080`. This tunnels through the existing SSH forwarding; QEMU needs no additional port mapping. A localhost request or SSH tunnel does not test the guest's ingress firewall rule. + +## 15–22 minutes: change the page + +Edit only the title in `site.json` to `Version two` with `nano site.json`, then: + +```sh +sudo nixos-rebuild switch --offline --flake ".#$host" +curl --fail http://localhost/ +readlink /run/current-system +``` + +Expected: the new heading and a different system store path. Both specified states are prebuilt, so this exercise needs no downloads. The site recipe normalizes JSON before building: changing whitespace in your editor does not invalidate the prepared version. Other titles or configuration changes can require additional build tools; warm those separately for an extended demo. + +## 22–27 minutes: roll back + +```sh +sudo nixos-rebuild switch --rollback --flake ".#$host" +curl --fail http://localhost/ +readlink /run/current-system +``` + +Expected: version one's heading and system path return. Keep the two switches adjacent so the previous generation is version one. The flake reference also lets `nixos-rebuild` resolve its own tool from the pin, without falling back to a legacy channel lookup. + +## 27–30 minutes: explain what changed + +- The system generation selects a page, nginx configuration and service definitions together. +- The site is generated during a build, not at service startup. +- Rollback did **not** undo `site.json` in the workspace or restore arbitrary mutable service data. A subsequent rebuild still uses the edited title. +- `system.stateVersion` is compatibility configuration, not the nixpkgs update mechanism. + +Restore the fixture before repeating the exercise. Do not garbage-collect the preloaded workshop paths while using the image. `make run` discards the guest session on exit. + +## Troubleshooting + +- Missing `nixos-rebuild` or workspace: use the updated training image. +- Missing offline dependency: confirm you kept the supplied lock and use the current image. Updating inputs requires downloading another closure. +- Failed rebuild: inspect `--show-trace -L` output; activation has not necessarily happened. Compare with `systemctl status nginx` and `journalctl -u nginx`. +- Running on macOS: perform the system switch in the guest, not on the host. Building `system.build.vm` on a Linux builder is an optional instructor workflow. + +--- +Sources: +- +- diff --git a/07-nixos/web-server/configuration.nix b/07-nixos/web-server/configuration.nix new file mode 100644 index 0000000..c6ca9ba --- /dev/null +++ b/07-nixos/web-server/configuration.nix @@ -0,0 +1,8 @@ +{ ... }: +{ + imports = [ + ./guest.nix + ./disk.nix + ./web-server.nix + ]; +} diff --git a/07-nixos/web-server/disk.nix b/07-nixos/web-server/disk.nix new file mode 100644 index 0000000..804e85d --- /dev/null +++ b/07-nixos/web-server/disk.nix @@ -0,0 +1,22 @@ +{ ... }: +{ + # Match the downloadable training image's existing UEFI/ext4 layout. + boot.loader.systemd-boot.enable = true; + boot.growPartition = true; + boot.initrd.availableKernelModules = [ + "virtio_pci" + "virtio_blk" + ]; + + fileSystems = { + "/" = { + device = "/dev/disk/by-label/nixos"; + autoResize = true; + fsType = "ext4"; + }; + "/boot" = { + device = "/dev/disk/by-label/ESP"; + fsType = "vfat"; + }; + }; +} diff --git a/07-nixos/web-server/flake.lock b/07-nixos/web-server/flake.lock new file mode 100644 index 0000000..0ccb16f --- /dev/null +++ b/07-nixos/web-server/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/07-nixos/web-server/flake.nix b/07-nixos/web-server/flake.nix new file mode 100644 index 0000000..a3b46d1 --- /dev/null +++ b/07-nixos/web-server/flake.nix @@ -0,0 +1,26 @@ +{ + description = "A standalone NixOS web server for the training guest"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + outputs = + { nixpkgs, ... }: + let + mkLab = + system: + nixpkgs.lib.nixosSystem { + inherit system; + modules = [ ./configuration.nix ]; + }; + in + { + nixosConfigurations = { + web-lab-x86_64 = mkLab "x86_64-linux"; + web-lab-aarch64 = mkLab "aarch64-linux"; + }; + + checks = nixpkgs.lib.genAttrs [ "x86_64-linux" "aarch64-linux" ] (system: { + web = nixpkgs.legacyPackages.${system}.testers.runNixOSTest (import ./test.nix); + }); + }; +} diff --git a/07-nixos/web-server/guest.nix b/07-nixos/web-server/guest.nix new file mode 100644 index 0000000..3083812 --- /dev/null +++ b/07-nixos/web-server/guest.nix @@ -0,0 +1,50 @@ +{ modulesPath, pkgs, ... }: +{ + imports = [ (modulesPath + "/profiles/minimal.nix") ]; + + boot.kernelParams = [ + "console=tty0" + (if pkgs.stdenv.hostPlatform.isAarch64 then "console=ttyAMA0,115200" else "console=ttyS0,115200n8") + ]; + + networking.hostName = "nix-training"; + hardware.enableRedistributableFirmware = false; + + # Nix >= 2.35 marks locked inputs final and reuses their store paths when + # already valid, so the preloaded pin evaluates without re-fetching the + # channel tarball. Older Nix always downloads it, defeating the offline + # preloaded image. + nix.package = pkgs.nixVersions.nix_2_35 or pkgs.nixVersions.latest; + nix.settings.experimental-features = [ + "nix-command" + "flakes" + ]; + # The lock supplies nixpkgs; the guest does not need a registry or NIX_PATH. + nixpkgs.flake.setNixPath = false; + nixpkgs.flake.setFlakeRegistry = false; + + services.openssh = { + enable = true; + settings = { + PasswordAuthentication = true; + PermitRootLogin = "no"; + }; + }; + + users.users.gambi = { + isNormalUser = true; + extraGroups = [ "wheel" ]; + # Disposable training guest; do not reuse this password on a real host. + initialPassword = "gambi"; + }; + + system.disableInstallerTools = true; + system.tools.nixos-rebuild.enable = true; + environment.systemPackages = [ + pkgs.curl + pkgs.jq + pkgs.nano + ]; + + system.stateVersion = "25.11"; +} diff --git a/07-nixos/web-server/render.jq b/07-nixos/web-server/render.jq new file mode 100644 index 0000000..39c82db --- /dev/null +++ b/07-nixos/web-server/render.jq @@ -0,0 +1 @@ +"\n\n\n\(.title | @html)\n

\(.title | @html)

\n
    \(.topics | map("
  • \(. | @html)
  • ") | join(""))
\n" diff --git a/07-nixos/web-server/site.json b/07-nixos/web-server/site.json new file mode 100644 index 0000000..7158627 --- /dev/null +++ b/07-nixos/web-server/site.json @@ -0,0 +1,4 @@ +{ + "title": "Hello, Gambiconf!", + "topics": ["Derivations", "Shells", "NixOS"] +} diff --git a/07-nixos/web-server/site.nix b/07-nixos/web-server/site.nix new file mode 100644 index 0000000..db63668 --- /dev/null +++ b/07-nixos/web-server/site.nix @@ -0,0 +1,14 @@ +{ + runCommand, + jq, + data ? builtins.fromJSON (builtins.readFile ./site.json), +}: + +let + # Ignore JSON whitespace so an editor and jq produce the same build input. + fixture = builtins.toFile "site.json" (builtins.toJSON data); +in +runCommand "training-site" { nativeBuildInputs = [ jq ]; } '' + mkdir -p "$out" + jq --exit-status --raw-output --from-file ${./render.jq} ${fixture} > "$out/index.html" +'' diff --git a/07-nixos/web-server/test.nix b/07-nixos/web-server/test.nix new file mode 100644 index 0000000..1c9628d --- /dev/null +++ b/07-nixos/web-server/test.nix @@ -0,0 +1,18 @@ +{ + name = "training-web-server"; + nodes = { + server = { ... }: { + imports = [ ./web-server.nix ]; + }; + client = { pkgs, ... }: { + environment.systemPackages = [ pkgs.curl ]; + }; + }; + testScript = '' + start_all() + server.wait_for_unit("nginx.service") + server.wait_for_open_port(80) + client.wait_for_unit("network.target") + client.wait_until_succeeds("curl --fail --silent --show-error --max-time 5 http://server/ | grep -F '

Hello, Gambiconf!

'") + ''; +} diff --git a/07-nixos/web-server/web-server.nix b/07-nixos/web-server/web-server.nix new file mode 100644 index 0000000..bbf5088 --- /dev/null +++ b/07-nixos/web-server/web-server.nix @@ -0,0 +1,14 @@ +{ pkgs, ... }: +let + site = import ./site.nix { inherit (pkgs) runCommand jq; }; +in +{ + services.nginx = { + enable = true; + virtualHosts.training = { + default = true; + root = site; + }; + }; + networking.firewall.allowedTCPPorts = [ 80 ]; +} diff --git a/flake.nix b/flake.nix index c1438fb..3053747 100644 --- a/flake.nix +++ b/flake.nix @@ -37,6 +37,7 @@ system: extraModules: nixpkgs.lib.nixosSystem { inherit system; + specialArgs = { inherit nixpkgs; }; modules = [ ./nixos/training-vm.nix ] ++ extraModules; }; vmModule = nixpkgs + "/nixos/modules/virtualisation/qemu-vm.nix"; diff --git a/nixos/training-image.nix b/nixos/training-image.nix index 41d4df9..3c3a81d 100644 --- a/nixos/training-image.nix +++ b/nixos/training-image.nix @@ -2,14 +2,35 @@ config, lib, modulesPath, + nixpkgs, pkgs, ... }: let inherit (pkgs.stdenv.hostPlatform) efiArch; + # The exact store path that a locked `tarball` input resolves to: the + # imported tree named "source". With Nix >= 2.35 in the guest, a valid + # path here lets flake evaluation reuse the preloaded pin with no + # download. Referencing `pkgs.path` through package-typed options is not + # enough: it gets re-imported under its basename, producing a + # differently-named copy that no lock file resolves to. + nixpkgsSource = builtins.path { + path = nixpkgs.outPath; + name = "source"; + }; + registration = pkgs.closureInfo { + rootPaths = [ + config.system.build.toplevel + nixpkgsSource + ]; + }; in { - imports = [ (modulesPath + "/image/repart.nix") ]; + imports = [ + (modulesPath + "/image/repart.nix") + ../07-nixos/web-server/disk.nix + ./training-preload.nix + ]; # Build the image with systemd-repart entirely in userspace, so no # KVM-capable builder (e.g. GitHub's ARM runners) is required. @@ -44,7 +65,13 @@ in }; }; root = { - storePaths = [ config.system.build.toplevel ]; + storePaths = [ + config.system.build.toplevel + nixpkgsSource + ]; + # Store files alone are not valid Nix paths in a fresh guest database. + # Keep this outside the system closure to avoid a self-reference. + contents."/etc/nix-training-registration".source = "${registration}/registration"; repartConfig = { Type = "root"; Format = "ext4"; @@ -69,32 +96,4 @@ in }) ); - boot.loader.systemd-boot.enable = true; - - boot.growPartition = true; - - fileSystems = { - "/" = { - device = "/dev/disk/by-label/nixos"; - autoResize = true; - fsType = "ext4"; - }; - "/boot" = { - device = "/dev/disk/by-label/ESP"; - fsType = "vfat"; - }; - }; - - # Do not embed the full nixpkgs source just to provide a local flake registry. - nixpkgs.flake.setNixPath = false; - nixpkgs.flake.setFlakeRegistry = false; - - # Students use the prebuilt guest; installer and rebuild commands needlessly - # pull Python and other large tools into its store closure. - system.disableInstallerTools = true; - - boot.initrd.availableKernelModules = [ - "virtio_pci" - "virtio_blk" - ]; } diff --git a/nixos/training-preload.nix b/nixos/training-preload.nix new file mode 100644 index 0000000..a69f1e3 --- /dev/null +++ b/nixos/training-preload.nix @@ -0,0 +1,118 @@ +{ + lib, + pkgs, + nixpkgs, + ... +}: +let + system = pkgs.stdenv.hostPlatform.system; + hello = import ../03-derivations/01-gnu-hello/hello.nix { + inherit (pkgs) stdenv fetchurl; + }; + # Building mkShell records its toolchain references in its output. Keeping + # only Hello's executable would lose the compiler needed for nix develop. + helloEnvironment = pkgs.mkShell { inputsFrom = [ hello ]; }; + jsonEnvironment = import ../04-shells/plain-flake-shell/devshell.nix { inherit pkgs; }; + greeting = import ../03-derivations/00-raw-derivation/greeting.nix { + inherit system; + inherit (pkgs) bash; + }; + site = import ../03-derivations/02-static-site/site.nix { inherit (pkgs) runCommand jq; }; + webSystem = nixpkgs.lib.nixosSystem { + inherit system; + modules = [ ../07-nixos/web-server/configuration.nix ]; + }; + # Prebuild both exact workshop states. This avoids retaining the entire + # NixOS build closure (compilers, bootstrap tools, and upstream sources). + webSystemV2 = webSystem.extendModules { + modules = [ + { + services.nginx.virtualHosts.training.root = lib.mkForce ( + import ../07-nixos/web-server/site.nix { + inherit (pkgs) runCommand jq; + data = (builtins.fromJSON (builtins.readFile ../07-nixos/web-server/site.json)) // { + title = "Version two"; + }; + } + ); + } + ]; + }; + trainingSource = lib.fileset.toSource { + root = ../.; + fileset = lib.fileset.unions [ + ../00-getting-started + ../01-nix-language + ../02-nix-store + ../03-derivations + ../04-shells + ../05-flakes + ../06-nixpkgs + ../07-nixos + ../08-declarative-infra + ../nixos + ../scripts + ../.github + ../.envrc + ../.gitignore + ../flake.nix + ../flake.lock + ../Makefile + ../LICENSE + ../README.md + ../README.pt-br.md + ]; + }; +in +{ + systemd.services.training-store-registration = { + description = "Register the preloaded store in the guest Nix database"; + wantedBy = [ "multi-user.target" ]; + before = [ + "nix-daemon.service" + "training-workspace.service" + ]; + unitConfig.ConditionPathExists = "/etc/nix-training-registration"; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + }; + script = '' + ${pkgs.nix}/bin/nix-store --store local --load-db < /etc/nix-training-registration + ''; + }; + systemd.services.nix-daemon.requires = [ "training-store-registration.service" ]; + + system.extraDependencies = [ + trainingSource + pkgs.hello + pkgs.bash + # nix develop selects bashInteractive's outputsToInstall, including man. + # Without this small output it tries rebuilding Bash on an offline guest. + pkgs.bashInteractive.man + hello + hello.src + helloEnvironment + jsonEnvironment + greeting + site + webSystem.config.system.build.toplevel + webSystemV2.config.system.build.toplevel + ]; + + # Copy once into a writable workspace. Rebuilds must not overwrite edits. + systemd.services.training-workspace = { + description = "Prepare the writable Nix training workspace"; + wantedBy = [ "multi-user.target" ]; + before = [ "sshd.service" ]; + requires = [ "training-store-registration.service" ]; + unitConfig.ConditionPathExists = "!/home/gambi/nix-training"; + serviceConfig.Type = "oneshot"; + script = '' + install -d -o gambi -g users /home/gambi + cp -R ${trainingSource} /home/gambi/nix-training + chmod -R u+w /home/gambi/nix-training + chown -R gambi:users /home/gambi/nix-training + ''; + }; +} diff --git a/nixos/training-vm.nix b/nixos/training-vm.nix index 29b504a..a1f17ea 100644 --- a/nixos/training-vm.nix +++ b/nixos/training-vm.nix @@ -1,33 +1,5 @@ -{ modulesPath, pkgs, ... }: +{ ... }: { - imports = [ (modulesPath + "/profiles/minimal.nix") ]; - - boot.kernelParams = [ - "console=tty0" - (if pkgs.stdenv.hostPlatform.isAarch64 then "console=ttyAMA0,115200" else "console=ttyS0,115200n8") - ]; - - networking.hostName = "nix-training"; - hardware.enableRedistributableFirmware = false; - - nix.settings.experimental-features = [ - "nix-command" - "flakes" - ]; - - services.openssh = { - enable = true; - settings = { - PasswordAuthentication = true; - PermitRootLogin = "no"; - }; - }; - - users.users.gambi = { - isNormalUser = true; - extraGroups = [ "wheel" ]; - initialPassword = "gambi"; - }; - - system.stateVersion = "25.11"; + # Share the guest settings with the independently usable NixOS lab. + imports = [ ../07-nixos/web-server/guest.nix ]; } diff --git a/scripts/check-vm-image.sh b/scripts/check-vm-image.sh index cfdef1c..37fbaab 100644 --- a/scripts/check-vm-image.sh +++ b/scripts/check-vm-image.sh @@ -9,6 +9,7 @@ qemu-img check -f qcow2 "$image" boot_log=$(mktemp) qemu_pid= +# shellcheck disable=SC2329 # Invoked by the EXIT trap. cleanup() { if [[ -n "$qemu_pid" ]]; then kill "$qemu_pid" 2>/dev/null || true @@ -18,7 +19,8 @@ cleanup() { } trap cleanup EXIT -VM_HEADLESS=1 VM_SSH_PORT="$ssh_port" bash scripts/run-vm.sh "$image" \ +# Keep the SSH forward but prohibit guest access to external download servers. +VM_HEADLESS=1 VM_RESTRICT_NETWORK=on VM_SSH_PORT="$ssh_port" bash scripts/run-vm.sh "$image" \ >"$boot_log" 2>&1 & qemu_pid=$! @@ -61,6 +63,19 @@ for ((attempt = 0; attempt < ssh_timeout; attempt++)); do if [[ $ssh_user == gambi ]] && [[ " $ssh_groups " == *" wheel "* ]] && [[ $ssh_uid == 0 ]] && [[ " $ssh_features " == *" nix-command "* ]] && [[ " $ssh_features " == *" flakes "* ]]; then echo "SSH password login, sudo access, and Nix flakes succeeded." + SSHPASS=gambi sshpass -e ssh \ + -F /dev/null \ + -o PreferredAuthentications=password \ + -o PubkeyAuthentication=no \ + -o StrictHostKeyChecking=no \ + -o UserKnownHostsFile=/dev/null \ + -p "$ssh_port" \ + gambi@127.0.0.1 \ + 'bash ~/nix-training/scripts/check-workshop.sh && printf "gambi\n" | sudo -S -p "" bash /home/gambi/nix-training/scripts/check-web-lab.sh' || { + echo "Offline workshop or web rollback checks failed." >&2 + exit 1 + } + echo "Offline workshop and web rollback checks succeeded." exit 0 fi echo "SSH login returned unexpected user, groups, sudo access, or Nix features: $ssh_output" >&2 diff --git a/scripts/check-web-lab.sh b/scripts/check-web-lab.sh new file mode 100644 index 0000000..aa29a0e --- /dev/null +++ b/scripts/check-web-lab.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +test "$(id -u)" = 0 +test "$(uname -n)" = nix-training +repo=${1:-/home/gambi/nix-training} +lab="$repo/07-nixos/web-server" +host="web-lab-$(uname -m)" +backup=$(mktemp) +cp "$lab/site.json" "$backup" +restore_fixture() { + cp "$backup" "$lab/site.json" + rm -f "$backup" "$lab/site.json.tmp" +} +trap restore_fixture EXIT + +nixos-rebuild switch --offline --flake "$lab#$host" +version_one=$(readlink /run/current-system) +curl --fail --silent http://localhost/ | grep -F '

Hello, Gambiconf!

' + +jq '.title = "Version two"' "$lab/site.json" > "$lab/site.json.tmp" +mv "$lab/site.json.tmp" "$lab/site.json" +nixos-rebuild switch --offline --flake "$lab#$host" +test "$(readlink /run/current-system)" != "$version_one" +curl --fail --silent http://localhost/ | grep -F '

Version two

' + +nixos-rebuild switch --rollback --flake "$lab#$host" +test "$(readlink /run/current-system)" = "$version_one" +curl --fail --silent http://localhost/ | grep -F '

Hello, Gambiconf!

' +test "$(jq -r .title "$lab/site.json")" = 'Version two' +echo 'Web lab switched twice and rolled back successfully.' diff --git a/scripts/check-workshop.sh b/scripts/check-workshop.sh new file mode 100644 index 0000000..ea9b528 --- /dev/null +++ b/scripts/check-workshop.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo=${1:-/home/gambi/nix-training} +build() { + nix build --offline --no-link --print-out-paths "$repo/$1" +} + +starter=$(build 00-getting-started) +test "$("$starter/bin/hello")" = 'Hello, world!' +greeting=$(build 03-derivations/00-raw-derivation) +test "$(<"$greeting")" = 'Hello from a derivation!' +hello=$(build 03-derivations/01-gnu-hello) +test "$("$hello/bin/hello" --greeting='Hello, Gambiconf!')" = 'Hello, Gambiconf!' +site=$(build 03-derivations/02-static-site) +grep -F '

Hello, Gambiconf!

' "$site/index.html" + +( + cd "$repo/04-shells/plain-flake-shell" + # shellcheck disable=SC2016 # Expand these variables inside the development shell. + nix develop --offline --command bash -c ' + test -z "${CC:-}" + test "$REPORT_TITLE" = "Gambiconf training" + bash report.sh + jq -r -f render.jq site.json + ' +) +nix develop --offline "$repo/03-derivations/01-gnu-hello#hello" \ + --command bash -c 'command -v cc && command -v make' + +echo 'Core package and development-shell exercises passed offline.' diff --git a/scripts/run-vm.sh b/scripts/run-vm.sh index 73647ae..3e9dbf5 100644 --- a/scripts/run-vm.sh +++ b/scripts/run-vm.sh @@ -20,7 +20,7 @@ esac qemu_args=( -m "$memory" - -nic "user,hostfwd=tcp:127.0.0.1:${ssh_port}-:22" + -nic "user,restrict=${VM_RESTRICT_NETWORK:-off},hostfwd=tcp:127.0.0.1:${ssh_port}-:22" -drive "file=$image,format=qcow2,if=virtio,snapshot=on" ) @@ -51,7 +51,7 @@ if [[ $arch == aarch64 ]]; then -cpu "$arm_cpu" -bios "${VM_FIRMWARE:-edk2-aarch64-code.fd}" ) - qemu=qemu-system-aarch64 + qemu="qemu-system-aarch64" else # QEMU's bundled x86_64 EDK2 image is too large for -bios, so attach it # as a read-only pflash device instead. @@ -64,7 +64,7 @@ else -machine "q35,accel=$accel" -drive "if=pflash,format=raw,readonly=on,file=$firmware" ) - qemu=qemu-system-x86_64 + qemu="qemu-system-x86_64" fi if [[ ${VM_HEADLESS:-0} == 1 ]]; then From 6d857ea0240715cfa89ebf951dd2465e12dc23bb Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Wed, 14 Oct 2026 10:11:57 -0400 Subject: [PATCH 6/8] docs: finish flake-first rework of NixOS and infra modules - rework module 07 around the web lab: build vs activate, VM entry points, and the two-machine integration test as an optional extension - rewrite module-system evaluation examples against nixosConfigurations instead of lookups - port module 08 to the flake workflow: disko as a flake input with follows, nixos-anywhere --flake, and flake-based rebuild/target-host commands; mark the Terraform walkthrough as historical reference - update both READMEs for the offline image guarantees, VM memory guidance, and the workspace preload --- 07-nixos/README.md | 42 +++++------ 07-nixos/configuration.md | 80 ++++++++------------ 07-nixos/module-system.md | 14 ++-- 07-nixos/vm-testing.md | 83 ++++++--------------- 08-declarative-infra/binary-cache-server.md | 7 +- 08-declarative-infra/remote-deployment.md | 56 ++++++++------ 08-declarative-infra/terraform.md | 9 ++- README.md | 8 +- README.pt-br.md | 4 +- 9 files changed, 131 insertions(+), 172 deletions(-) diff --git a/07-nixos/README.md b/07-nixos/README.md index 0939d60..755dc67 100644 --- a/07-nixos/README.md +++ b/07-nixos/README.md @@ -1,31 +1,27 @@ # 07 · NixOS -**NixOS** is a Linux distribution where the *entire system* (packages, `/etc`, services, users, bootloader) is built from one declarative Nix configuration. Every change is a new generation, so upgrades are atomic and rollbacks are one command (or one boot-menu entry) away. +NixOS applies the same dependency model to a system: packages, `/etc`, services, users and boot configuration. A flake exposes systems through `nixosConfigurations.`. -**Prerequisites:** [06 · Nixpkgs](../06-nixpkgs/README.md); [05 · Flakes](../05-flakes/README.md) is recommended +**Prerequisites:** [06 · Nixpkgs](../06-nixpkgs/README.md). Flakes have been the course interface since module 00. + +## Thirty-minute hands-on lab + +Use the standalone [web-server lab](web-server/README.md) inside the updated training image: + +1. Inspect its flake and imported modules. +2. Switch to a system serving the static page from module 03. +3. Change the page and switch again. +4. Roll back and observe the original page. + +The image preloads the core sources and tools and supplies `nixos-rebuild`. Boot with at least 2 GiB RAM before starting the lab (`make run VM_MEMORY=2048`). The core package/shell exercises and this switch/rollback workflow are checked offline by the image workflow. Optional devenv and icat extensions are not preloaded. ## Reading order -1. [configuration.md](configuration.md): `configuration.nix`, building and running it as a QEMU VM, `nixos-rebuild` -2. [module-system.md](module-system.md): options, types, merging, `mkIf`, submodules (the engine behind NixOS) -3. [vm-testing.md](vm-testing.md): multi-machine integration tests with `runNixOSTest` - -## Flake-based system (preview) -```nix -{ - inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05"; - outputs = { nixpkgs, ... }: { - nixosConfigurations.myhost = nixpkgs.lib.nixosSystem { - system = "x86_64-linux"; - modules = [ ./configuration.nix ]; - }; - }; -} -``` -```sh -nixos-rebuild build-vm --flake .#myhost && ./result/bin/run-myhost-vm -``` - -**Next:** [08 · Declarative Infrastructure](../08-declarative-infra/README.md): deploy these configurations to real machines. + +1. [configuration.md](configuration.md): system outputs, building versus activation, and VM entry points. +2. [module-system.md](module-system.md): options, types, merging and imports. +3. [vm-testing.md](vm-testing.md): an optional two-machine service test using the same web module. + +**Next:** [08 · Declarative infrastructure](../08-declarative-infra/README.md): deploy a flake-based configuration to a real target. --- Sources: diff --git a/07-nixos/configuration.md b/07-nixos/configuration.md index 22e01d1..8fee6de 100644 --- a/07-nixos/configuration.md +++ b/07-nixos/configuration.md @@ -1,65 +1,47 @@ -# NixOS Configuration & Virtual Machines +# System configuration and VMs -> A NixOS system is **one declarative configuration** (a module) covering packages, services, users, and boot. You can build it into a QEMU VM and try it without touching your machine. +The [complete web lab](web-server/README.md) is the primary example. Its flake exposes `web-lab-x86_64` and `web-lab-aarch64` with `nixpkgs.lib.nixosSystem` and imports `configuration.nix`. -## A minimal `configuration.nix` -```nix -{ config, pkgs, ... }: -{ - boot.loader.systemd-boot.enable = true; - boot.loader.efi.canTouchEfiVariables = true; +## Build, then activate - users.users.alice = { - isNormalUser = true; - extraGroups = [ "wheel" ]; # sudo - initialPassword = "test"; # demo only! use hashedPassword / SSH keys for real - }; +From the lab directory, on a matching Linux builder: - environment.systemPackages = with pkgs; [ cowsay lolcat ]; - - system.stateVersion = "24.05"; # set once at install; do NOT bump casually -} +```sh +host="web-lab-$(uname -m)" +nix eval ".#nixosConfigurations.$host.config.services.nginx.enable" +nix build ".#nixosConfigurations.$host.config.system.build.toplevel" ``` -The file is a **NixOS module**: a function taking `{ config, pkgs, lib, … }` and returning option definitions. See [module-system.md](module-system.md). -## Build & run as a VM -```sh -nix-build '' -A vm \ - -I nixpkgs=channel:nixos-24.05 \ - -I nixos-config=./configuration.nix +This builds a system closure without activating it. **Inside the training guest**, use: -QEMU_KERNEL_PARAMS=console=ttyS0 ./result/bin/run-nixos-vm -nographic; reset -# log in as alice/test … `sudo poweroff` to exit (or `sudo pkill qemu` from another terminal) +```sh +sudo nixos-rebuild switch --offline --flake ".#$host" +sudo nixos-rebuild switch --rollback --flake ".#$host" ``` -- `` is NixOS's entry point. `-A vm` picks the VM builder, and `-I nixos-config=` supplies your module. -- ⚠️ The VM keeps its state in **`nixos.qcow2`** in the current directory. Delete it after changing the config, or old state (like passwords) persists. -## Desktop VMs -```nix -services.xserver.enable = true; -services.xserver.displayManager.gdm.enable = true; -services.xserver.desktopManager.gnome.enable = true; # or: programs.sway.enable = true; -``` -Run it without `-nographic` to get a window. Sway may need a different display device: -```nix -imports = [ ]; -virtualisation.qemu.options = [ "-device virtio-vga" ]; -``` -Tip: `nixos-generate-config --dir ./` writes a starter config. +| Action | Effect | +|---|---| +| `build` | Build only | +| `test` | Activate temporarily without selecting a new boot default | +| `switch` | Activate and select the system generation for future boots | +| `boot` | Select a generation for the next boot, without activating it now | + +Rollback selects a previous system configuration; it does not restore arbitrary mutable application data or your working tree. + +## Build an interactive VM + +The repository root exposes separate VM configurations with QEMU's VM module and the same guest settings: -## On a real machine ```sh -sudo nixos-rebuild switch # build + activate + make boot default -sudo nixos-rebuild test | boot | build-vm # variants -sudo nixos-rebuild switch --flake .#myhost # from a flake's nixosConfigurations.myhost -sudo nixos-rebuild switch --rollback +nix build .#nixosConfigurations.training-vm.config.system.build.vm --out-link result-vm +QEMU_KERNEL_PARAMS=console=ttyS0 ./result-vm/bin/run-nix-training-vm -nographic ``` -Each rebuild creates a new **system generation**, the same profile mechanism as in [../02-nix-store/profiles-and-gc.md](../02-nix-store/profiles-and-gc.md). Old generations show up in the boot menu. -## See also -- [module-system.md](module-system.md) -- [vm-testing.md](vm-testing.md) -- Options search: +On ARM64 Linux use `training-vm-aarch64` and `console=ttyAMA0`. The launcher shares the host store and writes a persistent guest disk in the working directory. It is an instructor exploration tool; the downloadable qcow2 image supplies the standalone store and offline lab workspace. + +For the prepared image, follow the root README's `make run` workflow. It works with QEMU on macOS as well as Linux and discards guest changes on exit. Avoid nesting another VM inside the training guest during the timed lab. + +The lab's disk module is for the prepared guest's labels and UEFI layout. A real host needs its own hardware, disk and access configuration. Keep `system.stateVersion` at the installed compatibility baseline; update nixpkgs through the lock file. --- Source: diff --git a/07-nixos/module-system.md b/07-nixos/module-system.md index 1731c89..2d6e817 100644 --- a/07-nixos/module-system.md +++ b/07-nixos/module-system.md @@ -30,15 +30,17 @@ If a module has no `options`, you can drop the `config = { … }` wrapper and write the definitions at the top level. NixOS's `configuration.nix` does exactly this. ## Evaluating -```nix -# eval.nix -let pkgs = import { }; in -pkgs.lib.evalModules { modules = [ ./default.nix ]; } -``` + +Inspect the evaluated real modules from the web-lab directory: + ```sh -nix-instantiate --eval eval.nix -A config.scripts.output +host="web-lab-$(uname -m)" +nix eval ".#nixosConfigurations.$host.config.services.nginx.enable" +nix eval --raw ".#nixosConfigurations.$host.options.services.nginx.enable.type.description" ``` +The first reads a merged value; the second reads the declared type. For a standalone module experiment, use `nixpkgs.lib.evalModules { modules = [ ./example.nix ]; }` inside a flake's outputs function, with `lib` from the locked nixpkgs input. + ## Key ideas - **Type checking:** a bad definition fails with a precise error, e.g. `A definition for option 'scripts.output' is not of type 'strings concatenated with "\n"'`. - **Merging:** any module can define any option. How several definitions combine depends on the type: lists concatenate, `lines` join, attribute sets merge, and conflicting scalars are an error. diff --git a/07-nixos/vm-testing.md b/07-nixos/vm-testing.md index 1abf125..b807113 100644 --- a/07-nixos/vm-testing.md +++ b/07-nixos/vm-testing.md @@ -1,76 +1,39 @@ -# Integration Testing with NixOS VMs +# Integration testing with NixOS VMs -> `pkgs.testers.runNixOSTest` boots one or more NixOS VMs from declarative configs and drives them with a Python script. The tests are reproducible, cacheable, and CI-friendly (given KVM). +The web-server flake includes an optional **two-machine test**, separate from the thirty-minute hands-on lab. `testers.runNixOSTest` boots a server using the same `web-server.nix` module and a client that requests the page through the virtual network. -## Pattern -```nix -let - nixpkgs = fetchTarball "https://github.com/NixOS/nixpkgs/tarball/nixos-23.11"; - pkgs = import nixpkgs { config = {}; overlays = []; }; -in -pkgs.testers.runNixOSTest { - name = "minimal-test"; +From `web-server/`, on a matching Linux builder with KVM: - nodes.machine = { config, pkgs, ... }: { - users.users.alice = { - isNormalUser = true; - extraGroups = [ "wheel" ]; - packages = with pkgs; [ firefox tree ]; - }; - system.stateVersion = "23.11"; - }; - - testScript = '' - machine.wait_for_unit("default.target") - machine.succeed("su -- alice -c 'which firefox'") - machine.fail("su -- root -c 'which firefox'") - ''; -} -``` ```sh -nix-build minimal-test.nix +nix flake check -L ``` -- `name`: the test name -- `nodes.`: a NixOS module per VM. In Python, the node name becomes an object (`machine`, `server`, …). -- `testScript`: Python code with root access to every node. It can also be a function `{ nodes, ... }: ''…''`. -## Multi-machine example -```nix -nodes.server = { ... }: { - networking.firewall.allowedTCPPorts = [ 80 ]; - services.nginx = { enable = true; virtualHosts."server" = {}; }; -}; -nodes.client = { pkgs, ... }: { environment.systemPackages = [ pkgs.curl ]; }; -testScript = '' - server.wait_for_unit("default.target") - client.wait_for_unit("default.target") - client.succeed("curl http://server/ | grep -o \"Welcome to nginx!\"") -''; -``` -Nodes reach each other by name on a virtual network. +The complete [test.nix](web-server/test.nix) waits for nginx and port 80, then checks the actual HTML from the client. This exercises the service, document root and firewall together, rather than merely checking that a process exists. + +## Interactive driver + +On x86_64 Linux: -## Interactive debugging ```sh -$(nix-build -A driverInteractive minimal-test.nix)/bin/nixos-test-driver ->>> start_all() # or machine.start() ->>> test_script() # run the whole script ->>> machine.shell_interact() +nix build .#checks.x86_64-linux.web.driverInteractive --out-link result-driver +./result-driver/bin/nixos-test-driver ``` -## Re-running a passing test -Results are cached in the store, so an unchanged test won't run again. To force a re-run: -```sh -result=$(readlink -f ./result) rm ./result && nix-store --delete $result +Use `checks.aarch64-linux.web.driverInteractive` on ARM64 Linux. At the Python prompt: + +```python +start_all() +test_script() +server.shell_interact() ``` -(`nix-store --delete ./result` fails because the `result` symlink is itself a GC root.) -## Notes -- CI needs hardware virtualization (KVM). Many hosted runners don't have it, but there are workarounds. -- nixpkgs' own `nixos/tests/` directory is a large collection of examples. +Successful test derivations are cached. To rerun the same test, `nix build .#checks.x86_64-linux.web --rebuild -L` rebuilds the test output; changing its script also produces a new derivation. + +## Image acceptance checks + +The repository's image workflow additionally boots the **actual qcow2 image**, verifies login and sudo, runs the core package and shell exercises offline, switches to two versions of the web configuration, and rolls back. See `scripts/check-vm-image.sh`, `scripts/check-workshop.sh` and `scripts/check-web-lab.sh`. -## See also -- [configuration.md](configuration.md), [module-system.md](module-system.md) -- [../05-flakes/flake-schema.md](../05-flakes/flake-schema.md): expose tests as `checks..*` +These checks run outside the guest's interactive lesson. ARM CI without KVM uses QEMU emulation, so it can take longer than the native Linux integration test. --- Source: diff --git a/08-declarative-infra/binary-cache-server.md b/08-declarative-infra/binary-cache-server.md index a1d6da4..03ccf87 100644 --- a/08-declarative-infra/binary-cache-server.md +++ b/08-declarative-infra/binary-cache-server.md @@ -19,7 +19,7 @@ } ``` ```sh -nixos-rebuild switch --no-flake --target-host root@cache # nix-serve will crash-loop until the key exists +nixos-rebuild switch --flake .#cache --target-host root@cache # import binary-cache.nix in this host's modules ``` ## 2. Signing keys @@ -39,7 +39,10 @@ nix.settings = { ## 3. Verify ```sh curl http://cache/nix-cache-info # StoreDir / WantMassQuery / Priority -hash=$(nix-build '' -A pkgs.hello | awk -F/ '{print $4}' | awk -F- '{print $1}') +# On the cache host, from the starter exercise with its supplied lock: +path=$(nix build --no-link --print-out-paths) +store_name=${path##*/} +hash=${store_name%%-*} curl "http://cache/$hash.narinfo" | grep "Sig: " # must show your key name ``` diff --git a/08-declarative-infra/remote-deployment.md b/08-declarative-infra/remote-deployment.md index 4e98f3b..bc90e6e 100644 --- a/08-declarative-infra/remote-deployment.md +++ b/08-declarative-infra/remote-deployment.md @@ -8,25 +8,35 @@ - the local machine only needs Nix ## 1. Pinned tooling -```sh -nix-shell -p npins -npins init -npins add github nix-community disko -npins add github nix-community nixos-anywhere -``` + +Extend a copy of the starter flake, keeping its nixpkgs lock. Add disko as an input and expose both the target and a tool-only shell: + ```nix -# shell.nix -let - sources = import ./npins; - pkgs = import sources.nixpkgs {}; -in pkgs.mkShell { - nativeBuildInputs = with pkgs; [ npins nixos-anywhere nixos-rebuild ]; - shellHook = '' - export NIX_PATH="nixpkgs=${sources.nixpkgs}:nixos-config=$PWD/configuration.nix" - ''; +# flake.nix (x86_64 Linux target and deployment workstation) +{ + inputs = { + nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + disko.url = "github:nix-community/disko"; + disko.inputs.nixpkgs.follows = "nixpkgs"; + }; + outputs = { nixpkgs, disko, ... }: + let + system = "x86_64-linux"; + pkgs = nixpkgs.legacyPackages.${system}; + in { + nixosConfigurations.server = nixpkgs.lib.nixosSystem { + inherit system; + modules = [ disko.nixosModules.disko ./configuration.nix ]; + }; + devShells.${system}.default = pkgs.mkShellNoCC { + packages = [ pkgs.nixos-anywhere pkgs.nixos-rebuild ]; + }; + }; } ``` +Run `nix flake lock` to add disko without updating the existing nixpkgs entry, then `nix develop`. Keep the resulting lock. This is an online deployment extension, not part of the preloaded guest lab. On another architecture, select the appropriate target and deployment-shell systems separately. + ## 2. Declarative disk layout (`single-disk-layout.nix`) ```nix { ... }: { @@ -50,11 +60,10 @@ From this spec, disko generates **both** the partitioning script **and** the Nix ## 3. System config ```nix { modulesPath, ... }: -let diskDevice = "/dev/sda"; sources = import ./npins; in # check with: ssh target lsblk +let diskDevice = "/dev/sda"; in # replace after checking: ssh target lsblk { imports = [ (modulesPath + "/profiles/qemu-guest.nix") - (sources.disko + "/module.nix") ./single-disk-layout.nix ]; disko.devices.disk.main.device = diskDevice; @@ -68,17 +77,16 @@ let diskDevice = "/dev/sda"; sources = import ./npins; in # check with: ssh ta ## 4. Test, deploy, update ```sh # full install test in a VM -nix-build -E "((import {}).nixos [ ./configuration.nix ]).installTest" +nixos-anywhere --flake .#server --vm-test # first install: partitions, formats, installs, reboots -toplevel=$(nixos-rebuild build --no-flake) -diskoScript=$(nix-build -E "((import {}).nixos [ ./configuration.nix ]).diskoScript") -nixos-anywhere --store-paths "$diskoScript" "$toplevel" root@target-host +nix build .#nixosConfigurations.server.config.system.build.toplevel +nixos-anywhere --flake .#server --target-host root@target-host # (password auth: export SSH_PASS=…, then add --env-password) # later updates: no nixos-anywhere needed -npins update nixpkgs -nixos-rebuild switch --no-flake --target-host root@target-host +nix flake update nixpkgs +nixos-rebuild switch --flake .#server --target-host root@target-host ``` ## See also @@ -88,3 +96,5 @@ nixos-rebuild switch --no-flake --target-host root@target-host --- Source: + +Flake workflow: diff --git a/08-declarative-infra/terraform.md b/08-declarative-infra/terraform.md index 2d29021..5fdfc8f 100644 --- a/08-declarative-infra/terraform.md +++ b/08-declarative-infra/terraform.md @@ -1,10 +1,11 @@ # Deploying NixOS with Terraform -> Terraform provisions the cloud resources (here an AWS instance booted from a NixOS AMI). The `deploy_nixos` module then pushes your `configuration.nix` on every `terraform apply`. +> Terraform provisions cloud resources. Use the [flake deployment workflow](remote-deployment.md) for NixOS configuration updates. The older Terraform module walkthrough below is historical reference: its pinned provider/module versions and non-flake deployment entry point need adaptation before reuse. ## 1. Boot a NixOS instance ```sh -nix-shell -p terraform +# From the repository root, reuse the course's locked package collection. +NIXPKGS_ALLOW_UNFREE=1 nix shell --impure --inputs-from ./00-getting-started nixpkgs#terraform terraform login # Terraform Cloud as the state/lock backend (workspace execution mode: Local) ``` ```hcl @@ -43,8 +44,8 @@ terraform init && terraform apply ## 2. Deploy configuration changes ```nix # configuration.nix -{ config, lib, pkgs, ... }: { - imports = [ ]; +{ modulesPath, ... }: { + imports = [ (modulesPath + "/virtualisation/amazon-image.nix") ]; # add options here: https://search.nixos.org/options } ``` diff --git a/README.md b/README.md index e898a79..e96dbd8 100644 --- a/README.md +++ b/README.md @@ -61,12 +61,12 @@ To build the same image locally on an x86_64 Linux host (with Nix): nix build .#qemu-image ``` -The Makefile detects x86_64 or ARM64 hosts and provides the matching image, interactive QEMU boot, and automated boot, SSH, and sudo checks: +The Makefile detects x86_64 or ARM64 hosts and provides the matching image, interactive QEMU boot, and automated boot, SSH, offline core-exercise and web rollback checks: ```sh make image -make run -make test +make run VM_MEMORY=2048 +make test VM_MEMORY=2048 ``` On Linux, `make image` builds the matching NixOS image. On macOS, it downloads the matching image from the latest release; `make run` needs QEMU, while `make test` also needs Nix. `make run` prints the guest login (`gambi` / `gambi`), forwards SSH to `127.0.0.1:2222`, and discards guest changes on exit. `make test` uses port `2223`, so both can run at once. Override `VM_SSH_PORT`, `TEST_SSH_PORT`, or `VM_MEMORY` on the `make` command line if needed. QEMU boots the image with UEFI firmware on both architectures; set `VM_FIRMWARE` to a firmware file if QEMU cannot find `edk2-x86_64-code.fd` or `edk2-aarch64-code.fd` in its data directory. `make vm` builds the local VM launcher on Linux. @@ -86,7 +86,7 @@ Run a downloaded file directly with QEMU, or use `make run` to select the correc qemu-system-x86_64 -m 1024 -machine q35 -drive if=pflash,format=raw,readonly=on,file=/path/to/edk2-x86_64-code.fd -drive file=nix-training-x86_64.qcow2,format=qcow2,if=virtio -nic user,hostfwd=tcp:127.0.0.1:2222-:22 -nographic ``` -Log in on the console as `gambi` with password `gambi`, or connect with `ssh -p 2222 gambi@127.0.0.1`. The guest enables `nix-command` and `flakes`, so commands such as `nix flake show ` work inside it (remote flake inputs need network access). You can also add this to `~/.ssh/config`: +Log in on the console as `gambi` with password `gambi`, or connect with `ssh -p 2222 gambi@127.0.0.1`. The updated image creates a writable `~/nix-training` workspace and preloads the pinned nixpkgs source, core exercise tools, Hello's compiler environment and both specified web-lab system versions. Start with `cd ~/nix-training/00-getting-started`. Keep the supplied locks and use at least 2 GiB RAM for the NixOS lab; optional devenv and icat need additional downloads. The guest enables `nix-command` and `flakes`. You can also add this to `~/.ssh/config`: ``` Host gambiconf diff --git a/README.pt-br.md b/README.pt-br.md index 7bd4cf5..0fa1330 100644 --- a/README.pt-br.md +++ b/README.pt-br.md @@ -30,6 +30,8 @@ Os textos dos módulos estão em inglês. ## VM do treinamento -As [releases](https://github.com/PerplexSystems/nix-training/releases/latest) oferecem imagens qcow2 para x86_64 e ARM64. O comando `make run` seleciona a arquitetura, inicia a VM e encaminha SSH para `127.0.0.1:2222`. Usuário e senha: `gambi` / `gambi`. As alterações da VM são descartadas ao sair. +As [releases](https://github.com/PerplexSystems/nix-training/releases/latest) oferecem imagens qcow2 para x86_64 e ARM64. O comando `make run VM_MEMORY=2048` seleciona a arquitetura, inicia a VM com 2 GiB de RAM e encaminha SSH para `127.0.0.1:2222`. Usuário e senha: `gambi` / `gambi`. As alterações da VM são descartadas ao sair. + +A imagem atualizada inclui um diretório editável `~/nix-training`, o nixpkgs fixado, as dependências dos exercícios principais e as ferramentas de rebuild. Comece com `cd ~/nix-training/00-getting-started`. Os exemplos opcionais de devenv e icat exigem downloads adicionais. `make test VM_MEMORY=2048` verifica os exercícios principais offline e o ciclo de switch/rollback do servidor web. Consulte [Training VM](README.md#training-vm) para os comandos de construção, requisitos do QEMU e configuração de SSH. From 94e9b7a86050fc83032bd9a1e8b3cc5d2bd6899f Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Wed, 14 Oct 2026 11:19:26 -0400 Subject: [PATCH 7/8] fix: publish VM images without Actions artifacts --- .github/workflows/qemu-image.yml | 58 +++++++----- .gitignore | 3 + README.md | 2 +- README.pt-br.md | 2 + scripts/publish-vm-release.sh | 73 +++++++++++++++ tests/test_publish_vm_release.py | 152 +++++++++++++++++++++++++++++++ 6 files changed, 265 insertions(+), 25 deletions(-) create mode 100644 scripts/publish-vm-release.sh create mode 100644 tests/test_publish_vm_release.py diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml index 55562cf..68a9120 100644 --- a/.github/workflows/qemu-image.yml +++ b/.github/workflows/qemu-image.yml @@ -11,7 +11,26 @@ concurrency: cancel-in-progress: true jobs: + prepare: + if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') + runs-on: ubuntu-24.04 + permissions: + contents: write + outputs: + tag: ${{ steps.release.outputs.tag }} + steps: + - uses: actions/checkout@v6 + - name: Create draft release + id: release + env: + GH_TOKEN: ${{ github.token }} + run: bash scripts/publish-vm-release.sh prepare + build: + needs: prepare + # PRs and non-main manual runs validate images without creating a release. + # The status check allows builds to proceed when prepare was skipped. + if: ${{ !cancelled() && (needs.prepare.result == 'success' || needs.prepare.result == 'skipped') }} strategy: fail-fast: false matrix: @@ -28,9 +47,11 @@ jobs: ssh_timeout: 180 runs-on: ${{ matrix.runner }} permissions: - contents: read + contents: write steps: - uses: actions/checkout@v6 + - name: Test release publishing logic + run: python3 -m unittest discover -s tests -p 'test_publish_vm_release.py' -v - uses: cachix/install-nix-action@v31 - name: Enable unprivileged user namespaces run: | @@ -52,35 +73,24 @@ jobs: VM_SSH_TIMEOUT: ${{ matrix.ssh_timeout }} VM_MEMORY: 2048 run: nix develop .#ci --command bash scripts/check-vm-image.sh result/nix-training-${{ matrix.arch }}.qcow2 - - uses: actions/upload-artifact@v4 - with: - name: nix-training-${{ matrix.arch }} - path: result/nix-training-${{ matrix.arch }}.qcow2 - if-no-files-found: error - retention-days: 90 - compression-level: 0 + - name: Attach checked image to draft release + if: needs.prepare.result == 'success' + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ needs.prepare.outputs.tag }} + VM_ARCH: ${{ matrix.arch }} + run: bash scripts/publish-vm-release.sh upload "$RELEASE_TAG" "$VM_ARCH" "result/nix-training-$VM_ARCH.qcow2" publish: - if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') - needs: build + if: needs.prepare.result == 'success' + needs: [prepare, build] runs-on: ubuntu-24.04 permissions: contents: write - actions: read steps: - - uses: actions/download-artifact@v4 - with: - pattern: nix-training-* - path: image - merge-multiple: true + - uses: actions/checkout@v6 - name: Publish latest working image env: GH_TOKEN: ${{ github.token }} - run: | - gh release create "vm-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" \ - image/nix-training-*.qcow2 \ - --repo "$GITHUB_REPOSITORY" \ - --target "$GITHUB_SHA" \ - --title "Nix training QEMU image" \ - --notes "Built and boot-tested from commit $GITHUB_SHA. Offline core exercises and web-server switch/rollback checked. Login: gambi / gambi. Nix flakes enabled; workspace: ~/nix-training." \ - --latest + RELEASE_TAG: ${{ needs.prepare.outputs.tag }} + run: bash scripts/publish-vm-release.sh publish "$RELEASE_TAG" diff --git a/.gitignore b/.gitignore index 67443cf..798db5f 100644 --- a/.gitignore +++ b/.gitignore @@ -68,3 +68,6 @@ result-* # Writable development-environment state and rendered workspace pages .devenv/ /04-shells/*/index.html + +# Python regression-test bytecode +__pycache__/ diff --git a/README.md b/README.md index e96dbd8..9c41b55 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ Nix runs on Linux, macOS and even Windows [Through NixOS-WSL](https://github.com ## Training VM -Download the latest boot-tested [x86_64 or aarch64 qcow2 image](https://github.com/PerplexSystems/nix-training/releases/latest) from GitHub Releases. The [QEMU image workflow](https://github.com/PerplexSystems/nix-training/actions/workflows/qemu-image.yml) also provides both artifacts for each successful run (retained for up to 90 days). The latest release is updated only after both builds pass the image check and boot to a login prompt. +Download the latest boot-tested [x86_64 or aarch64 qcow2 image](https://github.com/PerplexSystems/nix-training/releases/latest) from GitHub Releases. The [QEMU image workflow](https://github.com/PerplexSystems/nix-training/actions/workflows/qemu-image.yml) builds and validates both architectures on pull requests. On `main`, checked images are attached directly to a run-specific draft release; only after both jobs succeed and both assets are complete is the release published and marked latest. This workflow does not use Actions artifact storage. Failed or cancelled publishing runs can leave an unpublished draft; failed-job reruns reuse it, while full reruns create a new draft for their attempt. To build the same image locally on an x86_64 Linux host (with Nix): diff --git a/README.pt-br.md b/README.pt-br.md index 0fa1330..db5e004 100644 --- a/README.pt-br.md +++ b/README.pt-br.md @@ -32,6 +32,8 @@ Os textos dos módulos estão em inglês. As [releases](https://github.com/PerplexSystems/nix-training/releases/latest) oferecem imagens qcow2 para x86_64 e ARM64. O comando `make run VM_MEMORY=2048` seleciona a arquitetura, inicia a VM com 2 GiB de RAM e encaminha SSH para `127.0.0.1:2222`. Usuário e senha: `gambi` / `gambi`. As alterações da VM são descartadas ao sair. +Pull requests constroem e validam as duas arquiteturas, sem enviar imagens para o armazenamento de artefatos do Actions. Na branch `main`, cada imagem validada é anexada diretamente a uma release em rascunho. A release só é publicada e marcada como mais recente quando os dois jobs passam e os dois arquivos estão completos. Execuções interrompidas podem deixar um rascunho não publicado; repetir os jobs que falharam reutiliza esse rascunho. + A imagem atualizada inclui um diretório editável `~/nix-training`, o nixpkgs fixado, as dependências dos exercícios principais e as ferramentas de rebuild. Comece com `cd ~/nix-training/00-getting-started`. Os exemplos opcionais de devenv e icat exigem downloads adicionais. `make test VM_MEMORY=2048` verifica os exercícios principais offline e o ciclo de switch/rollback do servidor web. Consulte [Training VM](README.md#training-vm) para os comandos de construção, requisitos do QEMU e configuração de SSH. diff --git a/scripts/publish-vm-release.sh b/scripts/publish-vm-release.sh new file mode 100644 index 0000000..2ee5a30 --- /dev/null +++ b/scripts/publish-vm-release.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +set -euo pipefail + +command=${1:?Usage: publish-vm-release.sh prepare | upload TAG ARCH IMAGE | publish TAG} +shift +repo=${GH_REPO:-${GITHUB_REPOSITORY:?Set GH_REPO or GITHUB_REPOSITORY}} +sha=${GITHUB_SHA:?Set GITHUB_SHA} + +load_release() { + release=$(gh release view "$tag" --repo "$repo" --json isDraft,targetCommitish,assets) + if ! jq --exit-status --arg sha "$sha" '.targetCommitish == $sha' <<< "$release" >/dev/null; then + echo "Release $tag does not target the checked commit $sha." >&2 + exit 1 + fi +} + +case "$command" in + prepare) + # Compute once and pass via job outputs. A failed-job rerun must reuse the + # original draft tag even though GITHUB_RUN_ATTEMPT has changed. + tag="vm-${GITHUB_RUN_ID:?Set GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT:?Set GITHUB_RUN_ATTEMPT}" + : "${GITHUB_OUTPUT:?Set GITHUB_OUTPUT}" + gh release create "$tag" \ + --repo "$repo" \ + --target "$sha" \ + --title "Nix training QEMU image" \ + --notes "Built and boot-tested from commit $sha. Offline core exercises and web-server switch/rollback checked. Login: gambi / gambi. Nix flakes enabled; workspace: ~/nix-training." \ + --draft + printf 'tag=%s\n' "$tag" >> "$GITHUB_OUTPUT" + ;; + upload) + tag=${1:?Set release tag} + arch=${2:?Set image architecture} + image=${3:?Set checked image path} + case "$arch" in + x86_64 | aarch64) ;; + *) echo "Unsupported image architecture: $arch" >&2; exit 1 ;; + esac + if [[ ! -s "$image" || ${image##*/} != "nix-training-$arch.qcow2" ]]; then + echo "Expected a nonempty nix-training-$arch.qcow2 image." >&2 + exit 1 + fi + load_release + if ! jq --exit-status '.isDraft == true' <<< "$release" >/dev/null; then + echo "Refusing to replace an asset in published release $tag." >&2 + exit 1 + fi + # Only draft assets may be replaced; this makes failed-job reruns safe. + gh release upload "$tag" "$image" --repo "$repo" --clobber + ;; + publish) + tag=${1:?Set release tag} + load_release + if ! jq --exit-status ' + (.assets | length) == 2 + and ([.assets[].name] | sort) == ["nix-training-aarch64.qcow2", "nix-training-x86_64.qcow2"] + and all(.assets[]; .state == "uploaded" and .size > 0) + ' <<< "$release" >/dev/null; then + echo "Release $tag must contain both complete, nonempty architecture images." >&2 + exit 1 + fi + if jq --exit-status '.isDraft == true' <<< "$release" >/dev/null; then + gh release edit "$tag" --repo "$repo" --draft=false --latest + else + # A retried finalization may find that its previous request succeeded. + echo "Release $tag is already published with both checked images." + fi + ;; + *) + echo "Unknown release command: $command" >&2 + exit 1 + ;; +esac diff --git a/tests/test_publish_vm_release.py b/tests/test_publish_vm_release.py new file mode 100644 index 0000000..7325040 --- /dev/null +++ b/tests/test_publish_vm_release.py @@ -0,0 +1,152 @@ +"""Exercise the release lifecycle against a fake gh CLI; never modify GitHub.""" + +import copy +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/publish-vm-release.sh" +SHA = "a" * 40 +TAG = "vm-123-1" + + +class PublishVmReleaseTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.calls_path = self.root / "calls.jsonl" + self.release_path = self.root / "release.json" + self.output_path = self.root / "output" + gh = self.root / "gh" + gh.write_text( + """#!/usr/bin/env python3 +import json +import os +from pathlib import Path +import sys + +args = sys.argv[1:] +with open(os.environ["MOCK_LOG"], "a") as calls: + calls.write(json.dumps(args) + "\\n") +if len(args) > 1 and args[1] == os.environ.get("MOCK_FAIL_COMMAND"): + sys.exit(1) +if args[:2] == ["release", "view"]: + print(Path(os.environ["MOCK_RELEASE"]).read_text()) +elif args[:2] not in (["release", "create"], ["release", "upload"], ["release", "edit"]): + sys.exit("Unexpected gh command") +""" + ) + gh.chmod(0o755) + self.env = os.environ | { + "PATH": str(self.root) + os.pathsep + os.environ["PATH"], + "GH_REPO": "PerplexSystems/nix-training", + "GH_TOKEN": "test-token", + "GITHUB_SHA": SHA, + "GITHUB_RUN_ID": "123", + "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_OUTPUT": str(self.output_path), + "MOCK_LOG": str(self.calls_path), + "MOCK_RELEASE": str(self.release_path), + "MOCK_FAIL_COMMAND": "", + } + self.release = { + "isDraft": True, + "targetCommitish": SHA, + "assets": [ + {"name": f"nix-training-{arch}.qcow2", "size": 10, "state": "uploaded"} + for arch in ["x86_64", "aarch64"] + ], + } + self.image = self.root / "nix-training-x86_64.qcow2" + self.image.write_bytes(b"checked image") + + def run_script(self, *args, success=True, release=None, **env): + self.release_path.write_text(json.dumps(self.release if release is None else release)) + self.calls_path.write_text("") + result = subprocess.run( + ["bash", str(SCRIPT), *map(str, args)], + env=self.env | env, + capture_output=True, + text=True, + ) + if success: + self.assertEqual(result.returncode, 0, result.stderr) + else: + self.assertNotEqual(result.returncode, 0, result.stdout) + return [json.loads(line) for line in self.calls_path.read_text().splitlines()] + + def test_prepare_creates_draft_and_exports_attempt_specific_tag(self): + calls = self.run_script("prepare") + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0][:3], ["release", "create", TAG]) + self.assertIn("--draft", calls[0]) + self.assertNotIn("--latest", calls[0]) + self.assertIn(SHA, calls[0]) + self.assertEqual(self.output_path.read_text(), f"tag={TAG}\n") + + def test_full_rerun_uses_a_new_draft(self): + calls = self.run_script("prepare", GITHUB_RUN_ATTEMPT="2") + self.assertEqual(calls[0][2], "vm-123-2") + + def test_failed_job_rerun_uploads_to_original_draft(self): + calls = self.run_script("upload", TAG, "x86_64", self.image, GITHUB_RUN_ATTEMPT="2") + self.assertEqual(calls[-1][:4], ["release", "upload", TAG, str(self.image)]) + self.assertIn("--clobber", calls[-1]) + self.assertFalse(any(call[1] == "edit" for call in calls)) + + def test_upload_refuses_published_release_or_wrong_commit(self): + for field, value in [("isDraft", False), ("targetCommitish", "b" * 40)]: + with self.subTest(field=field): + release = self.release | {field: value} + calls = self.run_script("upload", TAG, "x86_64", self.image, success=False, release=release) + self.assertFalse(any(call[1] == "upload" for call in calls)) + + def test_upload_requires_matching_nonempty_image(self): + empty = self.root / "empty/nix-training-x86_64.qcow2" + empty.parent.mkdir() + empty.touch() + for arch, image in [("unknown", self.image), ("aarch64", self.image), ("x86_64", empty)]: + with self.subTest(arch=arch, image=image): + self.assertEqual(self.run_script("upload", TAG, arch, image, success=False), []) + + def test_publish_promotes_complete_pair(self): + calls = self.run_script("publish", TAG) + self.assertEqual(calls[-1][:3], ["release", "edit", TAG]) + self.assertIn("--draft=false", calls[-1]) + self.assertIn("--latest", calls[-1]) + + def test_publish_rejects_missing_empty_pending_or_duplicate_assets(self): + variants = [] + for field, value in [("size", 0), ("state", "new"), ("name", "nix-training-x86_64.qcow2")]: + release = copy.deepcopy(self.release) + release["assets"][1][field] = value + variants.append(release) + variants.append(self.release | {"assets": self.release["assets"][:1]}) + for release in variants: + with self.subTest(assets=release["assets"]): + calls = self.run_script("publish", TAG, success=False, release=release) + self.assertFalse(any(call[1] == "edit" for call in calls)) + + def test_publish_rejects_wrong_commit(self): + calls = self.run_script("publish", TAG, success=False, release=self.release | {"targetCommitish": "b" * 40}) + self.assertFalse(any(call[1] == "edit" for call in calls)) + + def test_published_pair_is_an_idempotent_success(self): + calls = self.run_script("publish", TAG, release=self.release | {"isDraft": False}) + self.assertFalse(any(call[1] == "edit" for call in calls)) + + def test_github_failures_stop_publishing(self): + for command in ["view", "edit"]: + with self.subTest(command=command): + calls = self.run_script("publish", TAG, success=False, MOCK_FAIL_COMMAND=command) + if command == "view": + self.assertFalse(any(call[1] == "edit" for call in calls)) + + +if __name__ == "__main__": + unittest.main() From 0586c70e8bdbd99a3e6a621826d3f77366f83980 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Wed, 14 Oct 2026 12:43:09 -0400 Subject: [PATCH 8/8] fix: wait for web readiness in VM acceptance checks --- .github/workflows/qemu-image.yml | 4 +- 07-nixos/vm-testing.md | 2 + scripts/check-vm-image.sh | 6 +- scripts/check-web-lab.sh | 36 +++++++- scripts/lib/wait-for-http.sh | 45 ++++++++++ tests/test_web_readiness.py | 149 +++++++++++++++++++++++++++++++ 6 files changed, 234 insertions(+), 8 deletions(-) create mode 100644 scripts/lib/wait-for-http.sh create mode 100644 tests/test_web_readiness.py diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml index 68a9120..519d4eb 100644 --- a/.github/workflows/qemu-image.yml +++ b/.github/workflows/qemu-image.yml @@ -50,8 +50,8 @@ jobs: contents: write steps: - uses: actions/checkout@v6 - - name: Test release publishing logic - run: python3 -m unittest discover -s tests -p 'test_publish_vm_release.py' -v + - name: Test CI scripts + run: python3 -m unittest discover -s tests -p 'test_*.py' -v - uses: cachix/install-nix-action@v31 - name: Enable unprivileged user namespaces run: | diff --git a/07-nixos/vm-testing.md b/07-nixos/vm-testing.md index b807113..02e4809 100644 --- a/07-nixos/vm-testing.md +++ b/07-nixos/vm-testing.md @@ -35,5 +35,7 @@ The repository's image workflow additionally boots the **actual qcow2 image**, v These checks run outside the guest's interactive lesson. ARM CI without KVM uses QEMU emulation, so it can take longer than the native Linux integration test. +After each switch, image acceptance waits up to 120 seconds for the expected HTTP heading. An active nginx unit alone is not a readiness signal. A failed check reports its phase, command and exit status, the last HTTP response or curl error, nginx status/journal, and the VM console log. Persistent HTTP failures still fail the run; rebuild and generation assertions are not retried. + --- Source: diff --git a/scripts/check-vm-image.sh b/scripts/check-vm-image.sh index 37fbaab..3d1774a 100644 --- a/scripts/check-vm-image.sh +++ b/scripts/check-vm-image.sh @@ -72,8 +72,10 @@ for ((attempt = 0; attempt < ssh_timeout; attempt++)); do -p "$ssh_port" \ gambi@127.0.0.1 \ 'bash ~/nix-training/scripts/check-workshop.sh && printf "gambi\n" | sudo -S -p "" bash /home/gambi/nix-training/scripts/check-web-lab.sh' || { - echo "Offline workshop or web rollback checks failed." >&2 - exit 1 + status=$? + echo "Offline workshop or web rollback checks failed (SSH exit $status). VM console log:" >&2 + cat "$boot_log" >&2 + exit "$status" } echo "Offline workshop and web rollback checks succeeded." exit 0 diff --git a/scripts/check-web-lab.sh b/scripts/check-web-lab.sh index aa29a0e..f00900d 100644 --- a/scripts/check-web-lab.sh +++ b/scripts/check-web-lab.sh @@ -1,5 +1,23 @@ #!/usr/bin/env bash -set -euo pipefail +set -Eeuo pipefail + +script_dir=$(dirname "${BASH_SOURCE[0]}") +# shellcheck source=scripts/lib/wait-for-http.sh +source "$script_dir/lib/wait-for-http.sh" + +phase='initializing the web lab' +# shellcheck disable=SC2329 # Invoked by the ERR trap. +report_failure() { + local status=$1 line=$2 command=$3 + trap - ERR + printf 'Web lab failed while %s (line %s, exit %s): %s\n' "$phase" "$line" "$status" "$command" >&2 + echo 'Current system:' >&2 + readlink /run/current-system >&2 || true + systemctl status nginx.service --no-pager --full >&2 || true + journalctl -b -u nginx.service -n 80 --no-pager >&2 || true + exit "$status" +} +trap 'report_failure "$?" "$LINENO" "$BASH_COMMAND"' ERR test "$(id -u)" = 0 test "$(uname -n)" = nix-training @@ -14,18 +32,28 @@ restore_fixture() { } trap restore_fixture EXIT +phase='switching to version one' +printf 'Web lab: %s\n' "$phase" nixos-rebuild switch --offline --flake "$lab#$host" +phase='checking version one' version_one=$(readlink /run/current-system) -curl --fail --silent http://localhost/ | grep -F '

Hello, Gambiconf!

' +wait_for_http http://localhost/ '

Hello, Gambiconf!

' "${WEB_READY_TIMEOUT:-120}" +phase='preparing version two' jq '.title = "Version two"' "$lab/site.json" > "$lab/site.json.tmp" mv "$lab/site.json.tmp" "$lab/site.json" +phase='switching to version two' +printf 'Web lab: %s\n' "$phase" nixos-rebuild switch --offline --flake "$lab#$host" +phase='checking version two' test "$(readlink /run/current-system)" != "$version_one" -curl --fail --silent http://localhost/ | grep -F '

Version two

' +wait_for_http http://localhost/ '

Version two

' "${WEB_READY_TIMEOUT:-120}" +phase='rolling back to version one' +printf 'Web lab: %s\n' "$phase" nixos-rebuild switch --rollback --flake "$lab#$host" +phase='checking rollback' test "$(readlink /run/current-system)" = "$version_one" -curl --fail --silent http://localhost/ | grep -F '

Hello, Gambiconf!

' +wait_for_http http://localhost/ '

Hello, Gambiconf!

' "${WEB_READY_TIMEOUT:-120}" test "$(jq -r .title "$lab/site.json")" = 'Version two' echo 'Web lab switched twice and rolled back successfully.' diff --git a/scripts/lib/wait-for-http.sh b/scripts/lib/wait-for-http.sh new file mode 100644 index 0000000..8e1a164 --- /dev/null +++ b/scripts/lib/wait-for-http.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Wait for actual HTTP content, not just a systemd unit's active state. +# Zero timeout performs one bounded probe, useful for immediate assertions. +wait_for_http() { + local url=$1 expected=$2 timeout=${3:-120} + if [[ ! "$timeout" =~ ^[0-9]+$ ]]; then + echo "Invalid HTTP readiness timeout: $timeout" >&2 + return 1 + fi + + local deadline=$((SECONDS + timeout)) remaining request_timeout + local response='' curl_status=0 attempts=0 + while :; do + remaining=$((deadline - SECONDS)) + if ((attempts > 0 && remaining <= 0)); then + break + fi + request_timeout=$remaining + ((request_timeout > 10)) && request_timeout=10 + ((request_timeout < 1)) && request_timeout=1 + attempts=$((attempts + 1)) + if response=$(curl --fail --silent --show-error --noproxy '*' \ + --connect-timeout 5 --max-time "$request_timeout" "$url" 2>&1); then + curl_status=0 + if [[ "$response" == *"$expected"* ]]; then + printf '%s\n' "$response" + return 0 + fi + else + curl_status=$? + fi + + remaining=$((deadline - SECONDS)) + ((remaining <= 0)) && break + if ((remaining > 2)); then + sleep 2 + else + sleep "$remaining" + fi + done + + printf 'HTTP readiness failed after %s probe(s) (timeout %ss): %s\nExpected: %s\nLast curl exit status: %s\nLast response/error:\n%s\n' \ + "$attempts" "$timeout" "$url" "$expected" "$curl_status" "${response:0:4096}" >&2 + return 1 +} diff --git a/tests/test_web_readiness.py b/tests/test_web_readiness.py new file mode 100644 index 0000000..cb01be9 --- /dev/null +++ b/tests/test_web_readiness.py @@ -0,0 +1,149 @@ +"""Check bounded HTTP polling and failure diagnostics without booting a VM.""" + +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +HTTP_HELPER = ROOT / "scripts/lib/wait-for-http.sh" +WEB_CHECK = ROOT / "scripts/check-web-lab.sh" +HEADING = "

Version two

" + + +class WebReadinessTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.bin = self.root / "bin" + self.bin.mkdir() + self.responses = self.root / "responses.json" + self.calls = self.root / "curl-calls.jsonl" + self.write_command( + "curl", + """#!/usr/bin/env python3 +import json +import os +from pathlib import Path +import sys + +calls = Path(os.environ["MOCK_CURL_CALLS"]) +attempt = len(calls.read_text().splitlines()) if calls.exists() else 0 +with calls.open("a") as log: + log.write(json.dumps(sys.argv[1:]) + "\\n") +responses = json.loads(Path(os.environ["MOCK_RESPONSES"]).read_text()) +response = responses[min(attempt, len(responses) - 1)] +print(response.get("body", "")) +print(response.get("error", ""), file=sys.stderr) +sys.exit(response.get("status", 0)) +""", + ) + # Transient cases can retry immediately; timeout cases use one probe. + self.write_command("sleep", "#!/usr/bin/env bash\nexit 0\n") + self.env = os.environ | { + "PATH": str(self.bin) + os.pathsep + os.environ["PATH"], + "MOCK_RESPONSES": str(self.responses), + "MOCK_CURL_CALLS": str(self.calls), + } + + def write_command(self, name, text): + command = self.bin / name + command.write_text(text) + command.chmod(0o755) + + def probe(self, responses, timeout="5"): + self.responses.write_text(json.dumps(responses)) + result = subprocess.run( + [ + "bash", "-Eeuo", "pipefail", "-c", + 'source "$1"; wait_for_http http://localhost/ "$2" "$3"', + "_", str(HTTP_HELPER), HEADING, timeout, + ], + env=self.env, + capture_output=True, + text=True, + timeout=10, + ) + calls = [json.loads(line) for line in self.calls.read_text().splitlines()] if self.calls.exists() else [] + return result, calls + + def test_immediate_ready_page(self): + result, calls = self.probe([{"body": HEADING}], timeout="0") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(calls), 1) + self.assertIn(HEADING, result.stdout) + self.assertIn("--show-error", calls[0]) + self.assertIn("--max-time", calls[0]) + + def test_connection_refused_then_stale_content_then_ready(self): + result, calls = self.probe([ + {"status": 7, "error": "Connection refused"}, + {"body": "

Hello, Gambiconf!

"}, + {"body": HEADING}, + ]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(calls), 3) + self.assertIn(HEADING, result.stdout) + + def test_empty_response_is_not_ready(self): + result, calls = self.probe([{"body": ""}, {"body": HEADING}]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(calls), 2) + + def test_permanent_connection_failure_reports_last_error(self): + result, calls = self.probe([{"status": 7, "error": "Connection refused"}], timeout="0") + self.assertEqual(result.returncode, 1) + self.assertEqual(len(calls), 1) + self.assertIn("Last curl exit status: 7", result.stderr) + self.assertIn("Connection refused", result.stderr) + + def test_wrong_content_fails_even_with_successful_http_status(self): + result, calls = self.probe([{"body": "Wrong generation"}], timeout="0") + self.assertEqual(result.returncode, 1) + self.assertEqual(len(calls), 1) + self.assertIn(HEADING, result.stderr) + self.assertIn("Wrong generation", result.stderr) + self.assertIn("Last curl exit status: 0", result.stderr) + + def test_invalid_deadline_fails_before_request(self): + result, calls = self.probe([{"body": HEADING}], timeout="invalid") + self.assertNotEqual(result.returncode, 0) + self.assertEqual(calls, []) + self.assertIn("Invalid HTTP readiness timeout", result.stderr) + + def test_does_not_start_a_probe_after_deadline(self): + self.write_command("sleep", "#!/usr/bin/env python3\nimport time\ntime.sleep(1.1)\n") + result, calls = self.probe([{"body": "Stale page"}, {"body": HEADING}], timeout="1") + self.assertEqual(result.returncode, 1) + self.assertEqual(len(calls), 1) + + def test_diagnostics_preserve_rebuild_failure_and_fixture(self): + self.write_command("id", "#!/usr/bin/env bash\necho 0\n") + self.write_command("uname", '#!/usr/bin/env bash\ncase "$1" in -n) echo nix-training;; -m) echo aarch64;; esac\n') + self.write_command("nixos-rebuild", "#!/usr/bin/env bash\nexit 23\n") + self.write_command("readlink", "#!/usr/bin/env bash\necho /nix/store/example-system\n") + self.write_command("systemctl", "#!/usr/bin/env bash\necho MOCK_NGINX_STATUS\nexit 3\n") + self.write_command("journalctl", "#!/usr/bin/env bash\necho MOCK_NGINX_JOURNAL\nexit 1\n") + fixture = self.root / "07-nixos/web-server/site.json" + fixture.parent.mkdir(parents=True) + fixture.write_text('{"title": "Original fixture"}\n') + result = subprocess.run( + ["bash", str(WEB_CHECK), str(self.root)], + env=self.env, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 23, result.stderr) + self.assertIn("switching to version one", result.stderr) + self.assertIn("MOCK_NGINX_STATUS", result.stderr) + self.assertIn("MOCK_NGINX_JOURNAL", result.stderr) + self.assertEqual(fixture.read_text(), '{"title": "Original fixture"}\n') + + +if __name__ == "__main__": + unittest.main()