Debian Codegraph @

ansible_collections/containers/podman/plugins/modules/podman_prune.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # Copyright (c) 2023, Roberto Alfieri <[email protected]>
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r"""
12 module: podman_prune
13 author:
14 - 'Roberto Alfieri (@rebtoor)'
15 version_added: '1.10.0'
16 short_description: Allows to prune various podman objects
17 notes: []
18 description:
19 - Allows to run C(podman container prune), C(podman image prune), C(podman network prune),
20 C(podman volume prune) and C(podman system prune)
21 requirements:
22 - 'Podman installed on host'
23 options:
24 executable:
25 description:
26 - Podman binary.
27 type: str
28 default: podman
29 container:
30 description:
31 - Whether to prune containers.
32 type: bool
33 default: false
34 container_filters:
35 description:
36 - A dictionary of filter values used for selecting containers to delete.
37 - 'For example, C(until: 24h).'
38 - See L(the podman documentation,
39 https://docs.podman.io/en/latest/markdown/podman-container-prune.1.html#filter-filters)
40 for more information on possible filters.
41 type: dict
42 image:
43 description:
44 - Whether to prune images.
45 type: bool
46 default: false
47 image_filters:
48 description:
49 - A dictionary of filter values used for selecting images to delete.
50 - 'You can also use C(dangling_only: false) to delete dangling and non-dangling images or C(external: true)
51 to delete images even when they are used by external containers.'
52 - See L(the podman documentation,
53 https://docs.podman.io/en/latest/markdown/podman-image-prune.1.html#filter-filters)
54 for more information on possible filters.
55 type: dict
56 network:
57 description:
58 - Whether to prune networks.
59 type: bool
60 default: false
61 network_filters:
62 description:
63 - A dictionary of filter values used for selecting networks to delete.
64 - See L(the podman documentation,
65 https://docs.podman.io/en/latest/markdown/podman-network-prune.1.html#filter)
66 for more information on possible filters.
67 type: dict
68 system:
69 description:
70 - Whether to prune unused pods, containers, image, networks and volume data
71 type: bool
72 default: false
73 system_all:
74 description:
75 - Whether to prune all unused images, not only dangling images.
76 type: bool
77 default: false
78 system_volumes:
79 description:
80 - Whether to prune volumes currently unused by any container.
81 type: bool
82 default: false
83 volume:
84 description:
85 - Whether to prune volumes.
86 type: bool
87 default: false
88 volume_filters:
89 description:
90 - A dictionary of filter values used for selecting volumes to delete.
91 - See L(the podman documentation,
92 https://docs.podman.io/en/latest/markdown/podman-volume-prune.1.html#filter)
93 for more information on possible filters.
94 type: dict
95 """
96
97 EXAMPLES = r"""
98 - name: Prune containers older than 24h
99 containers.podman.podman_prune:
100 containers: true
101 containers_filters:
102 # only consider containers created more than 24 hours ago
103 until: 24h
104
105 - name: Prune everything
106 containers.podman.podman_prune:
107 system: true
108
109 - name: Prune everything (including non-dangling images)
110 containers.podman.podman_prune:
111 system: true
112 system_all: true
113 system_volumes: true
114 """
115
116 RETURN = r"""
117 # containers
118 containers:
119 description:
120 - List of IDs of deleted containers.
121 returned: I(containers) is C(true)
122 type: list
123 elements: str
124 sample: []
125
126 # images
127 images:
128 description:
129 - List of IDs of deleted images.
130 returned: I(images) is C(true)
131 type: list
132 elements: str
133 sample: []
134
135 # networks
136 networks:
137 description:
138 - List of IDs of deleted networks.
139 returned: I(networks) is C(true)
140 type: list
141 elements: str
142 sample: []
143
144 # volumes
145 volumes:
146 description:
147 - List of IDs of deleted volumes.
148 returned: I(volumes) is C(true)
149 type: list
150 elements: str
151 sample: []
152
153 # system
154 system:
155 description:
156 - List of ID of deleted containers, volumes, images, network and total reclaimed space
157 returned: I(system) is C(true)
158 type: list
159 elements: str
160 sample: []
161 """
162
163
164 from ansible.module_utils.basic import AnsibleModule
165
166
167 def filtersPrepare(target, filters):
168 filter_out = []
169 if target == "system":
170 for system_filter in filters:
171 filter_out.append(filters[system_filter])
172 else:
173 for common_filter in filters:
174 if isinstance(filters[common_filter], dict):
175 dict_filters = filters[common_filter]
176 for single_filter in dict_filters:
177 filter_out.append(
178 "--filter={label}={key}={value}".format(
179 label=common_filter,
180 key=single_filter,
181 value=dict_filters[single_filter],
182 )
183 )
184 else:
185 if target == "image" and (common_filter in ("dangling_only", "external")):
186 if common_filter == "dangling_only" and not filters["dangling_only"]:
187 filter_out.append("-a")
188 if common_filter == "external" and filters["external"]:
189 filter_out.append("--external")
190 else:
191 filter_out.append(
192 "--filter={label}={value}".format(label=common_filter, value=filters[common_filter])
193 )
194
195 return filter_out
196
197
198 def podmanExec(module, target, filters, executable):
199 command = [executable, target, "prune", "--force"]
200 if filters is not None:
201 command.extend(filtersPrepare(target, filters))
202 rc, out, err = module.run_command(command)
203 changed = bool(out) and ': 0B' not in out
204
205 if rc != 0:
206 module.fail_json(msg="Error executing prune on {target}: {err}".format(target=target, err=err))
207
208 return {
209 "changed": changed,
210 target: list(filter(None, out.split("\n"))),
211 "errors": err,
212 }
213
214
215 def main():
216 results = dict()
217 module_args = dict(
218 container=dict(type="bool", default=False),
219 container_filters=dict(type="dict"),
220 image=dict(type="bool", default=False),
221 image_filters=dict(type="dict"),
222 network=dict(type="bool", default=False),
223 network_filters=dict(type="dict"),
224 volume=dict(type="bool", default=False),
225 volume_filters=dict(type="dict"),
226 system=dict(type="bool", default=False),
227 system_all=dict(type="bool", default=False),
228 system_volumes=dict(type="bool", default=False),
229 executable=dict(type="str", default="podman"),
230 )
231
232 module = AnsibleModule(argument_spec=module_args)
233
234 executable = module.get_bin_path(module.params["executable"], required=True)
235
236 for target, filters in (
237 ("container", "container_filters"),
238 ("image", "image_filters"),
239 ("network", "network_filters"),
240 ("volume", "volume_filters"),
241 ):
242 if module.params[target]:
243 results[target] = podmanExec(module, target, module.params[filters], executable)
244
245 if module.params["system"]:
246 target = "system"
247 system_filters = {}
248 if module.params["system_all"]:
249 system_filters["system_all"] = "--all"
250 if module.params["system_volumes"]:
251 system_filters["system_volumes"] = "--volumes"
252 results[target] = podmanExec(module, target, system_filters, executable)
253
254 # Calculate global changed status from all targets
255 changed = any(res.get("changed", False) for res in results.values())
256
257 module.exit_json(changed=changed, **results)
258
259
260 if __name__ == "__main__":
261 main()