diff options
Diffstat (limited to 'worker/scripts/ansible_playbook')
-rw-r--r-- | worker/scripts/ansible_playbook | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/worker/scripts/ansible_playbook b/worker/scripts/ansible_playbook index e69de29..bfeeb8b 100644 --- a/worker/scripts/ansible_playbook +++ b/worker/scripts/ansible_playbook @@ -0,0 +1,67 @@ +#!/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<SecureNote>( + "ansible_secrets", + ); + await Deno.writeTextFile("secrets.yml", ansibleSecrets); + + const { notes: privateKey } = await bitwardenSession.getItem<SecureNote>( + "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"]), + ]); +} |