Skip to content

Instantly share code, notes, and snippets.

@suhr
Last active January 31, 2024 11:49
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suhr/4bb1f8434d0622588b23f9fe13e79973 to your computer and use it in GitHub Desktop.
Save suhr/4bb1f8434d0622588b23f9fe13e79973 to your computer and use it in GitHub Desktop.

How to use Nix Flakes system wide

There are some articles you want to read first:

Nix Flakes is currently an experimental feature, so this tutorial assumes that you are using the unstable channel.

First, add the following to the system configuration:

{
  nix = {
    package = pkgs.nixUnstable;
    extraOptions = ''
      experimental-features = nix-command flakes
    '';
  };
}

Switch to the new system configuration using nixos-rebuild.

After that, create /etx/nixos/flake.nix with the following content:

{
  inputs = {
    nixpkgs.url = github:NixOS/nixpkgs-channels/nixos-unstable;
    # nur.url = github:nix-community/NUR;
  };

  outputs = { nixpkgs, nix, self, ... }@inputs: {
    nixosConfigurations.nixos = nixpkgs.lib.nixosSystem {
      system = "x86_64-linux";
      modules =
        [ (import ./configuration.nix) ];
      specialArgs = { inherit inputs; };
    };
  };
}

Run cd /etc/nixos ; nix flake update to create the /etc/nixos/flake.lock file. Now your system uses Flakes. Run nixos-rebuld switch to insure that everything works normaly.

How to rollback

Removing /etc/nixos/flake.nix with switch nixos-rebuild back to using /etc/configuration.nix directly.

Using flakes to manage user packages

Create the following flake:

{
  description = "A home flake";

  inputs = {
    system.url = "self";
  };

  outputs = { self, nixpkgs, system }: {
    packages.x86_64-linux = system.legacyPackages.x86_64-linux;

    defaultPackage.x86_64-linux = with self.packages.x86_64-linux; buildEnv {
      name = "home-env";
      paths = [ <package list> ];
    };
    legacyPackages.x86_64-linux = system.legacyPackages.x86_64-linux;
  };
}

Then install it with nix profile install ..

Usage

  • Upgrade the system: nixos-rebuild --recreate-lock-file
  • Find a package: nix search self «query»
  • Install package:
    • From the system flake: nix profile install self#«package name»
    • From nixpkgs master: nix profile install github:NixOS/nixpkgs/master#«package name»
  • Update all packages in the profile: nix profile update '.*'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment