Skip to content
This repository was archived by the owner on Aug 4, 2023. It is now read-only.

Commit 1535a0e

Browse files
use kaniko for building the gcip docker image
1 parent 80d3cca commit 1535a0e

File tree

5 files changed

+167
-16
lines changed

5 files changed

+167
-16
lines changed

.gitlab-ci.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from gcip import Pipeline, PredefinedVariables
2-
from gcip.addons.docker import jobs as docker
2+
from gcip.addons.kaniko import jobs as kaniko
33
from gcip.addons.python import jobs as python
44

55
pipeline = Pipeline()
@@ -11,17 +11,12 @@
1111
python.flake8(),
1212
python.pytest(),
1313
python.evaluate_git_tag_pep404_conformity(),
14-
docker.build(repository="thomass/gcip", tag=PredefinedVariables.CI_COMMIT_REF_SLUG),
15-
)
16-
17-
if PredefinedVariables.CI_COMMIT_TAG or PredefinedVariables.CI_COMMIT_BRANCH == "master":
18-
pipeline.add_children(
19-
docker.push(
20-
image="thomass/gcip",
21-
tag=PredefinedVariables.CI_COMMIT_REF_SLUG,
22-
user_env_var="DOCKER_USER",
23-
login_env_var="DOCKER_LOGIN",
14+
kaniko.execute(
15+
image_name="thomass/gcip",
16+
enable_push=(PredefinedVariables.CI_COMMIT_TAG or PredefinedVariables.CI_COMMIT_BRANCH == "master"),
17+
dockerhub_user_env_var="DOCKER_USER",
18+
dockerhub_login_env_var="DOCKER_LOGIN",
2419
)
25-
)
20+
)
2621

2722
pipeline.write_yaml()

