| 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_remove |
| 11 |
|
| 12 |
short_description: Remove Docker images |
| 13 |
|
| 14 |
version_added: 3.6.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- Remove Docker images from the Docker daemon. |
| 18 |
extends_documentation_fragment: |
| 19 |
- community.docker._docker.api_documentation |
| 20 |
- community.docker._attributes |
| 21 |
- community.docker._attributes.actiongroup_docker |
| 22 |
|
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: full |
| 26 |
diff_mode: |
| 27 |
support: full |
| 28 |
idempotent: |
| 29 |
support: full |
| 30 |
|
| 31 |
options: |
| 32 |
name: |
| 33 |
description: |
| 34 |
- 'Image name. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When pushing or |
| 35 |
pulling an image the name can optionally include the tag by appending C(:tag_name).' |
| 36 |
- Note that image IDs (hashes) can also be used. |
| 37 |
type: str |
| 38 |
required: true |
| 39 |
tag: |
| 40 |
description: |
| 41 |
- Tag for the image name O(name) that is to be tagged. |
| 42 |
- If O(name)'s format is C(name:tag), then the tag value from O(name) will take precedence. |
| 43 |
type: str |
| 44 |
default: latest |
| 45 |
force: |
| 46 |
description: |
| 47 |
- Un-tag and remove all images matching the specified name. |
| 48 |
type: bool |
| 49 |
default: false |
| 50 |
prune: |
| 51 |
description: |
| 52 |
- Delete untagged parent images. |
| 53 |
type: bool |
| 54 |
default: true |
| 55 |
|
| 56 |
requirements: |
| 57 |
- "Docker API >= 1.25" |
| 58 |
|
| 59 |
author: |
| 60 |
- Felix Fontein (@felixfontein) |
| 61 |
|
| 62 |
seealso: |
| 63 |
- module: community.docker.docker_image_load |
| 64 |
- module: community.docker.docker_image_pull |
| 65 |
- module: community.docker.docker_image_tag |
| 66 |
""" |
| 67 |
|
| 68 |
EXAMPLES = r""" |
| 69 |
--- |
| 70 |
- name: Remove an image |
| 71 |
community.docker.docker_image_remove: |
| 72 |
name: pacur/centos-7 |
| 73 |
""" |
| 74 |
|
| 75 |
RETURN = r""" |
| 76 |
image: |
| 77 |
description: |
| 78 |
- Image inspection results for the affected image before removal. |
| 79 |
- Empty if the image was not found. |
| 80 |
returned: success |
| 81 |
type: dict |
| 82 |
sample: {} |
| 83 |
deleted: |
| 84 |
description: |
| 85 |
- The digests of the images that were deleted. |
| 86 |
returned: success |
| 87 |
type: list |
| 88 |
elements: str |
| 89 |
sample: [] |
| 90 |
untagged: |
| 91 |
description: |
| 92 |
- The digests of the images that were untagged. |
| 93 |
returned: success |
| 94 |
type: list |
| 95 |
elements: str |
| 96 |
sample: [] |
| 97 |
""" |
| 98 |
|
| 99 |
import traceback |
| 100 |
import typing as t |
| 101 |
|
| 102 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 103 |
DockerException, |
| 104 |
NotFound, |
| 105 |
) |
| 106 |
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import ( |
| 107 |
parse_repository_tag, |
| 108 |
) |
| 109 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 110 |
AnsibleDockerClient, |
| 111 |
RequestException, |
| 112 |
) |
| 113 |
from ansible_collections.community.docker.plugins.module_utils._util import ( |
| 114 |
DockerBaseClass, |
| 115 |
is_image_name_id, |
| 116 |
is_valid_tag, |
| 117 |
) |
| 118 |
|
| 119 |
|
| 120 |
class ImageRemover(DockerBaseClass): |
| 121 |
def __init__(self, client: AnsibleDockerClient) -> None: |
| 122 |
super().__init__() |
| 123 |
|
| 124 |
self.client = client |
| 125 |
self.check_mode = self.client.check_mode |
| 126 |
self.diff = self.client.module._diff |
| 127 |
|
| 128 |
parameters = self.client.module.params |
| 129 |
self.name = parameters["name"] |
| 130 |
self.tag = parameters["tag"] |
| 131 |
self.force = parameters["force"] |
| 132 |
self.prune = parameters["prune"] |
| 133 |
|
| 134 |
if not is_valid_tag(self.tag, allow_empty=True): |
| 135 |
self.fail(f'"{self.tag}" is not a valid docker tag') |
| 136 |
|
| 137 |
# If name contains a tag, it takes precedence over tag parameter. |
| 138 |
if not is_image_name_id(self.name): |
| 139 |
repo, repo_tag = parse_repository_tag(self.name) |
| 140 |
if repo_tag: |
| 141 |
self.name = repo |
| 142 |
self.tag = repo_tag |
| 143 |
|
| 144 |
def fail(self, msg: str) -> t.NoReturn: |
| 145 |
self.client.fail(msg) |
| 146 |
|
| 147 |
def get_diff_state(self, image: dict[str, t.Any] | None) -> dict[str, t.Any]: |
| 148 |
if not image: |
| 149 |
return {"exists": False} |
| 150 |
return { |
| 151 |
"exists": True, |
| 152 |
"id": image["Id"], |
| 153 |
"tags": sorted(image.get("RepoTags") or []), |
| 154 |
"digests": sorted(image.get("RepoDigests") or []), |
| 155 |
} |
| 156 |
|
| 157 |
def absent(self) -> dict[str, t.Any]: |
| 158 |
actions: list[str] = [] |
| 159 |
deleted: list[str] = [] |
| 160 |
untagged: list[str] = [] |
| 161 |
results: dict[str, t.Any] = { |
| 162 |
"changed": False, |
| 163 |
"actions": actions, |
| 164 |
"image": {}, |
| 165 |
"deleted": deleted, |
| 166 |
"untagged": untagged, |
| 167 |
} |
| 168 |
|
| 169 |
name = self.name |
| 170 |
if is_image_name_id(name): |
| 171 |
image = self.client.find_image_by_id(name, accept_missing_image=True) |
| 172 |
else: |
| 173 |
image = self.client.find_image(name, self.tag) |
| 174 |
if self.tag: |
| 175 |
name = f"{self.name}:{self.tag}" |
| 176 |
|
| 177 |
diff: dict[str, t.Any] = {} |
| 178 |
if self.diff: |
| 179 |
results["diff"] = diff |
| 180 |
diff["before"] = self.get_diff_state(image) |
| 181 |
|
| 182 |
if not image: |
| 183 |
if self.diff: |
| 184 |
diff["after"] = self.get_diff_state(image) |
| 185 |
return results |
| 186 |
|
| 187 |
results["changed"] = True |
| 188 |
actions.append(f"Removed image {name}") |
| 189 |
results["image"] = image |
| 190 |
|
| 191 |
if not self.check_mode: |
| 192 |
try: |
| 193 |
res = self.client.delete_json( |
| 194 |
"/images/{0}", |
| 195 |
name, |
| 196 |
params={"force": self.force, "noprune": not self.prune}, |
| 197 |
) |
| 198 |
except NotFound: |
| 199 |
# If the image vanished while we were trying to remove it, do not fail |
| 200 |
res = [] |
| 201 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 202 |
self.fail(f"Error removing image {name} - {exc}") |
| 203 |
|
| 204 |
for entry in res: |
| 205 |
if entry.get("Untagged"): |
| 206 |
untagged.append(entry["Untagged"]) |
| 207 |
if entry.get("Deleted"): |
| 208 |
deleted.append(entry["Deleted"]) |
| 209 |
|
| 210 |
untagged[:] = sorted(untagged) |
| 211 |
deleted[:] = sorted(deleted) |
| 212 |
|
| 213 |
if self.diff: |
| 214 |
image_after = self.client.find_image_by_id( |
| 215 |
image["Id"], accept_missing_image=True |
| 216 |
) |
| 217 |
diff["after"] = self.get_diff_state(image_after) |
| 218 |
|
| 219 |
elif is_image_name_id(name): |
| 220 |
deleted.append(image["Id"]) |
| 221 |
# TODO: the following is no longer correct with Docker 29+... |
| 222 |
untagged[:] = sorted( |
| 223 |
(image.get("RepoTags") or []) + (image.get("RepoDigests") or []) |
| 224 |
) |
| 225 |
if not self.force and results["untagged"]: |
| 226 |
self.fail( |
| 227 |
"Cannot delete image by ID that is still in use - use force=true" |
| 228 |
) |
| 229 |
if self.diff: |
| 230 |
diff["after"] = self.get_diff_state({}) |
| 231 |
|
| 232 |
elif is_image_name_id(self.tag): |
| 233 |
untagged.append(name) |
| 234 |
if ( |
| 235 |
len(image.get("RepoTags") or []) < 1 |
| 236 |
and len(image.get("RepoDigests") or []) < 2 |
| 237 |
): |
| 238 |
deleted.append(image["Id"]) |
| 239 |
if self.diff: |
| 240 |
diff["after"] = self.get_diff_state(image) |
| 241 |
try: |
| 242 |
diff["after"]["digests"].remove(name) |
| 243 |
except ValueError: |
| 244 |
pass |
| 245 |
|
| 246 |
else: |
| 247 |
untagged.append(name) |
| 248 |
if ( |
| 249 |
len(image.get("RepoTags") or []) < 2 |
| 250 |
and len(image.get("RepoDigests") or []) < 1 |
| 251 |
): |
| 252 |
deleted.append(image["Id"]) |
| 253 |
if self.diff: |
| 254 |
diff["after"] = self.get_diff_state(image) |
| 255 |
try: |
| 256 |
diff["after"]["tags"].remove(name) |
| 257 |
except ValueError: |
| 258 |
pass |
| 259 |
|
| 260 |
return results |
| 261 |
|
| 262 |
|
| 263 |
def main() -> None: |
| 264 |
argument_spec = { |
| 265 |
"name": {"type": "str", "required": True}, |
| 266 |
"tag": {"type": "str", "default": "latest"}, |
| 267 |
"force": {"type": "bool", "default": False}, |
| 268 |
"prune": {"type": "bool", "default": True}, |
| 269 |
} |
| 270 |
|
| 271 |
client = AnsibleDockerClient( |
| 272 |
argument_spec=argument_spec, |
| 273 |
supports_check_mode=True, |
| 274 |
) |
| 275 |
|
| 276 |
try: |
| 277 |
results = ImageRemover(client).absent() |
| 278 |
client.module.exit_json(**results) |
| 279 |
except DockerException as e: |
| 280 |
client.fail( |
| 281 |
f"An unexpected Docker error occurred: {e}", |
| 282 |
exception=traceback.format_exc(), |
| 283 |
) |
| 284 |
except RequestException as e: |
| 285 |
client.fail( |
| 286 |
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}", |
| 287 |
exception=traceback.format_exc(), |
| 288 |
) |
| 289 |
|
| 290 |
|
| 291 |
if __name__ == "__main__": |
| 292 |
main() |