Giter VIP home page Giter VIP logo

nixos-shell's Introduction

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.

nixos-shell's People

Contributors

573 avatar baughn avatar brianmcgee avatar davhau avatar dermetfan avatar lassulus avatar matthewcroughan avatar mic92 avatar mic92-renovate[bot] avatar mkg20001 avatar mrvandalo avatar radvendii avatar shamrocklee avatar tomeon avatar uosis avatar welteki avatar zarelit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nixos-shell's Issues

Mounting host dirs when running Nixos-Shell with Flake

Hey,
I have this flake.nix to launch nixos-shell:

{
  description = "Spawns lightweight nixos vm in a shell";

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

  outputs = { self, nixpkgs, nixos-shell }: let
    pkgs = nixpkgs.legacyPackages.x86_64-linux;
    start =
      pkgs.writeShellScriptBin "start" ''
        set -e
        export QEMU_NET_OPTS="hostfwd=tcp::8080-:80,hostfwd=tcp::1433-:143,hostfwd=tcp::5877-:587"
        ${pkgs.nixos-shell}/bin/nixos-shell --flake .
       '';
  in {

    nixosConfigurations.vm = nixpkgs.lib.nixosSystem {
      system = "x86_64-linux";
      modules = [
        (import ./vm-nextcloud.nix)
        nixos-shell.nixosModules.nixos-shell
      ];
    };

    packages = { inherit start; };
    defaultPackage.x86_64-linux = start;

  };
}

This is great because now the VM itself is pinned to the version of nixpkgs.url defined in this flake.nix.

Inside vm-nextcloud,nix I have this part:

nixos-shell.mounts.extraMounts = {
  "/var/lib/nextcloud/cleanup" = {
     target = ./cleanup;
     cache = "none";
  };
};

But this fails because /var/lib/nextcloud/cleanup is a local path of the host and the Flake cannot access it. I tried to use the --impure flag on nixos-shell but that didn't work.

Best regards
Jonas

Example vm script does not work

Hey,
when I try to run the exampel VM like this vm.nix:

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

Now running NIX_PATH=nixpkgs=/home/onny/projects/nixpkgs nixos-shell vm.nix results in:

error: A definition for option `virtualisation.memorySize' is not of type `positive integer, meaning >0'. Definition values:
- In `/nix/store/z51q89m10qqqj7bkl5yhpx9k2q5w2vjv-nixos-shell-0.2.1/share/nixos-shell/nixos-shell.nix': "500M"
(use '--show-trace' to show detailed location information)

Can nixos-shell use a correct default value for memorySize so that it works withotu defining it manually?

Regards
Jonas

Add to nixpkgs?

Easy enough to install as-is but putting in nixpkgs would give it some visibility!

Nix search path entry does not exist

I'm getting the following error:

warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels/nixos' does not exist, ignorg
warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels' does not exist, ignoring
error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I), at /home/karel3

Any advice on how to use nix build inside the vm?

The option virtualisation.* does not exist

Hi, I'm fairly new to nixos so forgive me if the answer is obvious.

I have built a monorepo based on https://aldoborrero.com/posts/2023/01/15/setting-up-my-machines-nix-style/, basically flake-parts + mission-control + multiple nixos configurations.
I can run my nixos-configurations through nixos-shell just fine, but defining qemu config for port forwarding etc doesn't work.

The following works;

# flake.nix
{
inputs ={..}
outputs = inputs: inputs.flake-parts.lib.mkFlake { inherit inputs; } {
imports = [ ./host.nix ];
};
}

# host.nix
{self, inputs, lib, ...}:
{
flake.nixosConfiguration = {
machine = lib.nixosSystem {
modules = [ .. ];
};
};
}

nixos-shell --flake .#machine builds and runs the configuration as expected.

What doesn't work is adding qemu config to the machine attribute set, also creating a new machine with additional qemu config doesn't work either;

# host.nix
{self, inputs, lib, ...}:
{
flake.nixosConfiguration = {
machine = lib.nixosSystem {
modules = [ .. ];
};
# Below attribute is added to keep the nixos-shell specific settings separated from the machine config
vm-machine = lib.nixosSystem {
modules = [ .. ] ++ [({...}: {
virtualisation.forwardPorts = [{from = "host"; host.port = 6667; guest.port = 67;}];
})];
};
};
}

nixos-shell --flake .#vm-machine fails. I'm not sure at which build step exactly, but I do understand that the nixos module for qemu should be included (because of /share/modules/nixos-shell.nix) but isn't.
I guess it has to do something with lib and the way flake-parts abstracts some attributes away, but I'm coming up blank on fixing this properly.

The error message

error: The option `virtualisation.forwardPorts' does not exist. Definition values:
       - In `/nix/store/6kp2ql3nww07p270y2qfjpl4habskbkb-source/flake.nix':
           [
             {
               from = "host";
               guest = {
                 port = 67;
           ...
(use '--show-trace' to show detailed location information)

I'm not sure how to pass --show-trace into the process to get more detailed information out.

Can I increase the disk size inside the VM ?

I tried setting the virtualisation.diskSize = 1024 * 512; parameter in examples/vm.nix but still df -h / says

Filesystem Size Used Avail Use% Mounted on
/dev/vda 488M 23M 430M 5% /

Can I somehow increase this value ?

virtualisation.msize error

error: The option `virtualisation.msize' defined in `<unknown-file>' does not exist.
  • system: "aarch64-linux"
  • host os: Linux 4.4.111-21427293
  • multi-user?: no
  • sandbox: no
  • version: nix-env (Nix) 2.3.16
  • channels(nix-on-droid): "home-manager-21.11, nix-on-droid-21.11, nixpkgs-21.11.336020.2128d0aa28e"
  • nixpkgs: /nix/store/3xxi7mfxzc2cr39z7slpiksl524aj9ma-nixexprs.tar.xz

