Declaring instances of a generic systemd service e.g. `my-service@foo`?

Using nixOS: In my configuration.nix, I have a custom generic service systemd.service."my-service@".

I am currently having to manage instances of that service manually (sudo systemctl start my-service@foo). How can I declare some fixed instances of that (e.g. my-service@foo, my-service@bar) in configuration.nix? I don’t want to redefine a service definition, I’d prefer to use the same machinery that systemd does for services with @.

This is not supported in NixOS. You have to use configuration.nix to template and instantiate your services.

https://github.com/NixOS/nixpkgs/issues/108054
https://github.com/NixOS/nixpkgs/issues/108643

Thank you for linking those issues! (They describe exactly this problem). Now that I know the keyword is “template”, my searches turn up more useful information, too.

I hope this gets resolved some day; I’ll follow along with the primary GitHub issue, which seems to be:
https://github.com/NixOS/nixpkgs/issues/80933

Not sure if this is useful to your case, but I’ve had a situation where I needed to create a fixed number of template instances before and used a target to do so.

I’ve just revisited this problem and come up with the following workaround. You need to put a symlink to the template unit in the systemd unit directory which you can do by using systemd.packages. Then you only have to add the new symlink to a target, which is done using systemd.services."<name>".wantedBy.

{ config, lib, pkgs, ... }: {

  systemd.packages = [
    (pkgs.runCommandNoCC "machines" {
      preferLocalBuild = true;
      allowSubstitutes = false;
    } ''
      mkdir -p $out/etc/systemd/system/
      ln -s /etc/systemd/system/systemd-nspawn@.service $out/etc/systemd/system/systemd-nspawn@archlinux.service
    '')
  ];

  systemd.services."systemd-nspawn@archlinux".wantedBy = [ "machines.target" ];

}