summaryrefslogtreecommitdiff
path: root/worker/scripts/ansible_playbook
blob: 062680db729d78cd156d3192c973a4e5eccffa20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env -S deno run --allow-env --allow-net --allow-run --allow-read --allow-write

import {
  BitwardenSession,
  getRequiredEnv,
  getStdout,
  loggerWithPrefix,
  prependWith,
  type SecureNote,
} from "@liz-ci/utils";
import type { AnsiblePlaybookJobProps } from "@liz-ci/model";

const args: AnsiblePlaybookJobProps = {
  path: getRequiredEnv("path"),
  playbooks: getRequiredEnv("playbooks"),
};
const logger = loggerWithPrefix(() =>
  `[${new Date().toISOString()}] [ansible_playbook.'${args.playbooks}']`
);

const run = async () => {
  logger.log("Starting Ansible playbook job");

  const bitwardenSession = new BitwardenSession();
  const secretFiles = await Promise.all(
    ["ansible_secrets", "ssh_key"]
      .map((secretName) =>
        bitwardenSession
          .getItem<SecureNote>(secretName)
          .then(async ({ notes: recoveredSecret }) => {
            const tempFile = await Deno.makeTempFile();
            await Deno.writeTextFile(tempFile, recoveredSecret);
            logger.log(secretName, "stored at", tempFile);
            return tempFile;
          })
      ),
  );
  const [ansibleSecrets, sshKey] = secretFiles;

  try {
    const volumes = [
      `${args.path}:/ansible`,
      `${sshKey}:/root/id_rsa`,
      `${ansibleSecrets}:/ansible/secrets.yml`,
    ];

    const playbookCmd = `ansible-playbook -e @secrets.yml ${args.playbooks}`;
    const deployCmd = [
      "docker",
      "run",
      ...prependWith(volumes, "-v"),
      "willhallonline/ansible:latest",
      ...playbookCmd.split(" "),
    ];
    logger.log("deploying...", deployCmd);
    await getStdout(deployCmd);
  } finally {
    await Promise.allSettled(
      [bitwardenSession.close()].concat(
        secretFiles.map((p) => {
          logger.log(`cleanup`, p);
          return Deno.remove(p);
        }),
      ),
    );
  }

  logger.log("ansible playbook job completed");
};

if (import.meta.main) {
  try {
    await run();
  } catch (e) {
    logger.error("womp womp D:", e);
    throw e;
  }
}