Miguel Carneiro

Nix - using multiple channels in a shell.nix file

This post is a public archival of a self-contained shell.nix file to use multiple channels of Nix. In this case the default and unstable channels.

Template:

# shell.nix
let
  unstable = import (fetchTarball https://nixos.org/channels/nixos-unstable/nixexprs.tar.xz) { };
in
{ nixpkgs ? import <nixpkgs> {} }:
with nixpkgs; mkShell {
  buildInputs = [
    packageFromTheDefaultChannelHere
    unstable.packageFromTheUnstableChannelHere
  ];
}

E.g. I needed kubectl 1.21.1 (from 21.05) and Terraform 1.0.6 (from unstable):

let
  unstable = import (fetchTarball https://nixos.org/channels/nixos-unstable/nixexprs.tar.xz) { };
in
{ nixpkgs ? import <nixpkgs> {} }:
with nixpkgs; mkShell {
  buildInputs = [
    kubectl
    unstable.terraform
  ];
  shellHook = ''
    export KUBECONFIG="`echo $(pwd)`/kubeconfig"
  '';
}

The shellHook is an extra to have kubectl ready using the kubeconfig file that is generated by the Terraform code.

Result:

[nix-shell:~/tmp/nix-example]$ which terraform
/nix/store/ya9w0sdja8d3d7vkjv2cbj6qjb70gdzs-terraform-1.0.6/bin/terraform

[nix-shell:~/tmp/nix-example]$ terraform version
Terraform v1.0.6
on linux_amd64

[nix-shell:~/tmp/nix-example]$ which kubectl
/nix/store/hjvsr2zgiz11n7dc3g7yp04qcxad9jrd-kubectl-1.21.1/bin/kubectl

[nix-shell:~/tmp/nix-example]$ kubectl version
Client Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.1", GitCommit:"5e58841cce77d4bc13713ad2b91fa0d961e69192", GitTreeState:"archive", BuildDate:"1980-01-01T00:00:00Z", GoVersion:"go1.16.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.1", GitCommit:"5e58841cce77d4bc13713ad2b91fa0d961e69192", GitTreeState:"clean", BuildDate:"2021-05-12T14:12:29Z", GoVersion:"go1.16.4", Compiler:"gc", Platform:"linux/amd64"}

Thank you Rui (our Head of Engineering at skeeled) for sharing this with me.

P.S. This page could be a TIL (Today I Learned) bit in a category like this one https://mrkaran.dev/tils/. When I do mine I will probably move it there.

Originally published at https://mig4ng.hashnode.dev/nix-using-multiple-channels-in-a-shellnix-file.


What should you do next?

Comment or give me feedback via email. Follow the site via RSS or Email.