Run one-off command

Instead of dropping into the login shell, would it be possible to create a CLI mode wherein the VM is launched, root shell entered and the given command is run, before exiting?

eg:

nixos-shell --flake github:srid/nixos-config#corsair --run "cd /Downloads && protonvpn c -f && aria2c ${MAGNET}"

9p cache / VM options

When I'm working on web stuff I like to mount the docroot into the VM with --mount so I can edit files on the host and see the effects immediately. Unfortunately cache=loose means the guest keeps the old version of the file for random time intervals (sometimes over a minute) so this workflow is blocked.

Before I start working on this I would like to agree on a plan. I had a few ideas:

  • add --mount-cache to specify how all directories are mounted
  • extend --mount to specify mount options on a per-directory basis, eg: --mount,cache=none /host /guest

These involve a bit of work on the command line parsing though and that may become more complex as nixos-shell evolves.

Perhaps it would be better to incorporate VM options into the vm.nix file itself so we can leverage the whole NixOS module system, akin to the way NixOps does it (deployment.targetEnv etc). We may end up with something like this:

{
  vm.mounts = {
    mountHome = true;
    mountNixProfile = true;

    # defaults
    cache = "loose";

    extraMounts = {
      # uses defaults defined above
      "/tank" = "/tank";

      "/var/www" = {
        target = "./src";
        cache = "none";
      };
    };
  };

  # normal NixOS options…
}

I would love to hear your take on this.

Disable mounting of $HOME

Is there a way to disable mounting the $HOME directory into the VM?

This causes all kinds of problems for me, for example with shell configuration.

Bad first user impressions

So I had read about nixos-shell before, but today I saw it in nixpkgs and decided to try it. This is what happened:

$ nix-env -iA nixos-shell -f.    # on nixpkgs master

$ nixos-shell
error: getting status of '/home/bf/proj/code/forks/nixpkgs/vm.nix': No such file or directory    # OK, so it needs this file... let's check --help
(use '--show-trace' to show detailed location information)

