Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright 2016 Red Hat | Ansible
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
11
12 short_description: Manage docker images
13
14 description:
15 - Build, load or pull an image, making the image available for creating containers. Also supports tagging an image, pushing
16 an image, and archiving an image to a C(.tar) file.
17 - We recommend to use the individual modules M(community.docker.docker_image_build), M(community.docker.docker_image_export),
18 M(community.docker.docker_image_load), M(community.docker.docker_image_pull), M(community.docker.docker_image_push),
19 M(community.docker.docker_image_remove), and M(community.docker.docker_image_tag) instead of this module.
20 notes:
21 - Building images is done using Docker daemon's API. It is not possible to use BuildKit / buildx this way. Use M(community.docker.docker_image_build)
22 to build images with BuildKit.
23 - Exporting images is generally not idempotent. It depends on whether the image ID equals the IDs found in the generated tarball's C(manifest.json).
24 This was the case with the default storage backend up to Docker 28, but seems to have changed in Docker 29.
25 extends_documentation_fragment:
26 - community.docker._docker.api_documentation
27 - community.docker._attributes
28 - community.docker._attributes.actiongroup_docker
29
30 attributes:
31 check_mode:
32 support: partial
33 details:
34 - When trying to pull an image, the module assumes this is always changed in check mode.
35 diff_mode:
36 support: none
37 idempotent:
38 support: partial
39 details:
40 - Whether the module is idempotent depends on the exact parameters, in particular of O(force_source) and O(force_tag).
41 # TODO: improve idempotent details!
42
43 options:
44 source:
45 description:
46 - Determines where the module will try to retrieve the image from.
47 - Use V(build) to build the image from a C(Dockerfile). O(build.path) must be specified when this value is used.
48 - Use V(load) to load the image from a C(.tar) file. O(load_path) must be specified when this value is used.
49 - Use V(pull) to pull the image from a registry.
50 - Use V(local) to make sure that the image is already available on the local docker daemon. This means that the module
51 does not try to build, pull or load the image.
52 type: str
53 choices:
54 - build
55 - load
56 - pull
57 - local
58 build:
59 description:
60 - Specifies options used for building images.
61 type: dict
62 suboptions:
63 cache_from:
64 description:
65 - List of image names to consider as cache source.
66 type: list
67 elements: str
68 dockerfile:
69 description:
70 - Use with O(state=present) and O(source=build) to provide an alternate name for the Dockerfile to use when building
71 an image.
72 - This can also include a relative path (relative to O(build.path)).
73 type: str
74 http_timeout:
75 description:
76 - Timeout for HTTP requests during the image build operation. Provide a positive integer value for the number of
77 seconds.
78 type: int
79 path:
80 description:
81 - Use with state 'present' to build an image. Will be the path to a directory containing the context and Dockerfile
82 for building an image.
83 type: path
84 required: true
85 pull:
86 description:
87 - When building an image downloads any updates to the FROM image in Dockerfile.
88 type: bool
89 default: false
90 rm:
91 description:
92 - Remove intermediate containers after build.
93 type: bool
94 default: true
95 network:
96 description:
97 - The network to use for C(RUN) build instructions.
98 type: str
99 nocache:
100 description:
101 - Do not use cache when building an image.
102 type: bool
103 default: false
104 etc_hosts:
105 description:
106 - Extra hosts to add to C(/etc/hosts) in building containers, as a mapping of hostname to IP address.
107 - Instead of an IP address, the special value V(host-gateway) can also be used, which resolves to the host's gateway
108 IP and allows building containers to connect to services running on the host.
109 type: dict
110 args:
111 description:
112 - Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive.
113 - Docker expects the value to be a string. For convenience any non-string values will be converted to strings.
114 type: dict
115 container_limits:
116 description:
117 - A dictionary of limits applied to each container created by the build process.
118 type: dict
119 suboptions:
120 memory:
121 description:
122 - Memory limit for build in format C(<number>[<unit>]). Number is a positive integer. Unit can be V(B) (byte),
123 V(K) (kibibyte, 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
124 - Omitting the unit defaults to bytes.
125 - Before community.docker 3.6.0, no units were allowed.
126 type: str
127 memswap:
128 description:
129 - Total memory limit (memory + swap) for build in format C(<number>[<unit>]), or the special values V(unlimited)
130 or V(-1) for unlimited swap usage. Number is a positive integer. Unit can be V(B) (byte), V(K) (kibibyte,
131 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
132 - Omitting the unit defaults to bytes.
133 - Before community.docker 3.6.0, no units were allowed, and neither was the special value V(unlimited).
134 type: str
135 cpushares:
136 description:
137 - CPU shares (relative weight).
138 type: int
139 cpusetcpus:
140 description:
141 - CPUs in which to allow execution.
142 - For example, V(0-3) or V(0,1).
143 type: str
144 use_config_proxy:
145 description:
146 - If set to V(true) and a proxy configuration is specified in the docker client configuration (by default C($HOME/.docker/config.json)),
147 the corresponding environment variables will be set in the container being built.
148 type: bool
149 target:
150 description:
151 - When building an image specifies an intermediate build stage by name as a final stage for the resulting image.
152 type: str
153 platform:
154 description:
155 - Platform in the format C(os[/arch[/variant]]).
156 type: str
157 version_added: 1.1.0
158 shm_size:
159 description:
160 - Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer. Unit can be V(B) (byte), V(K) (kibibyte,
161 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
162 - Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses V(64M).
163 type: str
164 version_added: 3.6.0
165 labels:
166 description:
167 - Dictionary of key value pairs.
168 type: dict
169 version_added: 3.6.0
170 archive_path:
171 description:
172 - Use with O(state=present) to archive an image to a C(.tar) file.
173 type: path
174 load_path:
175 description:
176 - Use with O(state=present) to load an image from a C(.tar) file.
177 - Set O(source=load) if you want to load the image.
178 type: path
179 force_source:
180 description:
181 - Use with O(state=present) to build, load or pull an image (depending on the value of the O(source) option) when the
182 image already exists.
183 type: bool
184 default: false
185 force_absent:
186 description:
187 - Use with O(state=absent) to un-tag and remove all images matching the specified name.
188 type: bool
189 default: false
190 force_tag:
191 description:
192 - Use with O(state=present) to force tagging an image.
193 type: bool
194 default: false
195 name:
196 description:
197 - 'Image name. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When pushing or
198 pulling an image the name can optionally include the tag by appending C(:tag_name).'
199 - Note that image IDs (hashes) are only supported for O(state=absent), for O(state=present) with O(source=load), and
200 for O(state=present) with O(source=local).
201 type: str
202 required: true
203 pull:
204 description:
205 - Specifies options used for pulling images.
206 type: dict
207 version_added: 1.3.0
208 suboptions:
209 platform:
210 description:
211 - When pulling an image, ask for this specific platform.
212 - Note that this value is not used to determine whether the image needs to be pulled. This might change in the future
213 in a minor release, though.
214 type: str
215 push:
216 description:
217 - Push the image to the registry. Specify the registry as part of the O(name) or O(repository) parameter.
218 type: bool
219 default: false
220 repository:
221 description:
222 - Use with O(state=present) to tag the image.
223 - Expects format C(repository:tag). If no tag is provided, will use the value of the O(tag) parameter or V(latest).
224 - If O(push=true), O(repository) must either include a registry, or will be assumed to belong to the default registry
225 (Docker Hub).
226 type: str
227 state:
228 description:
229 - Make assertions about the state of an image.
230 - When V(absent) an image will be removed. Use the force option to un-tag and remove all images matching the provided
231 name.
232 - When V(present) check if an image exists using the provided name and tag. If the image is not found or the force option
233 is used, the image will either be pulled, built or loaded, depending on the O(source) option.
234 type: str
235 default: present
236 choices:
237 - absent
238 - present
239 tag:
240 description:
241 - Used to select an image when pulling. Will be added to the image when pushing, tagging or building. Defaults to V(latest).
242 - If O(name) parameter format is C(name:tag), then tag value from O(name) will take precedence.
243 type: str
244 default: latest
245
246 requirements:
247 - "Docker API >= 1.25"
248
249 author:
250 - Pavel Antonov (@softzilla)
251 - Chris Houseknecht (@chouseknecht)
252 - Sorin Sbarnea (@ssbarnea)
253
254 seealso:
255 - module: community.docker.docker_image_build
256 - module: community.docker.docker_image_export
257 - module: community.docker.docker_image_info
258 - module: community.docker.docker_image_load
259 - module: community.docker.docker_image_pull
260 - module: community.docker.docker_image_push
261 - module: community.docker.docker_image_remove
262 - module: community.docker.docker_image_tag
263 """
264
265 EXAMPLES = r"""
266 ---
267 - name: Pull an image
268 community.docker.docker_image:
269 name: pacur/centos-7
270 source: pull
271 # Select platform for pulling. If not specified, will pull whatever docker prefers.
272 pull:
273 platform: amd64
274
275 - name: Tag and push to docker hub
276 community.docker.docker_image:
277 name: pacur/centos-7:56
278 repository: dcoppenhagan/myimage:7.56
279 push: true
280 source: local
281
282 - name: Tag and push to local registry
283 community.docker.docker_image:
284 # Image will be centos:7
285 name: centos
286 # Will be pushed to localhost:5000/centos:7
287 repository: localhost:5000/centos
288 tag: 7
289 push: true
290 source: local
291
292 - name: Add tag latest to image
293 community.docker.docker_image:
294 name: myimage:7.1.2
295 repository: myimage:latest
296 # As 'latest' usually already is present, we need to enable overwriting of existing tags:
297 force_tag: true
298 source: local
299
300 - name: Remove image
301 community.docker.docker_image:
302 state: absent
303 name: registry.ansible.com/chouseknecht/sinatra
304 tag: v1
305
306 - name: Build an image and push it to a private repo
307 community.docker.docker_image:
308 build:
309 path: ./sinatra
310 name: registry.ansible.com/chouseknecht/sinatra
311 tag: v1
312 push: true
313 source: build
314
315 - name: Archive image
316 community.docker.docker_image:
317 name: registry.ansible.com/chouseknecht/sinatra
318 tag: v1
319 archive_path: my_sinatra.tar
320 source: local
321
322 - name: Load image from archive and push to a private registry
323 community.docker.docker_image:
324 name: localhost:5000/myimages/sinatra
325 tag: v1
326 push: true
327 load_path: my_sinatra.tar
328 source: load
329
330 - name: Build image and with build args
331 community.docker.docker_image:
332 name: myimage
333 build:
334 path: /path/to/build/dir
335 args:
336 log_volume: /var/log/myapp
337 listen_port: 8080
338 source: build
339
340 - name: Build image using cache source
341 community.docker.docker_image:
342 name: myimage:latest
343 build:
344 path: /path/to/build/dir
345 # Use as cache source for building myimage
346 cache_from:
347 - nginx:latest
348 - alpine:3.8
349 source: build
350 """
351
352 RETURN = r"""
353 image:
354 description: Image inspection results for the affected image.
355 returned: success
356 type: dict
357 sample: {}
358 stdout:
359 description: Docker build output when building an image.
360 returned: success
361 type: str
362 sample: ""
363 version_added: 1.0.0
364 """
365
366 import base64
367 import errno
368 import json
369 import os
370 import traceback
371 import typing as t
372
373 from ansible.module_utils.common.text.converters import to_text
374 from ansible.module_utils.common.text.formatters import human_to_bytes
375
376 from ansible_collections.community.docker.plugins.module_utils._api.auth import (
377 get_config_header,
378 resolve_repository_name,
379 )
380 from ansible_collections.community.docker.plugins.module_utils._api.constants import (
381 CONTAINER_LIMITS_KEYS,
382 DEFAULT_DATA_CHUNK_SIZE,
383 )
384 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
385 DockerException,
386 NotFound,
387 )
388 from ansible_collections.community.docker.plugins.module_utils._api.utils.build import (
389 process_dockerfile,
390 tar,
391 )
392 from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
393 format_extra_hosts,
394 parse_repository_tag,
395 )
396 from ansible_collections.community.docker.plugins.module_utils._common_api import (
397 AnsibleDockerClient,
398 RequestException,
399 )
400 from ansible_collections.community.docker.plugins.module_utils._image_archive import (
401 ImageArchiveInvalidException,
402 api_image_id,
403 archived_image_manifest,
404 )
405 from ansible_collections.community.docker.plugins.module_utils._util import (
406 DockerBaseClass,
407 clean_dict_booleans_for_docker_api,
408 is_image_name_id,
409 is_valid_tag,
410 )
411 from ansible_collections.community.docker.plugins.module_utils._version import (
412 LooseVersion,
413 )
414
415 if t.TYPE_CHECKING:
416 from collections.abc import Callable
417
418 from ansible.module_utils.basic import AnsibleModule
419
420
421 def convert_to_bytes(
422 value: str | None,
423 module: AnsibleModule,
424 name: str,
425 unlimited_value: int | None = None,
426 ) -> int | None:
427 if value is None:
428 return value
429 try:
430 if unlimited_value is not None and value in ("unlimited", str(unlimited_value)):
431 return unlimited_value
432 return human_to_bytes(value)
433 except ValueError as exc:
434 module.fail_json(msg=f"Failed to convert {name} to bytes: {exc}")
435
436
437 class ImageManager(DockerBaseClass):
438 def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None:
439 """
440 Configure a docker_image task.
441
442 :param client: Ansible Docker Client wrapper over Docker client
443 :type client: AnsibleDockerClient
444 :param results: This task adds its output values to this dictionary
445 :type results: dict
446 """
447
448 super().__init__()
449
450 self.client = client
451 self.results = results
452 parameters = self.client.module.params
453 self.check_mode = self.client.check_mode
454
455 self.source: t.Literal["build", "load", "pull", "local"] | None = parameters[
456 "source"
457 ]
458 build: dict[str, t.Any] = parameters["build"] or {}
459 pull: dict[str, t.Any] = parameters["pull"] or {}
460 self.archive_path: str | None = parameters["archive_path"]
461 self.cache_from: list[str] | None = build.get("cache_from")
462 self.container_limits: dict[str, t.Any] | None = build.get("container_limits")
463 if self.container_limits and "memory" in self.container_limits:
464 self.container_limits["memory"] = convert_to_bytes(
465 self.container_limits["memory"],
466 self.client.module,
467 "build.container_limits.memory",
468 )
469 if self.container_limits and "memswap" in self.container_limits:
470 self.container_limits["memswap"] = convert_to_bytes(
471 self.container_limits["memswap"],
472 self.client.module,
473 "build.container_limits.memswap",
474 unlimited_value=-1,
475 )
476 self.dockerfile: str | None = build.get("dockerfile")
477 self.force_source: bool = parameters["force_source"]
478 self.force_absent: bool = parameters["force_absent"]
479 self.force_tag: bool = parameters["force_tag"]
480 self.load_path: str | None = parameters["load_path"]
481 self.name: str = parameters["name"]
482 self.network: str | None = build.get("network")
483 self.extra_hosts: dict[str, str] = clean_dict_booleans_for_docker_api(
484 build.get("etc_hosts") # type: ignore
485 )
486 self.nocache: bool = build.get("nocache", False)
487 self.build_path: str | None = build.get("path")
488 self.pull: bool | None = build.get("pull")
489 self.target: str | None = build.get("target")
490 self.repository: str | None = parameters["repository"]
491 self.rm: bool = build.get("rm", True)
492 self.state: t.Literal["absent", "present"] = parameters["state"]
493 self.tag: str = parameters["tag"]
494 self.http_timeout: int | None = build.get("http_timeout")
495 self.pull_platform: str | None = pull.get("platform")
496 self.push: bool = parameters["push"]
497 self.buildargs: dict[str, t.Any] | None = build.get("args")
498 self.build_platform: str | None = build.get("platform")
499 self.use_config_proxy: bool | None = build.get("use_config_proxy")
500 self.shm_size: int | None = convert_to_bytes(
501 build.get("shm_size"), self.client.module, "build.shm_size"
502 )
503 self.labels: dict[str, str] = clean_dict_booleans_for_docker_api(
504 build.get("labels") # type: ignore
505 )
506
507 # If name contains a tag, it takes precedence over tag parameter.
508 if not is_image_name_id(self.name):
509 repo, repo_tag = parse_repository_tag(self.name)
510 if repo_tag:
511 self.name = repo
512 self.tag = repo_tag
513
514 # Sanity check: fail early when we know that something will fail later
515 if self.repository and is_image_name_id(self.repository):
516 self.fail(f"`repository` must not be an image ID; got: {self.repository}")
517 if not self.repository and self.push and is_image_name_id(self.name):
518 self.fail(
519 f"Cannot push an image by ID; specify `repository` to tag and push the image with ID {self.name} instead"
520 )
521
522 if self.state == "present":
523 self.present()
524 elif self.state == "absent":
525 self.absent()
526
527 def fail(self, msg: str) -> t.NoReturn:
528 self.client.fail(msg)
529
530 def present(self) -> None:
531 """
532 Handles state = 'present', which includes building, loading or pulling an image,
533 depending on user provided parameters.
534
535 :returns None
536 """
537 if is_image_name_id(self.name):
538 image = self.client.find_image_by_id(self.name, accept_missing_image=True)
539 else:
540 image = self.client.find_image(name=self.name, tag=self.tag)
541
542 if not image or self.force_source:
543 if self.source == "build":
544 if is_image_name_id(self.name):
545 self.fail(
546 f"Image name must not be an image ID for source=build; got: {self.name}"
547 )
548
549 # Build the image
550 assert self.build_path is not None
551 if not os.path.isdir(self.build_path):
552 self.fail(
553 f"Requested build path {self.build_path} could not be found or you do not have access."
554 )
555 image_name = self.name
556 if self.tag:
557 image_name = f"{self.name}:{self.tag}"
558 self.log(f"Building image {image_name}")
559 self.results["actions"].append(
560 f"Built image {image_name} from {self.build_path}"
561 )
562 self.results["changed"] = True
563 if not self.check_mode:
564 self.results.update(self.build_image())
565
566 elif self.source == "load":
567 assert self.load_path is not None
568 # Load the image from an archive
569 if not os.path.isfile(self.load_path):
570 self.fail(
571 f"Error loading image {self.name}. Specified path {self.load_path} does not exist."
572 )
573 image_name = self.name
574 if self.tag and not is_image_name_id(image_name):
575 image_name = f"{self.name}:{self.tag}"
576 self.results["actions"].append(
577 f"Loaded image {image_name} from {self.load_path}"
578 )
579 self.results["changed"] = True
580 if not self.check_mode:
581 self.results["image"] = self.load_image()
582 elif self.source == "pull":
583 if is_image_name_id(self.name):
584 self.fail(
585 f"Image name must not be an image ID for source=pull; got: {self.name}"
586 )
587
588 # pull the image
589 self.results["actions"].append(f"Pulled image {self.name}:{self.tag}")
590 self.results["changed"] = True
591 if not self.check_mode:
592 self.results["image"], dummy = self.client.pull_image(
593 self.name, tag=self.tag, image_platform=self.pull_platform
594 )
595 elif self.source == "local":
596 if image is None:
597 name = self.name
598 if self.tag and not is_image_name_id(name):
599 name = f"{self.name}:{self.tag}"
600 self.client.fail(f"Cannot find the image {name} locally.")
601 if (
602 not self.check_mode
603 and image
604 and image["Id"] == self.results["image"]["Id"]
605 ):
606 self.results["changed"] = False
607 else:
608 self.results["image"] = image
609
610 if self.archive_path:
611 self.archive_image(self.name, self.tag)
612
613 if self.push and not self.repository:
614 self.push_image(self.name, self.tag)
615 elif self.repository:
616 self.tag_image(self.name, self.tag, self.repository, push=self.push)
617
618 def absent(self) -> None:
619 """
620 Handles state = 'absent', which removes an image.
621
622 :return None
623 """
624 name = self.name
625 if is_image_name_id(name):
626 image = self.client.find_image_by_id(name, accept_missing_image=True)
627 else:
628 image = self.client.find_image(name, self.tag)
629 if self.tag:
630 name = f"{self.name}:{self.tag}"
631 if image:
632 if not self.check_mode:
633 try:
634 self.client.delete_json(
635 "/images/{0}", name, params={"force": self.force_absent}
636 )
637 except NotFound:
638 # If the image vanished while we were trying to remove it, do not fail
639 pass
640 except Exception as exc: # pylint: disable=broad-exception-caught
641 self.fail(f"Error removing image {name} - {exc}")
642
643 self.results["changed"] = True
644 self.results["actions"].append(f"Removed image {name}")
645 self.results["image"]["state"] = "Deleted"
646
647 @staticmethod
648 def archived_image_action(
649 failure_logger: Callable[[str], None],
650 archive_path: str,
651 current_image_name: str,
652 current_image_id: str,
653 ) -> str | None:
654 """
655 If the archive is missing or requires replacement, return an action message.
656
657 :param failure_logger: a logging function that accepts one parameter of type str
658 :type failure_logger: Callable
659 :param archive_path: Filename to write archive to
660 :type archive_path: str
661 :param current_image_name: repo:tag
662 :type current_image_name: str
663 :param current_image_id: Hash, including hash type prefix such as "sha256:"
664 :type current_image_id: str
665
666 :returns: Either None, or an Ansible action message.
667 :rtype: str
668 """
669
670 def build_msg(reason: str) -> str:
671 return f"Archived image {current_image_name} to {archive_path}, {reason}"
672
673 try:
674 archived = archived_image_manifest(archive_path)
675 except ImageArchiveInvalidException as exc:
676 failure_logger(f"Unable to extract manifest summary from archive: {exc}")
677 return build_msg("overwriting an unreadable archive file")
678
679 if archived is None:
680 return build_msg("since none present")
681 if (
682 current_image_id == api_image_id(archived.image_id)
683 and [current_image_name] == archived.repo_tags
684 ):
685 return None
686 name = ", ".join(archived.repo_tags)
687
688 return build_msg(
689 f"overwriting archive with image {archived.image_id} named {name}"
690 )
691
692 def archive_image(self, name: str, tag: str | None) -> None:
693 """
694 Archive an image to a .tar file. Called when archive_path is passed.
695
696 :param name: Name/repository of the image
697 :type name: str
698 :param tag: Optional image tag; assumed to be "latest" if None
699 :type tag: str | None
700 """
701 assert self.archive_path is not None
702
703 if not tag:
704 tag = "latest"
705
706 if is_image_name_id(name):
707 image = self.client.find_image_by_id(name, accept_missing_image=True)
708 image_name = name
709 else:
710 image = self.client.find_image(name=name, tag=tag)
711 image_name = f"{name}:{tag}"
712
713 if not image:
714 self.log(f"archive image: image {image_name} not found")
715 return
716
717 # Will have a 'sha256:' prefix
718 image_id = image["Id"]
719
720 action = self.archived_image_action(
721 self.client.module.debug, self.archive_path, image_name, image_id
722 )
723
724 if action:
725 self.results["actions"].append(action)
726
727 self.results["changed"] = action is not None
728
729 if (not self.check_mode) and self.results["changed"]:
730 self.log(f"Getting archive of image {image_name}")
731 try:
732 saved_image = self.client._stream_raw_result(
733 self.client._get(
734 self.client._url("/images/{0}/get", image_name), stream=True
735 ),
736 chunk_size=DEFAULT_DATA_CHUNK_SIZE,
737 decode=False,
738 )
739 except Exception as exc: # pylint: disable=broad-exception-caught
740 self.fail(f"Error getting image {image_name} - {exc}")
741
742 try:
743 with open(self.archive_path, "wb") as fd:
744 for chunk in saved_image:
745 fd.write(chunk)
746 except Exception as exc: # pylint: disable=broad-exception-caught
747 self.fail(f"Error writing image archive {self.archive_path} - {exc}")
748
749 self.results["image"] = image
750
751 def push_image(self, name: str, tag: str | None = None) -> None:
752 """
753 If the name of the image contains a repository path, then push the image.
754
755 :param name Name of the image to push.
756 :param tag Use a specific tag.
757 :return: None
758 """
759
760 if is_image_name_id(name):
761 self.fail(f"Cannot push an image ID: {name}")
762
763 repository = name
764 if not tag:
765 repository, tag = parse_repository_tag(name)
766 registry, repo_name = resolve_repository_name(repository)
767
768 self.log(f"push {self.name} to {registry}/{repo_name}:{tag}")
769
770 if registry:
771 self.results["actions"].append(
772 f"Pushed image {self.name} to {registry}/{repo_name}:{tag}"
773 )
774 self.results["changed"] = True
775 if not self.check_mode:
776 status = None
777 try:
778 changed = False
779
780 push_repository, push_tag = repository, tag
781 if not push_tag:
782 push_repository, push_tag = parse_repository_tag(
783 push_repository
784 )
785 push_registry, dummy = resolve_repository_name(push_repository)
786 headers = {}
787 header = get_config_header(self.client, push_registry)
788 if not header:
789 # For some reason, from Docker 28.3.3 on not specifying X-Registry-Auth seems to be invalid.
790 # See https://github.com/moby/moby/issues/50614.
791 header = base64.urlsafe_b64encode(b"{}")
792 headers["X-Registry-Auth"] = header
793 response = self.client._post_json(
794 self.client._url("/images/{0}/push", push_repository),
795 data=None,
796 headers=headers,
797 stream=True,
798 params={"tag": push_tag},
799 )
800 self.client._raise_for_status(response)
801 for line in self.client._stream_helper(response, decode=True):
802 self.log(line, pretty_print=True)
803 if line.get("errorDetail"):
804 raise RuntimeError(line["errorDetail"]["message"])
805 status = line.get("status")
806 if status in ("Pushing", "Pushed"):
807 changed = True
808 self.results["changed"] = changed
809 except Exception as exc: # pylint: disable=broad-exception-caught
810 if "unauthorized" in str(exc):
811 if "authentication required" in str(exc):
812 self.fail(
813 f"Error pushing image {registry}/{repo_name}:{tag} - {exc}. Try logging into {registry} first."
814 )
815 else:
816 self.fail(
817 f"Error pushing image {registry}/{repo_name}:{tag} - {exc}. Does the repository exist?"
818 )
819 self.fail(f"Error pushing image {repository}: {exc}")
820 self.results["image"] = self.client.find_image(name=repository, tag=tag)
821 if not self.results["image"]:
822 self.results["image"] = {}
823 self.results["image"]["push_status"] = status
824
825 def tag_image(
826 self, name: str, tag: str, repository: str, push: bool = False
827 ) -> None:
828 """
829 Tag an image into a repository.
830
831 :param name: name of the image. required.
832 :param tag: image tag.
833 :param repository: path to the repository. required.
834 :param push: bool. push the image once it is tagged.
835 :return: None
836 """
837 repo, repo_tag = parse_repository_tag(repository)
838 if not repo_tag:
839 repo_tag = "latest"
840 if tag:
841 repo_tag = tag
842 image = self.client.find_image(name=repo, tag=repo_tag)
843 found = "found" if image else "not found"
844 self.log(f"image {repo} was {found}")
845
846 if not image or self.force_tag:
847 image_name = name
848 if not is_image_name_id(name) and tag and not name.endswith(":" + tag):
849 image_name = f"{name}:{tag}"
850 self.log(f"tagging {image_name} to {repo}:{repo_tag}")
851 self.results["changed"] = True
852 self.results["actions"].append(
853 f"Tagged image {image_name} to {repo}:{repo_tag}"
854 )
855 if not self.check_mode:
856 try:
857 # Finding the image does not always work, especially running a localhost registry. In those
858 # cases, if we do not set force=True, it errors.
859 params = {
860 "tag": repo_tag,
861 "repo": repo,
862 "force": True,
863 }
864 res = self.client._post(
865 self.client._url("/images/{0}/tag", image_name), params=params
866 )
867 self.client._raise_for_status(res)
868 if res.status_code != 201:
869 raise RuntimeError("Tag operation failed.")
870 except Exception as exc: # pylint: disable=broad-exception-caught
871 self.fail(f"Error: failed to tag image - {exc}")
872 self.results["image"] = self.client.find_image(name=repo, tag=repo_tag)
873 if image and image["Id"] == self.results["image"]["Id"]:
874 self.results["changed"] = False
875
876 if push:
877 self.push_image(repo, repo_tag)
878
879 @staticmethod
880 def _extract_output_line(line: dict[str, t.Any], output: list[str]) -> None:
881 """
882 Extract text line from stream output and, if found, adds it to output.
883 """
884 if "stream" in line or "status" in line:
885 # Make sure we have a string (assuming that line['stream'] and
886 # line['status'] are either not defined, falsish, or a string)
887 text_line = line.get("stream") or line.get("status") or ""
888 output.extend(text_line.splitlines())
889
890 def build_image(self) -> dict[str, t.Any]:
891 """
892 Build an image
893
894 :return: image dict
895 """
896 assert self.build_path is not None
897 remote = context = None
898 headers: dict[str, str | bytes] = {}
899 buildargs = {}
900 if self.buildargs:
901 for key, value in self.buildargs.items():
902 buildargs[key] = to_text(value)
903
904 container_limits = self.container_limits or {}
905 for key in container_limits:
906 if key not in CONTAINER_LIMITS_KEYS:
907 raise DockerException(f"Invalid container_limits key {key}")
908
909 dockerfile: tuple[str, str | None] | tuple[None, None] | str | None = (
910 self.dockerfile
911 )
912 if self.build_path.startswith(
913 ("http://", "https://", "git://", "github.com/", "git@")
914 ):
915 remote = self.build_path
916 elif not os.path.isdir(self.build_path):
917 raise TypeError("You must specify a directory to build in path")
918 else:
919 dockerignore = os.path.join(self.build_path, ".dockerignore")
920 exclude = None
921 if os.path.exists(dockerignore):
922 with open(dockerignore, "rt", encoding="utf-8") as f:
923 exclude = list(
924 filter(
925 lambda x: x != "" and x[0] != "#",
926 [line.strip() for line in f.read().splitlines()],
927 )
928 )
929 dockerfile_data = process_dockerfile(self.dockerfile, self.build_path)
930 dockerfile = dockerfile_data
931 context = tar(
932 self.build_path, exclude=exclude, dockerfile=dockerfile_data, gzip=False
933 )
934
935 params: dict[str, t.Any] = {
936 "t": f"{self.name}:{self.tag}" if self.tag else self.name,
937 "remote": remote,
938 "q": False,
939 "nocache": self.nocache,
940 "rm": self.rm,
941 "forcerm": self.rm,
942 "pull": self.pull,
943 "dockerfile": dockerfile,
944 }
945 params.update(container_limits)
946
947 if self.use_config_proxy:
948 proxy_args = self.client._proxy_configs.get_environment()
949 for k, v in proxy_args.items():
950 buildargs.setdefault(k, v)
951 if buildargs:
952 params.update({"buildargs": json.dumps(buildargs)})
953
954 if self.cache_from:
955 params.update({"cachefrom": json.dumps(self.cache_from)})
956
957 if self.target:
958 params.update({"target": self.target})
959
960 if self.network:
961 params.update({"networkmode": self.network})
962
963 if self.extra_hosts is not None:
964 params.update({"extrahosts": format_extra_hosts(self.extra_hosts)})
965
966 if self.build_platform is not None:
967 params["platform"] = self.build_platform
968
969 if self.shm_size is not None:
970 params["shmsize"] = self.shm_size
971
972 if self.labels:
973 params["labels"] = json.dumps(self.labels)
974
975 if context is not None:
976 headers["Content-Type"] = "application/tar"
977
978 self.client._set_auth_headers(headers)
979
980 response = self.client._post(
981 self.client._url("/build"),
982 data=context,
983 params=params,
984 headers=headers,
985 stream=True,
986 timeout=self.http_timeout,
987 )
988
989 if context is not None:
990 context.close()
991
992 build_output: list[str] = []
993 for line in self.client._stream_helper(response, decode=True):
994 # line = json.loads(line)
995 self.log(line, pretty_print=True)
996 self._extract_output_line(line, build_output)
997
998 if line.get("error"):
999 if line.get("errorDetail"):
1000 error_detail = line.get("errorDetail")
1001 self.fail(
1002 f"Error building {self.name} - code: {error_detail.get('code')}, message: {error_detail.get('message')}, logs: {build_output}"
1003 )
1004 else:
1005 self.fail(
1006 f"Error building {self.name} - message: {line.get('error')}, logs: {build_output}"
1007 )
1008
1009 return {
1010 "stdout": "\n".join(build_output),
1011 "image": self.client.find_image(name=self.name, tag=self.tag),
1012 }
1013
1014 def load_image(self) -> dict[str, t.Any] | None:
1015 """
1016 Load an image from a .tar archive
1017
1018 :return: image dict
1019 """
1020 # Load image(s) from file
1021 assert self.load_path is not None
1022 load_output: list[str] = []
1023 has_output = False
1024 try:
1025 self.log(f"Opening image {self.load_path}")
1026 with open(self.load_path, "rb") as image_tar:
1027 self.log(f"Loading image from {self.load_path}")
1028 res = self.client._post(
1029 self.client._url("/images/load"), data=image_tar, stream=True
1030 )
1031 if LooseVersion(self.client.api_version) >= LooseVersion("1.23"):
1032 has_output = True
1033 for line in self.client._stream_helper(res, decode=True):
1034 self.log(line, pretty_print=True)
1035 self._extract_output_line(line, load_output)
1036 else:
1037 self.client._raise_for_status(res)
1038 self.client.module.warn(
1039 "The API version of your Docker daemon is < 1.23, which does not return the image"
1040 " loading result from the Docker daemon. Therefore, we cannot verify whether the"
1041 " expected image was loaded, whether multiple images where loaded, or whether the load"
1042 " actually succeeded. You should consider upgrading your Docker daemon."
1043 )
1044 except EnvironmentError as exc:
1045 if exc.errno == errno.ENOENT:
1046 self.client.fail(f"Error opening image {self.load_path} - {exc}")
1047 self.client.fail(
1048 f"Error loading image {self.name} - {exc}",
1049 stdout="\n".join(load_output),
1050 )
1051 except Exception as exc: # pylint: disable=broad-exception-caught
1052 self.client.fail(
1053 f"Error loading image {self.name} - {exc}",
1054 stdout="\n".join(load_output),
1055 )
1056
1057 # Collect loaded images
1058 if has_output:
1059 # We can only do this when we actually got some output from Docker daemon
1060 loaded_images = set()
1061 loaded_image_ids = set()
1062 for line in load_output:
1063 if line.startswith("Loaded image:"):
1064 loaded_images.add(line[len("Loaded image:") :].strip())
1065 if line.startswith("Loaded image ID:"):
1066 loaded_image_ids.add(
1067 line[len("Loaded image ID:") :].strip().lower()
1068 )
1069
1070 if not loaded_images and not loaded_image_ids:
1071 self.client.fail(
1072 "Detected no loaded images. Archive potentially corrupt?",
1073 stdout="\n".join(load_output),
1074 )
1075
1076 if is_image_name_id(self.name):
1077 expected_image = self.name.lower()
1078 found_image = expected_image not in loaded_image_ids
1079 else:
1080 expected_image = f"{self.name}:{self.tag}"
1081 found_image = expected_image not in loaded_images
1082 if found_image:
1083 found_instead = ", ".join(
1084 sorted(
1085 [f"'{image}'" for image in loaded_images]
1086 + list(loaded_image_ids)
1087 )
1088 )
1089 self.client.fail(
1090 f"The archive did not contain image '{expected_image}'. Instead, found {found_instead}.",
1091 stdout="\n".join(load_output),
1092 )
1093 loaded_images.remove(expected_image)
1094
1095 if loaded_images:
1096 found_more = ", ".join(
1097 sorted(
1098 [f"'{image}'" for image in loaded_images]
1099 + list(loaded_image_ids)
1100 )
1101 )
1102 self.client.module.warn(
1103 f"The archive contained more images than specified: {found_more}"
1104 )
1105
1106 if is_image_name_id(self.name):
1107 return self.client.find_image_by_id(self.name, accept_missing_image=True)
1108 return self.client.find_image(self.name, self.tag)
1109
1110
1111 def main() -> None:
1112 argument_spec = {
1113 "source": {"type": "str", "choices": ["build", "load", "pull", "local"]},
1114 "build": {
1115 "type": "dict",
1116 "options": {
1117 "cache_from": {"type": "list", "elements": "str"},
1118 "container_limits": {
1119 "type": "dict",
1120 "options": {
1121 "memory": {"type": "str"},
1122 "memswap": {"type": "str"},
1123 "cpushares": {"type": "int"},
1124 "cpusetcpus": {"type": "str"},
1125 },
1126 },
1127 "dockerfile": {"type": "str"},
1128 "http_timeout": {"type": "int"},
1129 "network": {"type": "str"},
1130 "nocache": {"type": "bool", "default": False},
1131 "path": {"type": "path", "required": True},
1132 "pull": {"type": "bool", "default": False},
1133 "rm": {"type": "bool", "default": True},
1134 "args": {"type": "dict"},
1135 "use_config_proxy": {"type": "bool"},
1136 "target": {"type": "str"},
1137 "etc_hosts": {"type": "dict"},
1138 "platform": {"type": "str"},
1139 "shm_size": {"type": "str"},
1140 "labels": {"type": "dict"},
1141 },
1142 },
1143 "archive_path": {"type": "path"},
1144 "force_source": {"type": "bool", "default": False},
1145 "force_absent": {"type": "bool", "default": False},
1146 "force_tag": {"type": "bool", "default": False},
1147 "load_path": {"type": "path"},
1148 "name": {"type": "str", "required": True},
1149 "pull": {
1150 "type": "dict",
1151 "options": {
1152 "platform": {"type": "str"},
1153 },
1154 },
1155 "push": {"type": "bool", "default": False},
1156 "repository": {"type": "str"},
1157 "state": {
1158 "type": "str",
1159 "default": "present",
1160 "choices": ["absent", "present"],
1161 },
1162 "tag": {"type": "str", "default": "latest"},
1163 }
1164
1165 required_if = [
1166 ("state", "present", ["source"]),
1167 ("source", "build", ["build"]),
1168 ("source", "load", ["load_path"]),
1169 ]
1170
1171 def detect_etc_hosts(client: AnsibleDockerClient) -> bool:
1172 return client.module.params["build"] and bool(
1173 client.module.params["build"].get("etc_hosts")
1174 )
1175
1176 def detect_build_platform(client: AnsibleDockerClient) -> bool:
1177 return (
1178 client.module.params["build"]
1179 and client.module.params["build"].get("platform") is not None
1180 )
1181
1182 def detect_pull_platform(client: AnsibleDockerClient) -> bool:
1183 return (
1184 client.module.params["pull"]
1185 and client.module.params["pull"].get("platform") is not None
1186 )
1187
1188 option_minimal_versions = {
1189 "build.etc_hosts": {
1190 "docker_api_version": "1.27",
1191 "detect_usage": detect_etc_hosts,
1192 },
1193 "build.platform": {
1194 "docker_api_version": "1.32",
1195 "detect_usage": detect_build_platform,
1196 },
1197 "pull.platform": {
1198 "docker_api_version": "1.32",
1199 "detect_usage": detect_pull_platform,
1200 },
1201 }
1202
1203 client = AnsibleDockerClient(
1204 argument_spec=argument_spec,
1205 required_if=required_if,
1206 supports_check_mode=True,
1207 option_minimal_versions=option_minimal_versions,
1208 )
1209
1210 if not is_valid_tag(client.module.params["tag"], allow_empty=True):
1211 client.fail(f'"{client.module.params["tag"]}" is not a valid docker tag!')
1212
1213 if client.module.params["source"] == "build" and (
1214 not client.module.params["build"]
1215 or not client.module.params["build"].get("path")
1216 ):
1217 client.fail(
1218 'If "source" is set to "build", the "build.path" option must be specified.'
1219 )
1220
1221 try:
1222 results = {"changed": False, "actions": [], "image": {}}
1223
1224 ImageManager(client, results)
1225 client.module.exit_json(**results)
1226 except DockerException as e:
1227 client.fail(
1228 f"An unexpected Docker error occurred: {e}",
1229 exception=traceback.format_exc(),
1230 )
1231 except RequestException as e:
1232 client.fail(
1233 f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
1234 exception=traceback.format_exc(),
1235 )
1236
1237
1238 if __name__ == "__main__":
1239 main()