gcip/addons/docker/jobs.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def build(
2020
*,
2121
repository: str,
2222
tag: Optional[str] = None,
23-
context: Optional[str] = ".",
23+
context: str = ".",
2424
) -> Job:
2525
"""Runs [```docker build```](https://docs.docker.com/engine/reference/commandline/build/)
2626
@@ -35,7 +35,7 @@ def build(
3535
repository (str): The Docker repository name ```([<registry>/]<image>)```.
3636
tag (Optional[str]): A Docker image tag applied to the image. Defaults to `None` which no tag is provided
3737
to the docker build command. Docker should then apply the default tag ```latest```.
38-
context (Optional[str]): The Docker build context (the directory containing the Dockerfile). Defaults to
38+
context (str): The Docker build context (the directory containing the Dockerfile). Defaults to
3939
the current directory `.`.
4040
4141
Returns:
@@ -55,7 +55,7 @@ def push(
5555
*,
5656
registry: Optional[str] = None,
5757
image: str,
58-
tag: Optional[str] = "latest",
58+
tag: Optional[str] = None,
5959
user_env_var: Optional[str] = None,
6060
login_env_var: Optional[str] = None,
6161
) -> Job:

gcip/addons/kaniko/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
__author__ = "Thomas Steinbach"
2+
__copyright__ = "Copyright 2020 DB Systel GmbH"
3+
__credits__ = ["Thomas Steinbach"]
4+
# SPDX-License-Identifier: Apache-2.0
5+
__license__ = 'Apache-2.0'
6+
__maintainer__ = 'Thomas Steinbach'
7+
__email__ = 'thomas.t.steinbach@deutschebahn.com'

gcip/addons/kaniko/jobs.py

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
from typing import Dict, List, Optional
2+
3+
from gcip import Job, PredefinedVariables
4+
5+
__author__ = "Daniel von Eßen"
6+
__copyright__ = "Copyright 2020 DB Systel GmbH"
7+
__credits__ = ["Daniel von Eßen", "Thomas Steinbach"]
8+
# SPDX-License-Identifier: Apache-2.0
9+
__license__ = 'Apache-2.0'
10+
__maintainer__ = 'Thomas Steinbach'
11+
__email__ = 'thomas.t.steinbach@deutschebahn.com'
12+
13+
14+
def execute(
15+
gitlab_executor_image: Optional[str] = "gcr.io/kaniko-project/executor:latest",
16+
context: Optional[str] = None,
17+
image_name: Optional[str] = None,
18+
image_tag: Optional[str] = None,
19+
registries: List[str] = list(),
20+
tar_path: Optional[str] = None,
21+
build_args: Dict[str, str] = {},
22+
build_target: str = None,
23+
dockerfile: Optional[str] = None,
24+
enable_push: bool = False,
25+
verbosity: Optional[str] = None,
26+
ecr_login: bool = False,
27+
dockerhub_user_env_var: Optional[str] = None,
28+
dockerhub_login_env_var: Optional[str] = None,
29+
):
30+
"""
31+
Creates a job which builds container images.
32+
33+
This job creates images depending on their git branches.
34+
e.g If the branch which gets pushed to the remote is named
35+
`my_awsome_feature` the image
36+
37+
Args:
38+
gitlab_executor_image (str): The Gitlab executor image this `gcip.core.job.Job` should run with. Must contain the kaniko
39+
```executor``` binary. If set to `None`, no image will be set for this job.
40+
Defaults to ```gcr.io/kaniko-project/executor:latest```.
41+
context (Optional[str], optional): Context which will be send to kaniko. Defaults to `None` which implies the local
42+
directory is the context.
43+
image_name (Optional[str], optional): Image name which will be created. Defaults to PredefinedVariables.CI_PROJECT_NAME.
44+
image_tag (Optional[str]): The tag the image will be tagged with. Defaults to `PredefinedVariables.CI_COMMIT_REF_SLUG`.
45+
registries (Optional[List[str]], optional): List of container registries to push created image to. Defaults to an empty list.
46+
tar_path (Optional[str], optional): Container images created by kaniko are tarball files.
47+
This is the path where to store the image, will be named with suffix `.tar`. This path will be created if not present.
48+
Defaults to `None` which implies the image will be pushed to ```hub.docker.com```.
49+
build_args (Dict[str, str], optional): Container build arguments, used to instrument the container image build. Defaults to {}.
50+
build_target (Optional[str], optional): For container multistage builds name of the build stage you want to create.
51+
Image tag will be appended with the build_target. e.g. latest-buildtarget. Defaults to None.
52+
dockerfile (str, optional): Name of the dockerfile to use. File is relative to context. Defaults to "Dockerfile".
53+
enable_push (bool, optional): Enable push to container registry, disabled to allow subsequent jobs to act on container tarball.
54+
Defaults to False.
55+
verbosity (str, optional): Verbosity of kaniko logging. Defaults to "info".
56+
ecr_login (bool): If ```ecr-login``` should be registered as ```credStore``` in the ```.docker/config.json```.
57+
Mutually exclusive with `dockerhub_user_env_var` and `dockerhub_login_env_var`. Defaults to `False`.
58+
dockerhub_user_env_var (Optional[str]): If you have to login to the docker registry before the push, you have to provide
59+
the name of the environment variable, which contains the username value, here.
60+
**DO NOT PROVIDE THE USERNAME VALUE ITSELF!** This would be a security issue!
61+
Mutually exclusive with `ecr_login`.
62+
Defaults to `None` which skips the docker login attempt.
63+
dockerhub_login_env_var (Optional[str]): If you have to login to the docker registry before the push, you have to provide
64+
the name of the environment variable, which contains the password or token, here.
65+
**DO NOT PROVIDE THE LOGIN VALUE ITSELF!** This would be a security issue!
66+
Mutually exclusive with `ecr_login`.
67+
Defaults to `None` which skips the docker login attempt.
68+
69+
Returns:
70+
Job: gcip.Job will be returned to create container images.
71+
"""
72+
73+
if ecr_login and (dockerhub_user_env_var or dockerhub_login_env_var):
74+
raise ValueError("`ecr_login` is mutually exclusive with `dockerhub_user_env_var` and `dockerhub_login_env_var`.")
75+
76+
job = Job(
77+
name="kaniko",
78+
namespace="execute",
79+
script="date",
80+
)
81+
82+
if image_name is None:
83+
image_name = PredefinedVariables.CI_PROJECT_NAME
84+
85+
image_tag_postfix = ""
86+
if image_tag:
87+
image_tag_postfix = f":{image_tag}"
88+
89+
executor_cmd: List[str] = ["executor"]
90+
91+
if context:
92+
if context.endswith("/"):
93+
context = context[:-1]
94+
executor_cmd.append(f"--context {context}")
95+
96+
if tar_path:
97+
if tar_path.endswith("/"):
98+
tar_path = tar_path[:-1]
99+
executor_cmd.append(f"--tarPath {tar_path}/{image_name}.tar")
100+
job.append_scripts(f"mkdir -p {tar_path}")
101+
102+
if verbosity:
103+
executor_cmd.append(f"--verbosity {verbosity}")
104+
105+
if dockerfile:
106+
executor_cmd.append(f"--dockerfile {dockerfile}")
107+
108+
# Disable push to registries.
109+
if not enable_push:
110+
executor_cmd.append("--no-push")
111+
112+
# Check if multistage build is wanted.
113+
# Add --target flag to executor and prefix build_target "-"
114+
build_target_postfix = ""
115+
if build_target:
116+
executor_cmd.append(f"--target {build_target}")
117+
build_target_postfix = f"-{build_target}"
118+
119+
# Compose build arguments.
120+
for k, v in build_args.items():
121+
executor_cmd.append(f"--build-arg '{k}={v}'")
122+
123+
# Extend executor comman with --destination per registry
124+
if len(registries) == 0:
125+
executor_cmd.append(f"--destination {image_name}{image_tag_postfix}{build_target_postfix}")
126+
if image_tag and (image_tag == "main" or image_tag == "master"):
127+
executor_cmd.append(f"--destination {image_name}:latest{build_target_postfix}")
128+
129+
for registry in registries:
130+
executor_cmd.append(f"--destination {registry}/{image_name}{image_tag_postfix}{build_target_postfix}")
131+
if image_tag and (image_tag == "main" or image_tag == "master"):
132+
executor_cmd.append(f"--destination {registry}/{image_name}:latest{build_target_postfix}")
133+
134+
if ecr_login:
135+
job.prepend_scripts('mkdir -p /kaniko/.docker && echo "{\\"credsStore\\":\\"ecr-login\\"}" > /kaniko/.docker/config.json')
136+
137+
if dockerhub_user_env_var and dockerhub_login_env_var:
138+
# auth=$(echo "$DOCKER_USER:$DOCKER_LOGIN" | base64)
139+
auth = f'$(echo "${dockerhub_user_env_var}:${dockerhub_login_env_var}" | base64)'
140+
job.prepend_scripts(
141+
'mkdir -p /kaniko/.docker && echo "{\\"auths\\":{\\"https://index.docker.io/v1/\\":{\\"auth\\":\\"' + auth +
142+
'\\"}}}" > /kaniko/.docker/config.json'
143+
)
144+
145+
job.append_scripts(" ".join(executor_cmd), "rm -rf /kaniko/.docker/config.json")
146+
147+
if gitlab_executor_image:
148+
job.set_image(gitlab_executor_image)
149+
return job

setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ statistics = True
33
doctests = True
44
max_line_length = 140
55
max_doc_length = 140
6-
max-complexity = 18
6+
max-complexity = 20
77

88
[yapf]
99
arithmetic_precedence_indication=True

0 commit comments

Comments
 (0)