$ nixos-shell --help
error: string 'Usage: readlink [OPTION]... FILE...
Print value of a symbolic link or canonical file name

  -f, --canonicalize            canonicalize by following every symlink in
                                every component of the given name recursively;
                                all but the last component must exist
  -e, --canonicalize-existing   canonicalize by following every symlink in
                                every component of the given name recursively,
                                all components must exist
  -m, --canonicalize-missing    canonicalize by following every symlink in
                                every component of the given name recursively,
                                without requirements on components existence
  -n, --no-newline              do not output the trailing delimiter
  -q, --quiet
  -s, --silent                  suppress most error messages (on by default)
  -v, --verbose                 report error messages
  -z, --zero                    end each output line with NUL, not newline
      --help     display this help and exit
      --version  output version information and exit

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation <https://www.gnu.org/software/coreutils/readlink>
or available locally via: info '(coreutils) readlink invocation'' doesn't represent an absolute path, at /etc/current-nixpkgs/lib/modules.nix:109:89
(use '--show-trace' to show detailed location information)

# Ugh, that just pastes the readlink help!

$ man nixos-shell
No manual entry for nixos-shell

I realize the usage is documented in the README on github, but I think supporting --help and/or have error checking would be nice to users.

Btw, I don't think I would have made this issue if it wasn't for the fact that nixos-shell is packaged in nixpkgs.

Add a LICENSE

You have no LICENSE, and this is kinda scary. Could you please add it?

Getting setup-hook: cannot execute binary file error

When trying to utilise nixos-shell as remote builder host for my WSL client I accidentally came up with this minimal example - also my issue (note that this command was executed inside the nixos-shell session):

ssh nixos-shell
NIX_PATH=nixpkgs=http://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz nix-shell -p nix-info --run "nix-info -m"
unpacking 'http://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz'...
these paths will be fetched (0.05 MiB download, 0.28 MiB unpacked):
/nix/store/l31qzdd26g3rgn2a9h89sl7yjf71yim1-bash-interactive-4.4-p23-dev
copying path '/nix/store/l31qzdd26g3rgn2a9h89sl7yjf71yim1-bash-interactive-4.4-p23-dev' from 'https://cache.nixos.org'...
/nix/store/qdf49mvm79r83n9c9s7pkmmjqwhrw8jv-stdenv-linux/setup: line 519: source: /nix/store/1xmid45vayj917km02cvkwq5054mz2ms-binutils-wrapper-2.35.1/nix-support/setup-hook: cannot execute binary file

The exact error I got when trying to build i. e. pandoc remotely as in:

NIX_PATH=nixpkgs=http://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz nix-build -E '(with import <nixpkgs> { system = "x86_64-linux"; }; pkgs.haskell.packages.ghc884.ghcWithPackages (pkgs: [pkgs.pandoc]))' --option builders 'ssh://nixos-shell' # this got me the error as well, see below
NIX_PATH=nixpkgs=http://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz nix-build -E '(with import <nixpkgs> {}; pkgs.haskell.packages.ghc884.ghcWithPackages (pkgs: [pkgs.pandoc]))' # while this built

Did I do something unusual here ?

The error log:

copying path '/nix/store/6zinf42qdyfx528wgl428s9ljx80s86j-JuicyPixels-3.3.5.tar.gz' from 'https://cache.nixos.org'...
copying path '/nix/store/qk5hji9phm573cp51c97nhph4v6bwwmh-ghc-8.8.4-doc' from 'https://cache.nixos.org'...
copying path '/nix/store/q427hhgznng6cg7510ir4cm41m32hjmn-hscolour-1.24.4' from 'https://cache.nixos.org'...
copying path '/nix/store/i8zrgs1k4w633cgn967ypfhimlpkmnj3-ghc-8.8.4' from 'https://cache.nixos.org'...
copying path '/nix/store/wsjhnhvpaw50jw7zm2zbf818iajr7kq5-primitive-0.7.1.0-doc' from 'https://cache.nixos.org'...
copying path '/nix/store/fzwylip49bbs36534986di1n47jzclkl-zlib-0.6.2.3-doc' from 'https://cache.nixos.org'...
copying path '/nix/store/fzsrycbcmm4kfhpsahnmv1pacrs2agh2-primitive-0.7.1.0' from 'https://cache.nixos.org'...
copying path '/nix/store/wpwfs183zgr5z258rpxaxxykfmh23lsr-vector-0.12.3.0-doc' from 'https://cache.nixos.org'...
copying path '/nix/store/pi84scwxfxrif0qyz9vrlk6ff0jh58i7-zlib-0.6.2.3' from 'https://cache.nixos.org'...
copying path '/nix/store/faaa5szmazy4qasy2p99igwvzl2cadxy-vector-0.12.3.0' from 'https://cache.nixos.org'...
/nix/store/qdf49mvm79r83n9c9s7pkmmjqwhrw8jv-stdenv-linux/setup: line 519: source: /nix/store/1xmid45vayj917km02cvkwq5054mz2ms-binutils-wrapper-2.35.1/nix-support/setup-hook: cannot execute binary file
builder for '/nix/store/j1m8vd2qb047ims91gnkazlh54184dqx-JuicyPixels-3.3.5.drv' failed with exit code 126

