Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_image_build.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2023, Felix Fontein <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: docker_image_build
11
12 short_description: Build Docker images using Docker buildx
13
14 version_added: 3.6.0
15
16 description:
17 - This module allows you to build Docker images using Docker's buildx plugin (BuildKit).
18 - Note that the module is B(not idempotent) in the sense of classical Ansible modules. The only idempotence check is whether
19 the built image already exists. This check can be disabled with the O(rebuild) option.
20 extends_documentation_fragment:
21 - community.docker._docker.cli_documentation
22 - community.docker._attributes
23 - community.docker._attributes.actiongroup_docker
24
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: none
30 idempotent:
31 support: partial
32 details:
33 - If O(rebuild=always) the module is not idempotent.
34
35 options:
36 name:
37 description:
38 - 'Image name. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When pushing or
39 pulling an image the name can optionally include the tag by appending C(:tag_name).'
40 - Note that image IDs (hashes) and names with digest cannot be used.
41 type: str
42 required: true
43 tag:
44 description:
45 - Tag for the image name O(name) that is to be tagged.
46 - If O(name)'s format is C(name:tag), then the tag value from O(name) will take precedence.
47 type: str
48 default: latest
49 path:
50 description:
51 - The path for the build environment.
52 type: path
53 required: true
54 dockerfile:
55 description:
56 - Provide an alternate name for the Dockerfile to use when building an image.
57 - This can also include a relative path (relative to O(path)).
58 type: str
59 cache_from:
60 description:
61 - List of image names to consider as cache source.
62 type: list
63 elements: str
64 pull:
65 description:
66 - When building an image downloads any updates to the FROM image in Dockerfile.
67 type: bool
68 default: false
69 network:
70 description:
71 - The network to use for C(RUN) build instructions.
72 type: str
73 nocache:
74 description:
75 - Do not use cache when building an image.
76 type: bool
77 default: false
78 etc_hosts:
79 description:
80 - Extra hosts to add to C(/etc/hosts) in building containers, as a mapping of hostname to IP address.
81 - Instead of an IP address, the special value V(host-gateway) can also be used, which resolves to the host's gateway
82 IP and allows building containers to connect to services running on the host.
83 type: dict
84 args:
85 description:
86 - Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive.
87 - Docker expects the value to be a string. For convenience any non-string values will be converted to strings.
88 type: dict
89 target:
90 description:
91 - When building an image specifies an intermediate build stage by name as a final stage for the resulting image.
92 type: str
93 platform:
94 description:
95 - Platforms in the format C(os[/arch[/variant]]).
96 - Since community.docker 3.10.0 this can be a list of platforms, instead of just a single platform.
97 type: list
98 elements: str
99 shm_size:
100 description:
101 - Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer. Unit can be V(B) (byte), V(K) (kibibyte,
102 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
103 - Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses V(64M).
104 type: str
105 labels:
106 description:
107 - Dictionary of key value pairs.
108 type: dict
109 rebuild:
110 description:
111 - Defines the behavior of the module if the image to build (as specified in O(name) and O(tag)) already exists.
112 type: str
113 choices:
114 - never
115 - always
116 default: never
117 secrets:
118 description:
119 - Secrets to expose to the build.
120 type: list
121 elements: dict
122 version_added: 3.10.0
123 suboptions:
124 id:
125 description:
126 - The secret identifier.
127 - The secret will be made available as a file in the container under C(/run/secrets/<id>).
128 type: str
129 required: true
130 type:
131 description:
132 - Type of the secret.
133 type: str
134 choices:
135 file:
136 - Reads the secret from a file on the target.
137 - The file must be specified in O(secrets[].src).
138 env:
139 - Reads the secret from an environment variable on the target.
140 - The environment variable must be named in O(secrets[].env).
141 - Note that this requires the Buildkit plugin to have version 0.6.0 or newer.
142 value:
143 - Provides the secret from a given value O(secrets[].value).
144 - B(Note) that the secret will be passed as an environment variable to C(docker compose). Use another mean of
145 transport if you consider this not safe enough.
146 - Note that this requires the Buildkit plugin to have version 0.6.0 or newer.
147 required: true
148 src:
149 description:
150 - Source path of the secret.
151 - Only supported and required for O(secrets[].type=file).
152 type: path
153 env:
154 description:
155 - Environment value of the secret.
156 - Only supported and required for O(secrets[].type=env).
157 type: str
158 value:
159 description:
160 - Value of the secret.
161 - B(Note) that the secret will be passed as an environment variable to C(docker compose). Use another mean of transport
162 if you consider this not safe enough.
163 - Only supported and required for O(secrets[].type=value).
164 type: str
165 outputs:
166 description:
167 - Output destinations.
168 - You can provide a list of exporters to export the built image in various places. Note that not all exporters might
169 be supported by the build driver used.
170 - Note that depending on how this option is used, no image with name O(name) and tag O(tag) might be created, which
171 can cause the basic idempotency this module offers to not work.
172 - Providing an empty list to this option is equivalent to not specifying it at all. The default behavior is a single
173 entry with O(outputs[].type=image).
174 - B(Note) that since community.docker 4.2.0, an entry for O(name)/O(tag) is added if O(outputs) has at least one entry
175 and no entry has type O(outputs[].type=image) and includes O(name)/O(tag) in O(outputs[].name). This is because the
176 module would otherwise pass C(--tag name:image) to the buildx plugin, which for some reason overwrites all images
177 in O(outputs) by the C(name:image) provided in O(name)/O(tag).
178 type: list
179 elements: dict
180 version_added: 3.10.0
181 suboptions:
182 type:
183 description:
184 - The type of exporter to use.
185 type: str
186 choices:
187 local:
188 - This export type writes all result files to a directory on the client. The new files will be owned by the current
189 user. On multi-platform builds, all results will be put in subdirectories by their platform.
190 - The destination has to be provided in O(outputs[].dest).
191 tar:
192 - This export type export type writes all result files as a single tarball on the client. On multi-platform builds,
193 all results will be put in subdirectories by their platform.
194 - The destination has to be provided in O(outputs[].dest).
195 oci:
196 - This export type writes the result image or manifest list as an L(OCI image layout,
197 https://github.com/opencontainers/image-spec/blob/v1.0.1/image-layout.md)
198 tarball on the client.
199 - The destination has to be provided in O(outputs[].dest).
200 docker:
201 - This export type writes the single-platform result image as a Docker image specification tarball on the client.
202 Tarballs created by this exporter are also OCI compatible.
203 - The destination can be provided in O(outputs[].dest). If not specified, the tar will be loaded automatically
204 to the local image store.
205 - The Docker context where to import the result can be provided in O(outputs[].context).
206 image:
207 - This exporter writes the build result as an image or a manifest list. When using this driver, the image will
208 appear in C(docker images).
209 - The image name can be provided in O(outputs[].name). If it is not provided, O(name) and O(tag) will be used.
210 - Optionally, image can be automatically pushed to a registry by setting O(outputs[].push=true).
211 required: true
212 dest:
213 description:
214 - The destination path.
215 - Required for O(outputs[].type=local), O(outputs[].type=tar), O(outputs[].type=oci).
216 - Optional for O(outputs[].type=docker).
217 type: path
218 context:
219 description:
220 - Name for the Docker context where to import the result.
221 - Optional for O(outputs[].type=docker).
222 type: str
223 name:
224 description:
225 - Name(s) under which the image is stored under.
226 - If not provided, O(name) and O(tag) will be used.
227 - Optional for O(outputs[].type=image).
228 - This can be a list of strings since community.docker 4.2.0.
229 type: list
230 elements: str
231 push:
232 description:
233 - Whether to push the built image to a registry.
234 - Only used for O(outputs[].type=image).
235 type: bool
236 default: false
237 requirements:
238 - "Docker CLI with Docker buildx plugin"
239
240 author:
241 - Felix Fontein (@felixfontein)
242
243 seealso:
244 - module: community.docker.docker_image_push
245 - module: community.docker.docker_image_tag
246 """
247
248 EXAMPLES = r"""
249 ---
250 - name: Build Python 3.12 image
251 community.docker.docker_image_build:
252 name: localhost/python/3.12:latest
253 path: /home/user/images/python
254 dockerfile: Dockerfile-3.12
255
256 - name: Build multi-platform image
257 community.docker.docker_image_build:
258 name: multi-platform-image
259 tag: "1.5.2"
260 path: /home/user/images/multi-platform
261 platform:
262 - linux/amd64
263 - linux/arm64/v8
264 """
265
266 RETURN = r"""
267 image:
268 description: Image inspection results for the affected image.
269 returned: success
270 type: dict
271 sample: {}
272
273 command:
274 description: The command executed.
275 returned: success and for some failures
276 type: list
277 elements: str
278 version_added: 4.2.0
279 """
280
281 import base64
282 import os
283 import traceback
284 import typing as t
285
286 from ansible.module_utils.common.text.converters import to_text
287 from ansible.module_utils.common.text.formatters import human_to_bytes
288
289 from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
290 parse_repository_tag,
291 )
292 from ansible_collections.community.docker.plugins.module_utils._common_cli import (
293 AnsibleModuleDockerClient,
294 DockerException,
295 )
296 from ansible_collections.community.docker.plugins.module_utils._util import (
297 DockerBaseClass,
298 clean_dict_booleans_for_docker_api,
299 is_image_name_id,
300 is_valid_tag,
301 )
302 from ansible_collections.community.docker.plugins.module_utils._version import (
303 LooseVersion,
304 )
305
306 if t.TYPE_CHECKING:
307 from ansible.module_utils.basic import AnsibleModule
308
309
310 def convert_to_bytes(
311 value: str | None,
312 module: AnsibleModule,
313 name: str,
314 unlimited_value: int | None = None,
315 ) -> int | None:
316 if value is None:
317 return value
318 try:
319 if unlimited_value is not None and value in ("unlimited", str(unlimited_value)):
320 return unlimited_value
321 return human_to_bytes(value)
322 except ValueError as exc:
323 module.fail_json(msg=f"Failed to convert {name} to bytes: {exc}")
324
325
326 def dict_to_list(dictionary: dict[str, t.Any], concat: str = "=") -> list[str]:
327 return [f"{k}{concat}{v}" for k, v in sorted(dictionary.items())]
328
329
330 def _quote_csv(text: str) -> str:
331 if text.strip() == text and all(i not in text for i in '",\r\n'):
332 return text
333 text = text.replace('"', '""')
334 return f'"{text}"'
335
336
337 class ImageBuilder(DockerBaseClass):
338 def __init__(self, client: AnsibleModuleDockerClient) -> None:
339 super().__init__()
340 self.client = client
341 self.check_mode = self.client.check_mode
342 parameters = self.client.module.params
343
344 self.cache_from = parameters["cache_from"]
345 self.pull = parameters["pull"]
346 self.network = parameters["network"]
347 self.nocache = parameters["nocache"]
348 self.etc_hosts = clean_dict_booleans_for_docker_api(parameters["etc_hosts"])
349 self.args = clean_dict_booleans_for_docker_api(parameters["args"])
350 self.target = parameters["target"]
351 self.platform = parameters["platform"]
352 self.shm_size = convert_to_bytes(
353 parameters["shm_size"], self.client.module, "shm_size"
354 )
355 self.labels = clean_dict_booleans_for_docker_api(parameters["labels"])
356 self.rebuild = parameters["rebuild"]
357 self.secrets = parameters["secrets"]
358 self.outputs = parameters["outputs"]
359
360 buildx = self.client.get_client_plugin_info("buildx")
361 if buildx is None:
362 self.fail(
363 f"Docker CLI {self.client.get_cli()} does not have the buildx plugin installed"
364 )
365 buildx_version = buildx["Version"].lstrip("v")
366
367 if self.secrets:
368 for secret in self.secrets:
369 if secret["type"] in ("env", "value") and LooseVersion(
370 buildx_version
371 ) < LooseVersion("0.6.0"):
372 self.fail(
373 f"The Docker buildx plugin has version {buildx_version}, but 0.6.0 is needed for secrets of type=env and type=value"
374 )
375 if (
376 self.outputs
377 and len(self.outputs) > 1
378 and LooseVersion(buildx_version) < LooseVersion("0.13.0")
379 ):
380 self.fail(
381 f"The Docker buildx plugin has version {buildx_version}, but 0.13.0 is needed to specify more than one output"
382 )
383
384 self.path = parameters["path"]
385 if not os.path.isdir(self.path):
386 self.fail(f'"{self.path}" is not an existing directory')
387 self.dockerfile = parameters["dockerfile"]
388 if self.dockerfile and not os.path.isfile(
389 os.path.join(self.path, self.dockerfile)
390 ):
391 self.fail(
392 f'"{os.path.join(self.path, self.dockerfile)}" is not an existing file'
393 )
394
395 self.name = parameters["name"]
396 self.tag = parameters["tag"]
397 if not is_valid_tag(self.tag, allow_empty=True):
398 self.fail(f'"{self.tag}" is not a valid docker tag')
399 if is_image_name_id(self.name):
400 self.fail("Image name must not be a digest")
401
402 # If name contains a tag, it takes precedence over tag parameter.
403 repo, repo_tag = parse_repository_tag(self.name)
404 if repo_tag:
405 self.name = repo
406 self.tag = repo_tag
407
408 if is_image_name_id(self.tag):
409 self.fail("Image name must not contain a digest, but have a tag")
410
411 if self.outputs:
412 found = False
413 name_tag = f"{self.name}:{self.tag}"
414 for output in self.outputs:
415 if output["type"] == "image":
416 if not output["name"]:
417 # Since we no longer pass --tag if --output is provided, we need to set this manually
418 output["name"] = [name_tag]
419 if output["name"] and name_tag in output["name"]:
420 found = True
421 if not found:
422 self.outputs.append(
423 {
424 "type": "image",
425 "name": [name_tag],
426 "push": False,
427 }
428 )
429 if LooseVersion(buildx_version) < LooseVersion("0.13.0"):
430 self.fail(
431 f"The output does not include an image with name {name_tag}, and the Docker"
432 f" buildx plugin has version {buildx_version} which only supports one output."
433 )
434
435 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
436 self.client.fail(msg, **kwargs)
437
438 def add_list_arg(self, args: list[str], option: str, values: list[str]) -> None:
439 for value in values:
440 args.extend([option, value])
441
442 def add_args(self, args: list[str]) -> dict[str, t.Any]:
443 environ_update = {}
444 if not self.outputs:
445 args.extend(["--tag", f"{self.name}:{self.tag}"])
446 if self.dockerfile:
447 args.extend(["--file", os.path.join(self.path, self.dockerfile)])
448 if self.cache_from:
449 self.add_list_arg(args, "--cache-from", self.cache_from)
450 if self.pull:
451 args.append("--pull")
452 if self.network:
453 args.extend(["--network", self.network])
454 if self.nocache:
455 args.append("--no-cache")
456 if self.etc_hosts:
457 self.add_list_arg(args, "--add-host", dict_to_list(self.etc_hosts, ":"))
458 if self.args:
459 self.add_list_arg(args, "--build-arg", dict_to_list(self.args))
460 if self.target:
461 args.extend(["--target", self.target])
462 if self.platform:
463 for platform in self.platform:
464 args.extend(["--platform", platform])
465 if self.shm_size:
466 args.extend(["--shm-size", str(self.shm_size)])
467 if self.labels:
468 self.add_list_arg(args, "--label", dict_to_list(self.labels))
469 if self.secrets:
470 random_prefix = None
471 for index, secret in enumerate(self.secrets):
472 sid = secret["id"]
473 if secret["type"] == "file":
474 src = secret["src"]
475 args.extend(["--secret", f"id={sid},type=file,src={src}"])
476 if secret["type"] == "env":
477 env = secret["src"]
478 args.extend(["--secret", f"id={sid},type=env,env={env}"])
479 if secret["type"] == "value":
480 # We pass values on using environment variables. The user has been warned in the documentation
481 # that they should only use this mechanism when being comfortable with it.
482 if random_prefix is None:
483 # Use /dev/urandom to generate some entropy to make the environment variable's name unguessable
484 random_prefix = (
485 base64.b64encode(os.urandom(16))
486 .decode("utf-8")
487 .replace("=", "")
488 )
489 env_name = (
490 f"ANSIBLE_DOCKER_COMPOSE_ENV_SECRET_{random_prefix}_{index}"
491 )
492 environ_update[env_name] = secret["value"]
493 args.extend(["--secret", f"id={sid},type=env,env={env_name}"])
494 if self.outputs:
495 for output in self.outputs:
496 subargs = []
497 if output["type"] == "local":
498 dest = output["dest"]
499 subargs.extend(["type=local", f"dest={dest}"])
500 if output["type"] == "tar":
501 dest = output["dest"]
502 subargs.extend(["type=tar", f"dest={dest}"])
503 if output["type"] == "oci":
504 dest = output["dest"]
505 subargs.extend(["type=oci", f"dest={dest}"])
506 if output["type"] == "docker":
507 subargs.append("type=docker")
508 dest = output["dest"]
509 if output["dest"] is not None:
510 subargs.append(f"dest={dest}")
511 if output["context"] is not None:
512 context = output["context"]
513 subargs.append(f"context={context}")
514 if output["type"] == "image":
515 subargs.append("type=image")
516 if output["name"] is not None:
517 name = ",".join(output["name"])
518 subargs.append(f"name={name}")
519 if output["push"]:
520 subargs.append("push=true")
521 if subargs:
522 args.extend(
523 ["--output", ",".join(_quote_csv(subarg) for subarg in subargs)]
524 )
525 return environ_update
526
527 def build_image(self) -> dict[str, t.Any]:
528 image = self.client.find_image(self.name, self.tag)
529 results: dict[str, t.Any] = {
530 "changed": False,
531 "actions": [],
532 "image": image or {},
533 }
534
535 if image and self.rebuild == "never":
536 return results
537
538 results["changed"] = True
539 if not self.check_mode:
540 args = ["buildx", "build", "--progress", "plain"]
541 environ_update = self.add_args(args)
542 args.extend(["--", self.path])
543 rc, stdout, stderr = self.client.call_cli(
544 *args, environ_update=environ_update
545 )
546 if rc != 0:
547 self.fail(
548 f"Building {self.name}:{self.tag} failed",
549 stdout=to_text(stdout),
550 stderr=to_text(stderr),
551 command=args,
552 )
553 results["stdout"] = to_text(stdout)
554 results["stderr"] = to_text(stderr)
555 results["image"] = self.client.find_image(self.name, self.tag) or {}
556 results["command"] = args
557
558 return results
559
560
561 def main() -> None:
562 argument_spec = {
563 "name": {"type": "str", "required": True},
564 "tag": {"type": "str", "default": "latest"},
565 "path": {"type": "path", "required": True},
566 "dockerfile": {"type": "str"},
567 "cache_from": {"type": "list", "elements": "str"},
568 "pull": {"type": "bool", "default": False},
569 "network": {"type": "str"},
570 "nocache": {"type": "bool", "default": False},
571 "etc_hosts": {"type": "dict"},
572 "args": {"type": "dict"},
573 "target": {"type": "str"},
574 "platform": {"type": "list", "elements": "str"},
575 "shm_size": {"type": "str"},
576 "labels": {"type": "dict"},
577 "rebuild": {"type": "str", "choices": ["never", "always"], "default": "never"},
578 "secrets": {
579 "type": "list",
580 "elements": "dict",
581 "options": {
582 "id": {"type": "str", "required": True},
583 "type": {
584 "type": "str",
585 "choices": ["file", "env", "value"],
586 "required": True,
587 },
588 "src": {"type": "path"},
589 "env": {"type": "str"},
590 "value": {"type": "str", "no_log": True},
591 },
592 "required_if": [
593 ("type", "file", ["src"]),
594 ("type", "env", ["env"]),
595 ("type", "value", ["value"]),
596 ],
597 "mutually_exclusive": [
598 ("src", "env", "value"),
599 ],
600 "no_log": False,
601 },
602 "outputs": {
603 "type": "list",
604 "elements": "dict",
605 "options": {
606 "type": {
607 "type": "str",
608 "choices": ["local", "tar", "oci", "docker", "image"],
609 "required": True,
610 },
611 "dest": {"type": "path"},
612 "context": {"type": "str"},
613 "name": {"type": "list", "elements": "str"},
614 "push": {"type": "bool", "default": False},
615 },
616 "required_if": [
617 ("type", "local", ["dest"]),
618 ("type", "tar", ["dest"]),
619 ("type", "oci", ["dest"]),
620 ],
621 "mutually_exclusive": [
622 ("dest", "name"),
623 ("dest", "push"),
624 ("context", "name"),
625 ("context", "push"),
626 ],
627 },
628 }
629
630 client = AnsibleModuleDockerClient(
631 argument_spec=argument_spec,
632 supports_check_mode=True,
633 needs_api_version=False,
634 )
635
636 try:
637 results = ImageBuilder(client).build_image()
638 client.module.exit_json(**results)
639 except DockerException as e:
640 client.fail(
641 f"An unexpected Docker error occurred: {e}",
642 exception=traceback.format_exc(),
643 )
644
645
646 if __name__ == "__main__":
647 main()