summaryrefslogtreecommitdiff
path: root/worker/scripts/build_image
blob: 6618af6ffc259b944478886776cedad56eae5e72 (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
92
93
94
95
96
97
98
#!/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~ (⑅˘꒳˘) let's make something cute!",
  );

  const bitwardenSession = new BitwardenSession();
  const { username: registryUsername, password: registryPassword } =
    (await bitwardenSession.getItem<LoginItem>(args.registry))?.login ?? {};
  if (!(registryUsername && registryPassword)) {
    throw new Error("oh nyo! can't find the login info (。•́︿•̀。)");
  }

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

  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 image~ (◕ᴗ◕✿)`, tag, buildCmd);
  await getStdout(
    buildCmd,
    {
      clearEnv: true,
      env: {},
    },
  );

  const pushCmd = [
    "docker",
    "push",
    tag,
  ];
  logger.log(`sending image to wegistwy~ (>ᴗ<)`, pushCmd);
  await getStdout(pushCmd);
};

if (import.meta.main) {
  try {
    await run();
  } catch (e) {
    logger.error("oh nyo! something went wrong with the build (´。﹏。`)", e);
    throw e;
  }
}