Inheriting TERM variable leads to broken terminal

nixos-shell will inherit the TERM variable from the user environment which leads to a broken terminal in some situations.

For example, I have TERM=rxvt-unicode-256color, which is inherited and leads to a broken terminal. Probably because rxvt_unicode is not in the system packages?

Can I mount a direct partition like /dev/sdc in the vm?

I tried setting /dev/sdc as a mount but get an error of:

qemu-system-x86_64: -virtfs local,path=/dev/sdc,security_model=none,mount_tag=a457b9c00b7152b02ceea27e7fe1a07: cannot initialize fsdev 'a457b9c00b7152b02ceea27e7fe1a07': failed to open '/dev/sdc': Not a directory

From reading further it seems I need to set a -hda option, but once again I can't seem to find this in https://github.com/NixOS/nixpkgs/blob/b0df5a6816b644c2e0b6ebcde6ad0784b07205e0/nixos/modules/virtualisation/qemu-vm.nix either.

Not sure if this is the greatest place to ask, but if anyone know that would be appreciated.

[bug] nixos-shell does not find getty

Using the vm-efi.nix as example:

$> nixos-shell
warning: unknown setting 'experimental-features'
error: The option `services.getty' defined in `/nix/store/l2rg81cjbac3fvlir9k817qdw6z86kh8-nixos-shell-0.2.1/share/nixos-shell/nixos-shell.nix' does not exist.
(use '--show-trace' to show detailed location information)

How to configure uid/gid with `extraMounts` option?

Hey,
I'm looking to configure permissions of a 9p mount point. Usually they are owned by root inside the nixos-shell VM. How can I change the ownership?

What I can do currently is:

mount -o remount,uid=<UID>,gid=<GID> <mountpoint>

or alternaivley

bindfs -u 997 -g 997 /var/lib/nextcloud/calendar /var/lib/nextcloud/store-apps/calendar

Best regards
Jonas

Error: Option virtualisation.memorySize is not of type positive integer

Hey,
after a recent update I somehow get following error trying to use nixos-shell:

