nixos_config/nixos/modules/services/oci-authorized-keys.nix
2026-05-29 19:30:07 +02:00

73 lines
2.3 KiB
Nix

{ config, lib, pkgs, ... }:
let
cfg = config.alisceon.ociAuthorizedKeys;
home = config.users.users.${cfg.user}.home;
sshDir = "${home}/.ssh";
authorizedKeysFile = "${sshDir}/authorized_keys";
fetchOciAuthorizedKeys = pkgs.writeShellApplication {
name = "fetch-oci-authorized-keys";
runtimeInputs = [
pkgs.coreutils
pkgs.curl
];
text = ''
install -d -m 0700 -o ${lib.escapeShellArg cfg.user} -g ${lib.escapeShellArg cfg.group} ${lib.escapeShellArg sshDir}
if [ -s ${lib.escapeShellArg authorizedKeysFile} ]; then
echo "OCI authorized_keys already present for ${cfg.user}"
exit 0
fi
curl --fail --silent --show-error --location \
--header ${lib.escapeShellArg "Authorization: Bearer Oracle"} \
--output ${lib.escapeShellArg authorizedKeysFile} \
${lib.escapeShellArg cfg.metadataUrl}
chown ${lib.escapeShellArg "${cfg.user}:${cfg.group}"} ${lib.escapeShellArg authorizedKeysFile}
chmod 0600 ${lib.escapeShellArg authorizedKeysFile}
'';
};
in
{
options.alisceon.ociAuthorizedKeys = {
enable = lib.mkEnableOption "fetching SSH authorized_keys from OCI metadata";
user = lib.mkOption {
type = lib.types.str;
default = "alisceon";
description = "User whose authorized_keys file should be populated.";
};
group = lib.mkOption {
type = lib.types.str;
default = "users";
description = "Group owner for the user's SSH files.";
};
metadataUrl = lib.mkOption {
type = lib.types.str;
default = "http://169.254.169.254/opc/v2/instance/metadata/ssh_authorized_keys";
description = "OCI metadata endpoint containing SSH authorized keys.";
};
};
config = lib.mkIf cfg.enable {
systemd.services.fetch-oci-authorized-keys = {
description = "Fetch OCI metadata authorized_keys for ${cfg.user}";
wantedBy = [ "sshd.service" ];
before = [ "sshd.service" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
StandardError = "journal+console";
StandardOutput = "journal+console";
};
script = lib.getExe fetchOciAuthorizedKeys;
};
systemd.services.fetch-ssh-keys.enable = false;
};
}