NixOS / nixpkgs

Nix Packages collection & NixOS
MIT License
18.07k stars 14.13k forks source link

`hostnamectl hostname --static` should be allowed #285464

Open hacker1024 opened 9 months ago

hacker1024 commented 9 months ago

Describe the bug

hostnamectl hostname --static is currently blocked.

There are valid use-cases for this tool on NixOS, though. I, for example, want to set the static hostname dynamically based on system properties. The transient hostname is not used by NetworkManager for DHCP requests, which is why the static hostname must be used.

Steps To Reproduce

A service like the following does not currently work.

{
  networking.hostName = "";
  systemd.services.set-hostname = {
    wants = [ "network-pre.target" ];
    before = [ "network-pre.target" ];
    wantedBy = [ "multi-user.target" ];
    path = with pkgs; [ coreutils ];
    script = ''
      hostnamectl hostname --static "$(sha256sum /sys/devices/virtual/dmi/id/board_serial | cut --characters=-8)"
    '';
    serviceConfig.Type = "oneshot";
  };
}

Expected behavior

hostnamectl hostname --static should not fail.

Notify maintainers

@NixOS/systemd

Metadata

Please run nix-shell -p nix-info --run "nix-info -m" and paste the result.

[user@system:~]$ nix-shell -p nix-info --run "nix-info -m"
 - system: `"aarch64-linux"`
 - host os: `Linux 5.10.104, NixOS, 24.05 (Uakari), 24.05pre-git`
 - multi-user?: `yes`
 - sandbox: `yes`
 - version: `nix-env (Nix) 2.18.1`
 - channels(root): `"nixos"`
 - nixpkgs: `/nix/var/nix/profiles/per-user/root/channels/nixos`

Add a :+1: reaction to issues you find important.

arianvp commented 9 months ago

This makes sense to me.

hacker1024 commented 4 months ago

Also see: https://github.com/NixOS/nixpkgs/issues/224080#issuecomment-1509170912

It might make sense to conditionally allow setting the static hostname interactively when networking.hostName is not set.

flokli commented 4 months ago

I'd be happy to review such patch.

TheDelus commented 3 months ago

Since I came here while searching for a way to dynamically change the hostname to the machine-id on boot I want to leave my (hacky) solution here:

  # /etc/hostname symlink is not created on empty hostName in config
  networking.hostName = lib.mkForce "";
  systemd.services.set-machine-id-as-hostname = {
    description = "Set hostname from /etc/machine-id";

    # Run after the system has booted and the filesystem is mounted
    after = [ "network.target" ];

    # Set to run before the hostname is set
    before = [ "systemd-hostnamed.service" ];

    serviceConfig = {
      User = "root";
      Group = "root";
      Type = "oneshot";
      RemainAfterExit = true;
    };

    script = ''
      ${pkgs.coreutils}/bin/echo "system-''$(cat /etc/machine-id)" > /etc/hostname
    '';

    # Ensure the service runs on boot
    wantedBy = [ "multi-user.target" ];
  };

It seems to be working fine. But I am not sure if this will break anything.