$ NIX_PATH=nixpkgs=/home/onny/projects/nixpkgs nixos-shell vm-opensnitchd.nix
error: A definition for option `virtualisation.memorySize' is not of type `positive integer, meaning >0'. Definition values:
- In `/nix/store/0q31g3syllx7335a3kjmw2rlsjnxn5nk-nixos-shell-0.2.1/share/nixos-shell/nixos-shell.nix': "500M"
(use '--show-trace' to show detailed location information)

Are there some changes in the background or is something wrong with my system settings?

Regards
Jonas

When running make test repeatedly nixos.qcow2 copied to store

I noticed that when I run make test repeatedly and there is the nixos.qcow2 lying around in the source directory depending on the file size I eventually get

warning: dumping very large path (> 256 MiB); this may run out of memory
error: out of memory

This is expected as the qcow2 file which may get quite large (depending on virtualization.diskSize and effective size) gets copied to the store, but I wonder if there was something to do about it.

I. e. an option to exclude the file from store ?

How to use nixos-shell modules from a flake.nix file

It would be nice to provide an example to illustrate how this could be used from a flake file, to build a VM using nixos-shell modules.

I currently have something such as:

{
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-21.11";
  outputs = { self, nixpkgs }: let
    pkgs = nixpkgs.legacyPackages."x86_64-linux";
    system = import (pkgs.path + /nixos) {
      system = "x86_64-linux";
      configuration = import ./configuration.nix;
    };
  in {
    defaultPackage.x86_64-linux = system.vm;
  };
}

How could i use nixos-shell modules to run this vm?

Note I would like to avoid relying on the nixos-shell script and use nix build|run directly instead.

Broken shell..cant install!

So it's funny through this process I have found a four or so different ways to root my phone and it's been an amazing learning experience but my shell is broken right now and I was going to reboot my phone but I wanted to see if I could Rescue It with Nix... I didn't know if there was a way someone from the community could possibly help by secure SSH or FTP to me so that it installs because I can't complete any functions on my terminal

Run without KVM

Would it be possible to run this without KVM support of the host system?
Many cloud environments do not enable hardware support for virtualization.

In this case one will get the error:
qemu-system-x86_64: CPU model 'host' requires KVM

Is qemu able to emulate the missing features somehow?

Q&A: How would I use nix-repl for config ?

I would like to inspect the configuration settings (config.) in the spawned nixos-shell for what I did:

nix repl '<nixpkgs/nixos>'

But it's only getting me back this:

warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels/nixos' does not exist, ignoring
warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels' does not exist, ignoring
error: file 'nixpkgs/nixos' was not found in the Nix search path (add it using $NIX_PATH or -I)

Is there another way I can say give me the equivalent /etc/configuration.nix ?

What I'd like to find out is if having boot.binfmt.emulatedSystems = [ "aarch64-linux" ]; i. e. in my modified vm.nix does have any effect at all.

Or more general are any config values in the vm.nix file, i. e. smth like users.users.builder = {..} ?

Question: Is space configurable via nixos-shell ?

I am trying to spawn nixos-shell as a local builder for aarch64 packages on my x86_64 machine. Everything is working fine

NIX_BUILD_TOP=/tmp/build NIX_PATH=nixpkgs=http://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz nix-build '<nixpkgs>' -A pkgsStatic.hledger --argstr system aarch64-linux --option sandbox false --builders 'ssh://nixos-shell aarch64-linux' -j0

But when I try to build more complex packages as in the example above I am getting

error: preallocating file of 266966 bytes: No space left on device
error: writing to file: Broken pipe

Is there something I can tune via config here ? Thinking examples/vm.nix.

Can't access custom nixos configuration attr

Most nix commands and tools seem to have a default search path that they look at, including nixos-shell. For example
nixos-shell --flake .#foo searches at .#nixosConfigurations.foo first.

However, most nix commands and tools will fall back to searching at the top level if that fails. So if I do
nix build .#my.custom.path.foo it will first try to find packages.<system>.my.custom.path.foo, but if that fails it will look for plain my.custom.path.foo before giving up.

nixos-shell does not do this, it requires the configurations to be at specific paths.

I'm thinking this might be because nixos-shell takes two kinds of inputs: configurations and modules, and it can only tell the difference by the path. One option is to have a default (I would guess configuration). But also this could be specified at the command line with a --module or --configuration flag.

multihoming

I was pondering between using this and keep using nixops but this seems leaner (my nixops is full of libvirt hacks) and I also like that the host store can be accessed.

I am trying to create a multihomed vm.nix by adding virtualisation.vlans = [ 2 1 3 4 ]; in my vm.nix but I still see only one eth0 in the vm.

I installed nixos-shell via nix-env and the name is not very inspiring so here is patch changing the name and removing some trailing whitespace if you want.

diff --git a/default.nix b/default.nix
index 0224ee5..3440675 100644
--- a/default.nix
+++ b/default.nix
@@ -1,6 +1,7 @@
 with import <nixpkgs> {};
 stdenv.mkDerivation {
-  name = "env";
+  pname = "nixos-shell";
+  version = "20190604";
   src = ./.;
   buildInputs = [ bash ];
   preConfigure = ''
diff --git a/share/nixos-shell/nixos-shell.nix b/share/nixos-shell/nixos-shell.nix
index 4e353f7..ae407fb 100644
--- a/share/nixos-shell/nixos-shell.nix
+++ b/share/nixos-shell/nixos-shell.nix
@@ -43,15 +43,15 @@ in {
                 type = types.path;
                 description = "Target on the guest.";
               };
-  
+
               inherit cache;
-  
+
               tag = mkOption {
                 type = types.str;
                 internal = true;
               };
             };
-  
+
             config.tag = lib.mkDefault (
               builtins.substring 0 31 ( # tags must be shorter than 32 bytes
                 "a" + # tags must not begin with a digit

Error after logging in with fish shell

Hey, after logging in with root to the nixos-shell vm, I get following error:

<<< Welcome to NixOS 21.11.git.3d6b1e6372eM (x86_64) - ttyS0 >>>
Log in as "root" with an empty password.
If you are connect via serial console:
Type Ctrl-a c to switch to the qemu console
and `quit` to stop the VM.
 
 
Run 'nixos-help' for the NixOS manual.
 
nixos login: root
set: Tried to change the read-only variable “PWD”
test: Missing argument at index 6
-z  -a -eq 1
             ^
~/.config/fish/config.fish (line 23): 
  if test -z "$DISPLAY" -a $XDG_VTNR -eq 1
     ^
from sourcing file ~/.config/fish/config.fish
	called during startup
Welcome to fish, the friendly interactive shell
Type `help` for instructions on how to use fish

The source file which is loaded looks like this:

# ~/.config/fish/config.fish: DO NOT EDIT -- this file has been generated
# automatically by home-manager.

# if we haven't sourced the general config, do it
if not set -q __fish_general_config_sourced

  set --prepend fish_function_path /nix/store/xyy67np060dn02kv1k84r3rxv1xb9h4f-fishplugin-foreign-env-git-20200209/share/fish/vendor_functions.d
  fenv source /home/onny/.nix-profile/etc/profile.d/hm-session-vars.sh > /dev/null
  set -e fish_function_path[1]

  
  # and leave a note so we don't source this config section again from
  # this very shell (children will source the general config anew)
  set -g __fish_general_config_sourced 1

end

# if we haven't sourced the login config, do it
status --is-login; and not set -q __fish_login_config_sourced
and begin

  # Login shell initialisation
  if test -z "$DISPLAY" -a $XDG_VTNR -eq 1
  exec /nix/store/ps113w91dgz263nx39561jyq2xfmclcb-dbus-1.12.20/bin/dbus-run-session /nix/store/lncrylx32a8m8sja6h5gjvs0fh6ag05p-sway-1.6.1/bin/sway
end


  # and leave a note so we don't source this config section again from
  # this very shell (children will source the general config anew)
  set -g __fish_login_config_sourced 1

end

# if we haven't sourced the interactive config, do it
status --is-interactive; and not set -q __fish_interactive_config_sourced
and begin

  # Abbreviations
  

  # Aliases
  

  # Prompt initialisation
  

  # Interactive shell intialisation
  # add completions generated by Home Manager to $fish_complete_path
begin
  set -l joined (string join " " $fish_complete_path)
  set -l prev_joined (string replace --regex "[^\s]*generated_completions.*" "" $joined)
  set -l post_joined (string replace $prev_joined "" $joined)
  set -l prev (string split " " (string trim $prev_joined))
  set -l post (string split " " (string trim $post_joined))
  set fish_complete_path $prev "/home/onny/.local/share/fish/home-manager_generated_completions" $post
end

alias codium='codium --enable-features=UseOzonePlatform·--ozone-platform=wayland'
alias signal-desktop='signal-desktop --enable-features=UseOzonePlatform·--ozone-platform=wayland'


  # and leave a note so we don't source this config section again from
  # this very shell (children will source the general config anew,
  # allowing configuration changes in, e.g, aliases, to propagate)
  set -g __fish_interactive_config_sourced 1

end

I don't get this error when using fish on my host system :(

Best regard
Jonas

ssh still asking for password

I'm running make test-forward and while trying to

ssh nixos-shell
# ~/.ssh/config
Host nixos-shell
  Port 2222
  IdentitiesOnly yes
  User root
  HostName 127.0.0.1
  IdentityFile ~/.ssh/id_rsa

I am being still asked for a password.

Force VM rebuild

Hey,
I guess NixOS is caching somehow the state of a VM and only applies changes if you run it again.
How can I force a rebuild or delete the KVM images manually?

Regards
Jonas

Cannot override default net device

Trying to use the example config vm-forward.nix produces this error:

qemu-kvm: -netdev user,id=user.0,hostfwd=tcp::2222-:22: Duplicate ID 'user.0' for netdev

This is on a nixpkgs-unstable system. I can use QEMU_NET_OPTS as a workaround.

Flake support

How to get to a system built from a flake?
I'm currently using flake-utils-plus to build and manage my main system, and it has a hosts options which allows to output multiple hosts as outputs, while sharing channels (inputs), overlays and modules between them.

It'd be great to be able to use nixos-shell to boot one of these hosts directly, and have that documented. Not sure how to handle the custom config.nixos-shell on this context though. Sharing modules may make it easier to get into a nixos-shell without mounting home.

warning message about programs.bash.enable

When I run nixos-shell, I get this warning message:

trace: warning: The option definition `programs.bash.enable' in `/home/ryantm/.nix-profile/share/nixos-shell/nixos-shell.nix' no longer has any effect; please remove it.                                          

