77 lines
2.9 KiB
Nix
77 lines
2.9 KiB
Nix
{
|
|
config,
|
|
lib,
|
|
pkgs,
|
|
...
|
|
}:
|
|
let
|
|
cfg = config.khscodes.services.read-vault-auth-from-userdata;
|
|
in
|
|
{
|
|
options.khscodes.services.read-vault-auth-from-userdata = {
|
|
enable = lib.mkEnableOption "Enables reading vault auth information from instance userdata";
|
|
url = lib.mkOption {
|
|
type = lib.types.str;
|
|
description = "URL to retrieve instance metadata from";
|
|
};
|
|
};
|
|
|
|
config = lib.mkIf (cfg.enable && config.khscodes.services.vault-agent.enable) (
|
|
let
|
|
vault_addr = lib.escapeShellArg config.khscodes.services.vault-agent.vault.address;
|
|
secretIdFilePath = lib.escapeShellArg config.khscodes.services.vault-agent.vault.secretIdFilePath;
|
|
roleIdFilePath = lib.escapeShellArg config.khscodes.services.vault-agent.vault.roleIdFilePath;
|
|
cacheFilePath = lib.escapeShellArg "${config.khscodes.services.vault-agent.vault.secretIdFilePath}.wrapped";
|
|
in
|
|
{
|
|
systemd.services."read-vault-auth-from-userdata" = {
|
|
enable = true;
|
|
wantedBy = [ "multi-user.target" ];
|
|
wants = [ "network-online.target" ];
|
|
after = [ "network-online.target" ];
|
|
serviceConfig = {
|
|
Type = "oneshot";
|
|
RemainAfterExit = true;
|
|
ExecStart = lib.getExe (
|
|
pkgs.writeShellApplication {
|
|
name = "read-vault-auth-from-userdata";
|
|
runtimeInputs = [
|
|
pkgs.curl
|
|
pkgs.jq
|
|
pkgs.openbao
|
|
pkgs.getent
|
|
pkgs.systemd
|
|
];
|
|
text = ''
|
|
userdata="$(curl ${lib.escapeShellArg cfg.url})"
|
|
role_id="$(echo "$userdata" | jq --raw-output '.VAULT_ROLE_ID')"
|
|
secret_id_wrapped="$(echo "$userdata" | jq --raw-output '.VAULT_SECRET_ID_WRAPPED')"
|
|
if [[ -f ${cacheFilePath} ]]; then
|
|
cache_key="$(cat ${cacheFilePath})"
|
|
if [[ "$secret_id_wrapped" == "$cache_key" ]]; then
|
|
echo "Secret id matched last used value, exiting program"
|
|
exit 0
|
|
fi
|
|
fi
|
|
secret_id="$(BAO_ADDR=${vault_addr} bao unwrap -field=secret_id "$secret_id_wrapped")"
|
|
mkdir -p "$(dirname ${secretIdFilePath})"
|
|
mkdir -p "$(dirname ${roleIdFilePath})"
|
|
echo -n "$role_id" > ${roleIdFilePath}
|
|
echo -n "$secret_id" > ${secretIdFilePath}
|
|
chown root:root ${secretIdFilePath}
|
|
chmod 0600 ${secretIdFilePath}
|
|
chown root:root ${roleIdFilePath}
|
|
chmod 0600 ${roleIdFilePath}
|
|
echo -n "$secret_id_wrapped" > ${cacheFilePath}
|
|
chmod 0600 ${cacheFilePath}
|
|
chown root:root ${cacheFilePath}
|
|
echo "Role id and secret id copied, restarting vault-agent"
|
|
systemctl restart vault-agent-openbao.service
|
|
'';
|
|
}
|
|
);
|
|
};
|
|
};
|
|
}
|
|
);
|
|
}
|