summaryrefslogtreecommitdiff
path: root/worker/scripts/build_image
blob: 07c07c92b6be7c47c136f7971f642bbc91fbfd92 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env -S deno run --allow-env --allow-net --allow-run

import type { BuildDockerImageJobProps } from "@liz-ci/model";
import {
  BitwardenSession,
  getRequiredEnv,
  getStdout,
  loggerWithPrefix,
  type LoginItem,
} from "@liz-ci/utils";

const args: BuildDockerImageJobProps = {
  registry: getRequiredEnv("registry"),
  namespace: getRequiredEnv("namespace"),
  repository: getRequiredEnv("repository"),
  imageTag: getRequiredEnv("imageTag"),

  context: getRequiredEnv("context"),
  dockerfile: getRequiredEnv("dockerfile"),
  buildTarget: getRequiredEnv("buildTarget"),
};

const logger = loggerWithPrefix(() =>
  `[${
    new Date().toISOString()
  }] [build_image.${args.repository}.${args.imageTag}]`
);

const run = async () => {
  logger.log("Starting Docker image build job");

  const bitwardenSession = new BitwardenSession();
  const { username: registryUsername, password: registryPassword } =
    (await bitwardenSession.getItem<LoginItem>(args.registry))?.login ?? {};
  if (!(registryUsername && registryPassword)) {
    throw new Error("where's the login info bruh");
  }

  logger.log(`Logging in to Docker registry: ${args.registry}`);
  await getStdout(
    [
      "docker",
      "login",
      "--username",
      registryUsername,
      "--password",
      registryPassword,
      args.registry,
    ],
  );

  const tag =
    `${args.registry}/${args.namespace}/${args.repository}:${args.imageTag}`;
  const buildCmd = [
    "docker",
    "build",
    "--target",
    args.buildTarget,
    "-t",
    tag,
    "-f",
    `${args.dockerfile}`,
    `${args.context}`,
  ];

  logger.log(`building`, tag, buildCmd);
  await getStdout(
    buildCmd,
    {
      clearEnv: true,
      env: {},
    },
  );

  const pushCmd = [
    "docker",
    "push",
    tag,
  ];
  logger.log(`pushing`, pushCmd);
  await getStdout(pushCmd);
};

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