• Stars
    star
    423
  • Rank 98,854 (Top 3 %)
  • Language
    Nix
  • License
    MIT License
  • Created about 6 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Spawns lightweight nixos vms in a shell

nixos-shell

  • Spawns a headless qemu virtual machines based on a vm.nix nixos module in the current working directory.
  • Mounts $HOME and the user's nix profile into the virtual machine
  • Provides console access in the same terminal window

Example vm.nix:

{ pkgs, ... }: {
  boot.kernelPackages = pkgs.linuxPackages_latest;
}

How to install

nixos-shell is available in nixpkgs.

Start a virtual machine

To start a vm use:

$ nixos-shell

In this case nixos-shell will read vm.nix in the current directory. Instead of vm.nix, nixos-shell also accepts other modules on the command line.

$ nixos-shell some-nix-module.nix

You can also start a vm from a flake's nixosConfigurations or nixosModules output using the --flake flag.

$ nixos-shell --flake github:Mic92/nixos-shell#vm-forward

This will run the vm-forward example.

Note: nixos-shell must be able to extend the specified system configuration with certain modules.

If your version of nixpkgs provides the extendModules function on system configurations, nixos-shell will use it to inject the required modules; no additional work on your part is needed.

If your version of nixpkgs does not provide extendModules, you must make your system configurations overridable with lib.makeOverridable to use them with nixos-shell:

{
 nixosConfigurations = let
   lib = nixpkgs.lib;
 in {
   vm = lib.makeOverridable lib.nixosSystem {
     # ...
   };
 };
}

Specifying a non-overridable system configuration will cause nixos-shell to abort with a non-zero exit status.

When using the --flake flag, if no attribute is given, nixos-shell tries the following flake output attributes:

  • packages.<system>.nixosConfigurations.<vm>
  • nixosConfigurations.<vm>
  • nixosModules.<vm>

If an attribute name is given, nixos-shell tries the following flake output attributes:

  • packages.<system>.nixosConfigurations.<name>
  • nixosConfigurations.<name>
  • nixosModules.<name>

Terminating the virtual machine

Type Ctrl-a x to exit the virtual machine.

You can also run the poweroff command in the virtual machine console:

$vm> poweroff

Or switch to qemu console with Ctrl-a c and type:

(qemu) quit

Port forwarding

To forward ports from the virtual machine to the host, use the virtualisation.forwardPorts NixOS option. See examples/vm-forward.nix where the ssh server running on port 22 in the virtual machine is made accessible through port 2222 on the host.

The same can be also achieved by using the QEMU_NET_OPTS environment variable.

$ QEMU_NET_OPTS="hostfwd=tcp::2222-:22" nixos-shell

SSH login

Your keys are used to enable passwordless login for the root user. At the moment only ~/.ssh/id_rsa.pub, ~/.ssh/id_ecdsa.pub and ~/.ssh/id_ed25519.pub are added automatically. Use users.users.root.openssh.authorizedKeys.keyFiles to add more.

Note: sshd is not started by default. It can be enabled by setting services.openssh.enable = true.

Bridge Network

QEMU is started with user mode network by default. To use bridge network instead, set virtualisation.qemu.networkingOptions to something like [ "-nic bridge,br=br0,model=virtio-net-pci,mac=11:11:11:11:11:11,helper=/run/wrappers/bin/qemu-bridge-helper" ]. /run/wrappers/bin/qemu-bridge-helper is a NixOS specific path for qemu-bridge-helper on other Linux distributions it will be different. QEMU needs to be installed on the host to get qemu-bridge-helper with setuid bit set - otherwise you will need to start VM as root. On NixOS this can be achieved using virtualisation.libvirtd.enable = true;

RAM

By default qemu will allow at most 500MB of RAM, this can be increased using virtualisation.memorySize (size in megabyte).

{ virtualisation.memorySize = 1024; }

CPUs

To increase the CPU count use virtualisation.cores (defaults to 1):

{ virtualisation.cores = 2; }

Hard drive

To increase the size of the virtual hard drive, i. e. to 20 GB (see virtualisation options at bottom, defaults to 512M):

{ virtualisation.diskSize = 20 * 1024; }

Notice that for this option to become effective you may also need to delete previous block device files created by qemu (nixos.qcow2).

Notice that changes in the nix store are written to an overlayfs backed by tmpfs rather than the block device that is configured by virtualisation.diskSize. This tmpfs can be disabled however by using:

{ virtualisation.writableStoreUseTmpfs = false; }

This option is recommend if you plan to use nixos-shell as a remote builder.

Graphics/Xserver

To use graphical applications, add the virtualisation.graphics NixOS option (see examples/vm-graphics.nix).

Firewall

By default for user's convenience nixos-shell does not enable a firewall. This can be overridden by:

{ networking.firewall.enable = true; }

Mounting physical disks

There does not exists any explicit options right now but one can use either the $QEMU_OPTS environment variable or set virtualisation.qemu.options to pass the right qemu command line flags:

{
  # /dev/sdc also needs to be read-writable by the user executing nixos-shell
  virtualisation.qemu.options = [ "-hdc" "/dev/sdc" ];
}

