Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_prune.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_prune
11
12 short_description: Allows to prune various docker objects
13
14 description:
15 - Allows to run C(docker container prune), C(docker image prune), C(docker network prune) and C(docker volume prune) through
16 the Docker API.
17 extends_documentation_fragment:
18 - community.docker._docker.api_documentation
19 - community.docker._attributes
20 - community.docker._attributes.actiongroup_docker
21
22 attributes:
23 check_mode:
24 support: none
25 diff_mode:
26 support: none
27 idempotent:
28 support: full
29
30 options:
31 containers:
32 description:
33 - Whether to prune containers.
34 type: bool
35 default: false
36 containers_filters:
37 description:
38 - A dictionary of filter values used for selecting containers to delete.
39 - 'For example, C(until: 24h).'
40 - See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/container_prune/#filtering) for
41 more information on possible filters.
42 type: dict
43 images:
44 description:
45 - Whether to prune images.
46 type: bool
47 default: false
48 images_filters:
49 description:
50 - A dictionary of filter values used for selecting images to delete.
51 - 'For example, C(dangling: true).'
52 - See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/image_prune/#filtering) for more
53 information on possible filters.
54 type: dict
55 networks:
56 description:
57 - Whether to prune networks.
58 type: bool
59 default: false
60 networks_filters:
61 description:
62 - A dictionary of filter values used for selecting networks to delete.
63 - See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/network_prune/#filtering) for
64 more information on possible filters.
65 type: dict
66 volumes:
67 description:
68 - Whether to prune volumes.
69 type: bool
70 default: false
71 volumes_filters:
72 description:
73 - A dictionary of filter values used for selecting volumes to delete.
74 - See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/volume_prune/#filtering) for more
75 information on possible filters.
76 type: dict
77 builder_cache:
78 description:
79 - Whether to prune the builder cache.
80 type: bool
81 default: false
82 builder_cache_all:
83 description:
84 - Whether to remove all types of build cache.
85 type: bool
86 default: false
87 version_added: 3.10.0
88 builder_cache_filters:
89 description:
90 - A dictionary of filter values used for selecting images to delete.
91 - 'For example, C(until: 10m).'
92 - See L(the API documentation,https://docs.docker.com/engine/api/v1.44/#tag/Image/operation/BuildPrune) for more information
93 on possible filters.
94 type: dict
95 version_added: 3.10.0
96 builder_cache_keep_storage:
97 description:
98 - Amount of disk space to keep for cache in format C(<number>[<unit>]).".
99 - Number is a positive integer. Unit can be one of V(B) (byte), V(K) (kibibyte, 1024B), V(M) (mebibyte), V(G) (gibibyte),
100 V(T) (tebibyte), or V(P) (pebibyte).
101 - Omitting the unit defaults to bytes.
102 type: str
103 version_added: 3.10.0
104
105 author:
106 - "Felix Fontein (@felixfontein)"
107
108 notes:
109 - The module always returned C(changed=false) before community.docker 3.5.1.
110 requirements:
111 - "Docker API >= 1.25"
112 """
113
114 EXAMPLES = r"""
115 ---
116 - name: Prune containers older than 24h
117 community.docker.docker_prune:
118 containers: true
119 containers_filters:
120 # only consider containers created more than 24 hours ago
121 until: 24h
122
123 - name: Prune containers with labels
124 community.docker.docker_prune:
125 containers: true
126 containers_filters:
127 # Prune containers whose "foo" label has value "bar", and
128 # whose "bam" label has value "baz". If you only want to
129 # compare one label, you can provide it as a string instead
130 # of a list with one element.
131 label:
132 - foo=bar
133 - bam=baz
134 # Prune containers whose label "bar" does *not* have value
135 # "baz". If you want to avoid more than one label, you can
136 # provide a list of multiple label-value pairs.
137 "label!": bar=baz
138
139 - name: Prune everything
140 community.docker.docker_prune:
141 containers: true
142 images: true
143 networks: true
144 volumes: true
145 builder_cache: true
146
147 - name: Prune everything (including non-dangling images)
148 community.docker.docker_prune:
149 containers: true
150 images: true
151 images_filters:
152 dangling: false
153 networks: true
154 volumes: true
155 builder_cache: true
156 """
157
158 RETURN = r"""
159 # containers
160 containers:
161 description:
162 - List of IDs of deleted containers.
163 returned: O(containers=true)
164 type: list
165 elements: str
166 sample: []
167 containers_space_reclaimed:
168 description:
169 - Amount of reclaimed disk space from container pruning in bytes.
170 returned: O(containers=true)
171 type: int
172 sample: 0
173
174 # images
175 images:
176 description:
177 - List of IDs of deleted images.
178 returned: O(images=true)
179 type: list
180 elements: str
181 sample: []
182 images_space_reclaimed:
183 description:
184 - Amount of reclaimed disk space from image pruning in bytes.
185 returned: O(images=true)
186 type: int
187 sample: 0
188
189 # networks
190 networks:
191 description:
192 - List of IDs of deleted networks.
193 returned: O(networks=true)
194 type: list
195 elements: str
196 sample: []
197
198 # volumes
199 volumes:
200 description:
201 - List of IDs of deleted volumes.
202 returned: O(volumes=true)
203 type: list
204 elements: str
205 sample: []
206 volumes_space_reclaimed:
207 description:
208 - Amount of reclaimed disk space from volumes pruning in bytes.
209 returned: O(volumes=true)
210 type: int
211 sample: 0
212
213 # builder_cache
214 builder_cache_space_reclaimed:
215 description:
216 - Amount of reclaimed disk space from builder cache pruning in bytes.
217 returned: O(builder_cache=true)
218 type: int
219 sample: 0
220 builder_cache_caches_deleted:
221 description:
222 - The build caches that were deleted.
223 returned: O(builder_cache=true) and API version is 1.39 or later
224 type: list
225 elements: str
226 sample: []
227 version_added: 3.10.0
228 """
229
230 import traceback
231
232 from ansible.module_utils.common.text.formatters import human_to_bytes
233
234 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
235 DockerException,
236 )
237 from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
238 convert_filters,
239 )
240 from ansible_collections.community.docker.plugins.module_utils._common_api import (
241 AnsibleDockerClient,
242 RequestException,
243 )
244 from ansible_collections.community.docker.plugins.module_utils._util import (
245 clean_dict_booleans_for_docker_api,
246 )
247
248
249 def main() -> None:
250 argument_spec = {
251 "containers": {"type": "bool", "default": False},
252 "containers_filters": {"type": "dict"},
253 "images": {"type": "bool", "default": False},
254 "images_filters": {"type": "dict"},
255 "networks": {"type": "bool", "default": False},
256 "networks_filters": {"type": "dict"},
257 "volumes": {"type": "bool", "default": False},
258 "volumes_filters": {"type": "dict"},
259 "builder_cache": {"type": "bool", "default": False},
260 "builder_cache_all": {"type": "bool", "default": False},
261 "builder_cache_filters": {"type": "dict"},
262 "builder_cache_keep_storage": {"type": "str"}, # convert to bytes
263 }
264
265 client = AnsibleDockerClient(
266 argument_spec=argument_spec,
267 option_minimal_versions={
268 "builder_cache": {"docker_py_version": "1.31"},
269 "builder_cache_all": {"docker_py_version": "1.39"},
270 "builder_cache_filters": {"docker_py_version": "1.31"},
271 "builder_cache_keep_storage": {"docker_py_version": "1.39"},
272 },
273 # supports_check_mode=True,
274 )
275
276 builder_cache_keep_storage = None
277 if client.module.params.get("builder_cache_keep_storage") is not None:
278 try:
279 builder_cache_keep_storage = human_to_bytes(
280 client.module.params.get("builder_cache_keep_storage")
281 )
282 except ValueError as exc:
283 client.module.fail_json(
284 msg=f"Error while parsing value of builder_cache_keep_storage: {exc}"
285 )
286
287 try:
288 result = {}
289 changed = False
290
291 if client.module.params["containers"]:
292 filters = clean_dict_booleans_for_docker_api(
293 client.module.params.get("containers_filters"), allow_sequences=True
294 )
295 params = {"filters": convert_filters(filters)}
296 res = client.post_to_json("/containers/prune", params=params)
297 result["containers"] = res.get("ContainersDeleted") or []
298 result["containers_space_reclaimed"] = res["SpaceReclaimed"]
299 if result["containers"] or result["containers_space_reclaimed"]:
300 changed = True
301
302 if client.module.params["images"]:
303 filters = clean_dict_booleans_for_docker_api(
304 client.module.params.get("images_filters"), allow_sequences=True
305 )
306 params = {"filters": convert_filters(filters)}
307 res = client.post_to_json("/images/prune", params=params)
308 result["images"] = res.get("ImagesDeleted") or []
309 result["images_space_reclaimed"] = res["SpaceReclaimed"]
310 if result["images"] or result["images_space_reclaimed"]:
311 changed = True
312
313 if client.module.params["networks"]:
314 filters = clean_dict_booleans_for_docker_api(
315 client.module.params.get("networks_filters"), allow_sequences=True
316 )
317 params = {"filters": convert_filters(filters)}
318 res = client.post_to_json("/networks/prune", params=params)
319 result["networks"] = res.get("NetworksDeleted") or []
320 if result["networks"]:
321 changed = True
322
323 if client.module.params["volumes"]:
324 filters = clean_dict_booleans_for_docker_api(
325 client.module.params.get("volumes_filters"), allow_sequences=True
326 )
327 params = {"filters": convert_filters(filters)}
328 res = client.post_to_json("/volumes/prune", params=params)
329 result["volumes"] = res.get("VolumesDeleted") or []
330 result["volumes_space_reclaimed"] = res["SpaceReclaimed"]
331 if result["volumes"] or result["volumes_space_reclaimed"]:
332 changed = True
333
334 if client.module.params["builder_cache"]:
335 filters = clean_dict_booleans_for_docker_api(
336 client.module.params.get("builder_cache_filters"), allow_sequences=True
337 )
338 params = {"filters": convert_filters(filters)}
339 if client.module.params.get("builder_cache_all"):
340 params["all"] = "true"
341 if builder_cache_keep_storage is not None:
342 params["keep-storage"] = builder_cache_keep_storage
343 res = client.post_to_json("/build/prune", params=params)
344 result["builder_cache_space_reclaimed"] = res["SpaceReclaimed"]
345 if result["builder_cache_space_reclaimed"]:
346 changed = True
347 if "CachesDeleted" in res:
348 # API version 1.39+: return value CachesDeleted (list of str)
349 result["builder_cache_caches_deleted"] = res["CachesDeleted"]
350 if result["builder_cache_caches_deleted"]:
351 changed = True
352
353 result["changed"] = changed
354 client.module.exit_json(**result)
355 except DockerException as e:
356 client.fail(
357 f"An unexpected Docker error occurred: {e}",
358 exception=traceback.format_exc(),
359 )
360 except RequestException as e:
361 client.fail(
362 f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
363 exception=traceback.format_exc(),
364 )
365
366
367 if __name__ == "__main__":
368 main()