Valentin Reis

Remote Nix shells

Page contents:

Instantiate a derivation, build it, copy its closure over and enter a nix-shell over ssh. This can be done using the following shell script:


Usage: <host> <nix-instantiate arguments>

#!/usr/bin/env sh

export NIX_SSHOPTS="source .profile" # Necessary for non-NixOS hosts.

host=$1;shift # The first argument should be the host.

#creating a derivation in the local store.
# the rest of the argument list is passed to nix-instantiate:
drv=$(nix-instantiate --quiet $@)

#building this derivation locally.
nix-store --realize $drv --quiet > /dev/null

#copying the derivation and its output to the host.
nix-copy-closure --include-outputs --to $host $drv

echo "entering a remote shell.
ssh -t $host "source .profile; nix-shell $drv"

Example 1

Entering the hello derivation’s environment:

./ user@host '<nixpkgs>' --attr hello

Example 2

Using an env.nix file that specifies an environment:

#file env.nix
{ pkgs ? import <nixpkgs> {}}:
with pkgs;
stdenv.mkDerivation rec {
  name = "exampleEnvironment";

  #These two lines are necessary to build a nix derivation with no source.
  installPhase = "mkdir $out";
  unpackPhase = "true";

  #The environment's content.
  buildInputs = [ hello ];
  VAR = "baz";
  shellHook = "whoami; hostname; echo $VAR; hello";



./ foo@bar env.nix
creating a derivation in the local store.
building this derivation locally.
copying the derivation and its output to the host.
entering a remote shell.
Hello, world!