Boot with efi

{ virtualisation.qemu.options = [ "-bios" "${pkgs.OVMF.fd}/FV/OVMF.fd" ]; }

Shared folders

To mount anywhere inside the virtual machine, use the nixos-shell.mounts.extraMounts option.

{
  nixos-shell.mounts.extraMounts = {
    # simple USB stick sharing
    "/media" = /media;

    # override options for each mount
    "/var/www" = {
      target = ./src;
      cache = "none";
    };
  };
}

You can further configure the default mount settings:

{
  nixos-shell.mounts = {
    mountHome = false;
    mountNixProfile = false;
    cache = "none"; # default is "loose"
  };
}

Available cache modes are documented in the 9p kernel module.

Disable KVM

In many cloud environments KVM is not available and therefore nixos-shell will fail with:
CPU model 'host' requires KVM.
In newer versions of nixpkgs this has been fixed by falling back to emulation. In older version one can set the virtualisation.qemu.options or set the environment variable QEMU_OPTS:

export QEMU_OPTS="-cpu max"
nixos-shell

A full list of supported qemu cpus can be obtained by running qemu-kvm -cpu help.

Channels/NIX_PATH

By default VMs will have a NIX_PATH configured for nix channels but no channel are downloaded yet. To avoid having to download a nix-channel every time the VM is reset, you can use the following nixos configuration:

{...}: {
  nix.nixPath = [
    "nixpkgs=${pkgs.path}"
  ];
}

This will add the nixpkgs that is used for the VM in the NIX_PATH of login shell.

Embedding nixos-shell in your own nixos-configuration

Instead of using the cli, it's also possible to include the nixos-shell NixOS module in your own NixOS configuration.

Add this to your flake.nix:

{
  inputs.nixos-shell.url = "github:Mic92/nixos-shell";
}

And this to your nixos configuration defined in your flake:

{
  imports = [ inputs.nixos-shell.nixosModules.nixos-shell ];
}

Afterwards you can start your nixos configuration with nixos-shell with one of the two following variants:

For the pure version (doesn't set SHELL or mount /home):

nix run .#nixosConfigurations.<yourmachine>.config.system.build.nixos-shell

Or for a version closer to nixos-shell:

nix run .#nixosConfigurations.<yourmachine>.config.system.build.nixos-shell

More configuration

Have a look at the virtualisation options NixOS provides.

More Repositories

1

sops-nix

Atomic secret provisioning for NixOS based on sops
Nix
1,081
star
2

cntr

A container debugging tool based on FUSE
Rust
542
star
3

nix-ld

Run unpatched dynamic binaries on NixOS
C
422
star
4

nix-update

Swiss-knife for updating nix packages.
Python
369
star
5

python-mpd2

Python library which provides a client interface for the Music Player Daemon.
Python
342
star
6

nixpkgs-review

Review pull-requests on https://github.com/NixOS/nixpkgs
Python
327
star
7

dotfiles

My NixOS dotfiles
Nix
299
star
8

envfs

Fuse filesystem that returns symlinks to executables based on the PATH of the requesting process.
Rust
133
star
9

vmsh

Shell into a virtualized linux, with your own tools
Rust
116
star
10

nix-fast-build

Combine the power of nix-eval-jobs with nix-output-monitor to speed-up your evaluation and building process.
Python
105
star
11

mina-sidekiq

Tasks to deploy Sidekiq with mina.
Ruby
91
star
12

nix-build-uncached

A CI friendly wrapper around nix-build.
Go
72
star
13

zig.ko

Linux kernel module written in Zig
Makefile
70
star
14

nixos-aarch64-images

Build NixOS images for various ARM single computer boards
Python
49
star
15

x86_64-linux-cheatsheats

Plain files for syscalls, errnos, signals, registers and x86_64 instructions
Python
49
star
16

pry.py

pry.py - an interactive drop in shell for python, similar to binding.pry in ruby
Python
49
star
17

ssh-to-age

Convert SSH Ed25519 keys to age keys. This is useful for usage in sops-nix and sops
Go
47
star
18

buildbot-nix

A nixos module to make buildbot a proper Nix-CI.
Python
42
star
19

hue-ble-ctl

Control your Phillips Hue light bulb over bluetooth
Python
33
star
20

pythonix

Eval nix code from python
C++
32
star
21

awesome-dotfiles

Configuration files of the window manager awesome
Lua
28
star
22

nur-packages

My personal NUR repository
Nix
23
star
23

fast-flake-update

Update flake.lock with the latest commit of a local checkout
Python
22
star
24

flake-linter

Find duplicate dependencies in flakes
Python
18
star
25

ansible-lxc

Ansible Connection Plugin for lxc containers (https://linuxcontainers.org/)
Python
17
star
26

iana-etc

Build /etc/protocols and /etc/services files from IANA's Assigned Internet Protocol Numbers
Python
17
star
27

lognotify

log watcher for awesome wm
Lua
14
star
28

nix-sysdig

Wrapper to debug sysdig builds
Python
13
star
29

github-tags

sinatra app to generate rss feeds with the latest git tags of a project on github
Ruby
13
star
30

ssh-to-pgp

Convert SSH RSA keys to GPG keys
Go
11
star
31

whois42d

Whois server for the dn42 registry
Go
11
star
32

bing-gpt-server

HTML
9
star
33

utils

A set of lua modules I use in awesome wm.
Lua
9
star
34

stockholm

Mirror of https://git.thalheim.io/Mic92/stockholm/
Nix
9
star
35

valauncher

A fast dmenu-like gtk3 application launcher
CMake
8
star
36

dlopen-resolver

Python
7
star
37

openvpn-ddns

Maintain dns records for connecting openvpn clients
Ruby
7
star
38

flake-templates

Personal templates i like to use.
Nix
6
star
39

kvm-pirate

Attach to kvm-based VMs
Python
5
star
40

systemd-ta

http://c3d2.de/news/ta-systemd.html
JavaScript
4
star
41

nixos-test-example

Nix
4
star
42

nix-build-shell

Rust
4
star
43

dream2nix-home-assistant

Packaging experiments with dream2nix to package home-assistant with all dependencies.
Nix
4
star
44

robolab

Simulator for the course Robolab at TU Dresden
4
star
45

server-bookings

Rust
3
star
46

Algebra-I

Das inoffizielle Skript zur Vorlesung bei Prof. Schmidt
Ruby
3
star
47

nsattach

attach to linux namespaces
C
3
star
48

nixos-configuration

The content of this repo has been integrated into https://github.com/Mic92/dotfiles/
3
star
49

nix-fmt

abandoned in favor of https://github.com/orivej/go-nix and https://gitlab.com/jD91mZM2/rnix
OCaml
3
star
50

imap-notify

IMAP notifier using IMAP's NOTIFY SET
Python
3
star
51

docker-pid

Resolve container id/name to container's process id
Go
3
star
52

nftables

Mirror of netfilter/nftables
C
3
star
53

mpdtools

Usefull tools for MPD: mpdadd - Link and play files outside of the MPD directory to MPD. mpdmark - bookmark songs
Ruby
3
star
54

SWT_And_Programming

Programs/Stubs created during exercises at university.
Java
2
star
55

int3

Better debugger breakpoints
Python
2
star
56

vtune-nix

Vtune nix package
Nix
2
star
57

systemd-user-units

2
star
58

live-net-info

My adventures using the bubbletea framework.
Go
2
star
59

blog

Source of my blog
Shell
2
star
60

bors-gen-config

Generate bors.toml for github repositories
Python
2
star
61

themenabend-nixos

Folien und Code zum Themenabend รผber Nix/Nixos
JavaScript
2
star
62

lxc-machined-start

Integrate lxc container into machined
M4
2
star
63

company-tmux

emacs auto complete with content of tmux panes
Emacs Lisp
2
star
64

pgp-verify

Verify pgp signatures of files.
Go
2
star
65

build-system-koans

C
2
star
66

mpdstated

Auto restore recent position for each podcast in mpd.
Vala
2
star
67

container-pid

Rust crate to resolve a container names/ids to PID
Rust
2
star
68

bme680-mqtt

Publish BME680 sensor data to home-assistant via MQTT
Python
2
star
69

nixcon2023-nixos-anywhere

Presentation slides for NixCon 2023 presentation on nixos-anywhere
JavaScript
2
star
70

scripts

All my tiny scripts and stubs
Shell
1
star
71

lualdap

fork of https://git.zx2c4.com/lualdap/ with lua5.3 support
C
1
star
72

pcap-preload

Rust
1
star
73

mic92.github.com

1
star
74

keychron-keyboards

Configuration of my k6 pro keyboard
Nix
1
star
75

phd-website

HTML
1
star
76

ports

my freebsd ports
Makefile
1
star
77

drone-convert-nix

Go
1
star
78

webscraping-workshop

Folien und Code zum Webscraping workshop auf den Datenspuren 2015
JavaScript
1
star
79

qtile-config

Python
1
star
80

semeion

A DynDNS Server interface in Haskell and Yesod
Haskell
1
star
81

hadoop-exercise

MapReduce Assignment 2015 at System Engineering II (TU Dresden)
Java
1
star
82

xfstests-cntr

Fork of xfstests with support for cntr
Shell
1
star
83

fuidshift

Move Filesystem ownership into other subordinated uid ranges
Go
1
star
84

android-notifier

Automatically exported from code.google.com/p/android-notifier
Java
1
star
85

drone-nix-scheduler

Schedule nix jobsets in drone ci
Python
1
star
86

fft

FFT Implementation for Tensilica DSP Processors
C
1
star
87

arch-package-feed

bottle.py based project to provide a more advanced arch package feed.
Python
1
star
88

PKGBUILDs

My PKGBUILDs of Packages I maintain in Archlinux AUR
Shell
1
star
89

tracedump

System service to dump Intel processor trace + memory after a crash.
Python
1
star
90

Japanese-sum-solver

A solver for the logic game Japsum
JavaScript
1
star
91

clusterssh

wrapper arround go-ssh to execute commands in a cluster
Go
1
star