jq impurity in flake mode

jq is used in nixos-shell and is not a satisfied dependency when using nixos-shell 1.0 from nixpkgs like nix-shell -p nixos-shell

flake_uri="$(nix flake metadata --extra-experimental-features "nix-command flakes" --json -- "$flake" | jq -r .url)"

I'm not sure how this is best solved. Maybe nixos-shell should be a writeShellApplication with all of its runtimInputs resolved properly? Maybe we should use resholve? I'm unsure.

Graphical log-in not working

I have this configuration

{ modulesPath, ... }: {
        # weird workaround https://github.com/NixOS/nixpkgs/issues/59219#issuecomment-774711048
        imports = [ (modulesPath + "/virtualisation/qemu-vm.nix") ];
        virtualisation.graphics = true;

        services.xserver = {
          enable = true;
          desktopManager.xfce.enable = true;
        };
};

And once I log in with root and empty password, the VM freezes. Sometimes I see the background of the login screen, and sometimes it fails to render entirely and I get my computers desktop background.

Same thing happens with gnome instead of xfce. I also tried upping virtualisation.memory to 1024.

Failing with current unstable

When running nixos-shell with -I nixpkgs=channel:nixos-unstable to get access to packages not available yet in a release, I get a failure to create users:

/nix/store/jrnaxgnf7kskxjb0xilcz42jv86ai8vs-nixos-vm
running activation script...
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "\x{0}\x{0}\x{0}\x{0}...") at /nix/store/sr09hv1nv3ikc7qbnhrgbrcyjjxn8j25-update-users-groups.pl line 10.
Activation script snippet 'users' failed (2)
setting up /etc...
chown: invalid user: 'root:root'
Activation script snippet 'var' failed (1)
chown: invalid user: 'root:root'
chown: invalid user: 'root:messagebus'
chown: invalid user: 'root:root'
chown: invalid user: 'root:root'
...

