#!/usr/bin/env -S deno run --allow-env --allow-net --allow-run --allow-read --allow-write import { BitwardenSession, getRequiredEnv, getStdout, type SecureNote, } from "@liz-ci/utils"; import type { AnsiblePlaybookJobProps } from "@liz-ci/model"; const args: AnsiblePlaybookJobProps = { path: getRequiredEnv("path"), playbooks: getRequiredEnv("playbooks"), }; const tempKeyFile = await Deno.makeTempFile(); const cwd = Deno.cwd(); const bitwardenSession = new BitwardenSession(); try { Deno.chdir(args.path); const { notes: ansibleSecrets } = await bitwardenSession.getItem( "ansible_secrets", ); await Deno.writeTextFile("secrets.yml", ansibleSecrets); const { notes: privateKey } = await bitwardenSession.getItem( "ssh_key", ); // Create a temporary file for the SSH key await Deno.writeTextFile(tempKeyFile, privateKey); await getStdout(["chmod", "600", tempKeyFile]); // Start ssh-agent and add the key const sshAgent = await getStdout(["ssh-agent", "-s"]); const [SSH_AGENT_PID, SSH_AUTH_SOCK] = [ /SSH_AGENT_PID=(\d+)/, /SSH_AUTH_SOCK=([^;]+)/, ] .map((regex) => sshAgent.match(regex)?.[1]) .map((val) => { if (!val) throw new Error("Failed to start ssh-agent"); return val; }); const sshEnv = { SSH_AGENT_PID, SSH_AUTH_SOCK, }; await getStdout(["ssh-add", tempKeyFile], { env: sshEnv, }); await getStdout([ "ansible-playbook", "-e", "@secrets.yml", ...args.playbooks.split(" "), ], { env: sshEnv }); } finally { await Promise.allSettled([ Deno.chdir.bind(null, cwd), Deno.remove(tempKeyFile), getStdout(["ssh-agent", "-k"]), ]); }