This results in not being able to log in as root either.

Odd file permissions?

Apologies I don't really expect the maintainers of the software to respond to this, just more for my own reference and if I or anyone else finds an answer.


When I create a file in a mounted directory, the permissions seem a bit odd. It seems to be created with the userid of the parent host system.

Which means if I try to edit files with nvim it starts complaining about not being able to write a backup file.

From within the guest:

touch example
touch: setting times of 'example': Permission denied

How could I shared a mounted directory while also allowing any necessary permission to write/create files?

unset `NIX_PATH` causes nixos-shell to not work

If you use nixos-shell with an unset NIX_PATH it doesn't work, but maybe it should follow the pkgs.path of the nixosConfiguration it's invoking, especially when this is fully defined in a flake and ready to evaluate.

❯ nixos-shell --flake .#binfmt-sdk-nixos-shell
warning: Git tree '/home/matthew/git/mobile-nixos-templates' is dirty
error: file 'nixpkgs' was not found in the Nix search path (add it using $NIX_PATH or -I)

       at /nix/store/j7x4a64zsw8fg7kq6sdq3vbcnx48wg1k-nixos-shell-1.0.0/share/nixos-shell.nix:1:13:

            1| { nixpkgs ? <nixpkgs>
             |             ^
            2| , system ? builtins.currentSystem
(use '--show-trace' to show detailed location information)

vm_forward.nix example passes net option twice

Running nixos-shell on examples/vm_forward.nix results in the following error:

nixos-shell/examples: nixos-shell vm-forward.nix
trace: warning: system.stateVersion is not set, defaulting to 22.05. Read why this matters on https://nixos.org/manual/nixos/stable/options.html#opt-system.stateVersion.
/nix/store/ii93pa9vnfcf5j9niwglnf3m71yrm97j-nixos-vm
qemu-kvm: -netdev user,id=user.0,hostfwd=tcp::2222-:22: Duplicate ID 'user.0' for netdev

When looking at the corresponding run-nixos-vm script we see that qemu gets two -net and -netdev options, both with id=user.0.

-net nic,netdev=user.0,model=virtio -netdev user,id=user.0,"$QEMU_NET_OPTS" -net nic,netdev=user.0,model=virtio -netdev user,id=user.0,hostfwd=tcp::2222-:22

nixos-shell broken with `auto-allocate-uids = true`

Hi.
Can't run with auto-allocate-uids = true it say cannot find name for user ID 872415232

nix.conf

auto-allocate-uids = true
experimental-features = auto-allocate-uids

Log:

bash-5.2# nixos-shell vm.nix
trace: warning: system.stateVersion is not set, defaulting to 23.11. Read why this matters on https://nixos.org/manual/nixos/stable/options.html#opt-system.stateVersion.
these 9 derivations will be built:
  /nix/store/zkv098nlsnknygmpa0m3mk0y63z3yzm8-logrotate.conf.drv
  /nix/store/dg9nipiqkm4zkk68kqh6ccq12r12h266-unit-logrotate-checkconf.service.drv
  /nix/store/rhavd64cc8afzzn1h7pq9fxvg1jgv3cn-unit-logrotate.service.drv
  /nix/store/pqdzlsy3zf8sjvili9cl6wfm9jjyy8yz-system-units.drv
  /nix/store/9fb9na23pgma5zkjgx68r6wjbx5p4v55-etc.drv
  /nix/store/lgay8wgpzb8zda65bin95xanpv7ql0if-nixos-system-nixos-23.11pre-git.drv
  /nix/store/sw4d2pa66x53f02xfx9iqbd7n7rpjjsv-closure-info.drv
  /nix/store/k2c3sfq4nv29b0x81yxhw31f5mrxf16k-run-nixos-vm.drv
  /nix/store/vqqq324da6azwgc5jv9891ysd4g1b5v4-nixos-vm.drv
building '/nix/store/zkv098nlsnknygmpa0m3mk0y63z3yzm8-logrotate.conf.drv'...
/nix/store/whinz9rj5h6h8zxp9bkmfzv7fkzc0cq8-coreutils-9.3/bin/id: cannot find name for user ID 872415232
error: builder for '/nix/store/zkv098nlsnknygmpa0m3mk0y63z3yzm8-logrotate.conf.drv' failed with exit code 1
error: 1 dependencies of derivation '/nix/store/dg9nipiqkm4zkk68kqh6ccq12r12h266-unit-logrotate-checkconf.service.drv' failed to build
error: 1 dependencies of derivation '/nix/store/rhavd64cc8afzzn1h7pq9fxvg1jgv3cn-unit-logrotate.service.drv' failed to build

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.