Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_config.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_config
11
12 short_description: Manage docker configs
13
14 description:
15 - Create and remove Docker configs in a Swarm environment. Similar to C(docker config create) and C(docker config rm).
16 - Adds to the metadata of new configs C(ansible_key), an encrypted hash representation of the data, which is then used in
17 future runs to test if a config has changed. If C(ansible_key) is not present, then a config will not be updated unless
18 the O(force) option is set.
19 - Updates to configs are performed by removing the config and creating it again.
20 extends_documentation_fragment:
21 - community.docker._docker
22 - community.docker._docker.docker_py_2_documentation
23 - community.docker._attributes
24 - community.docker._attributes.actiongroup_docker
25
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: none
31 idempotent:
32 support: partial
33 details:
34 - If O(force=true) the module is not idempotent.
35
36 options:
37 data:
38 description:
39 - The value of the config.
40 - Mutually exclusive with O(data_src). One of O(data) and O(data_src) is required if O(state=present).
41 type: str
42 data_is_b64:
43 description:
44 - If set to V(true), the data is assumed to be Base64 encoded and will be decoded before being used.
45 - To use binary O(data), it is better to keep it Base64 encoded and let it be decoded by this option.
46 type: bool
47 default: false
48 data_src:
49 description:
50 - The file on the target from which to read the config.
51 - Mutually exclusive with O(data). One of O(data) and O(data_src) is required if O(state=present).
52 type: path
53 version_added: 1.10.0
54 labels:
55 description:
56 - A map of key:value meta data, where both the C(key) and C(value) are expected to be a string.
57 - If new meta data is provided, or existing meta data is modified, the config will be updated by removing it and creating
58 it again.
59 type: dict
60 force:
61 description:
62 - Use with O(state=present) to always remove and recreate an existing config.
63 - If V(true), an existing config will be replaced, even if it has not been changed.
64 type: bool
65 default: false
66 rolling_versions:
67 description:
68 - If set to V(true), configs are created with an increasing version number appended to their name.
69 - Adds a label containing the version number to the managed configs with the name C(ansible_version).
70 type: bool
71 default: false
72 version_added: 2.2.0
73 versions_to_keep:
74 description:
75 - When using O(rolling_versions), the number of old versions of the config to keep.
76 - Extraneous old configs are deleted after the new one is created.
77 - Set to V(-1) to keep everything or V(0) or V(1) to keep only the current one.
78 type: int
79 default: 5
80 version_added: 2.2.0
81 name:
82 description:
83 - The name of the config.
84 type: str
85 required: true
86 state:
87 description:
88 - Set to V(present), if the config should exist, and V(absent), if it should not.
89 type: str
90 default: present
91 choices:
92 - absent
93 - present
94 template_driver:
95 description:
96 - Set to V(golang) to use a Go template in O(data) or a Go template file in O(data_src).
97 type: str
98 choices:
99 - golang
100 version_added: 2.5.0
101
102 requirements:
103 - "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 2.6.0"
104 - "Docker API >= 1.30"
105
106 author:
107 - Chris Houseknecht (@chouseknecht)
108 - John Hu (@ushuz)
109 """
110
111 EXAMPLES = r"""
112 ---
113 - name: Create config foo (from a file on the control machine)
114 community.docker.docker_config:
115 name: foo
116 # If the file is JSON or binary, Ansible might modify it (because
117 # it is first decoded and later re-encoded). Base64-encoding the
118 # file directly after reading it prevents this to happen.
119 data: "{{ lookup('file', '/path/to/config/file') | b64encode }}"
120 data_is_b64: true
121 state: present
122
123 - name: Create config foo (from a file on the target machine)
124 community.docker.docker_config:
125 name: foo
126 data_src: /path/to/config/file
127 state: present
128
129 - name: Change the config data
130 community.docker.docker_config:
131 name: foo
132 data: Goodnight everyone!
133 labels:
134 bar: baz
135 one: '1'
136 state: present
137
138 - name: Add a new label
139 community.docker.docker_config:
140 name: foo
141 data: Goodnight everyone!
142 labels:
143 bar: baz
144 one: '1'
145 # Adding a new label will cause a remove/create of the config
146 two: '2'
147 state: present
148
149 - name: No change
150 community.docker.docker_config:
151 name: foo
152 data: Goodnight everyone!
153 labels:
154 bar: baz
155 one: '1'
156 # Even though 'two' is missing, there is no change to the existing config
157 state: present
158
159 - name: Update an existing label
160 community.docker.docker_config:
161 name: foo
162 data: Goodnight everyone!
163 labels:
164 bar: monkey # Changing a label will cause a remove/create of the config
165 one: '1'
166 state: present
167
168 - name: Force the (re-)creation of the config
169 community.docker.docker_config:
170 name: foo
171 data: Goodnight everyone!
172 force: true
173 state: present
174
175 - name: Remove config foo
176 community.docker.docker_config:
177 name: foo
178 state: absent
179 """
180
181 RETURN = r"""
182 config_id:
183 description:
184 - The ID assigned by Docker to the config object.
185 returned: success and O(state=present)
186 type: str
187 sample: 'hzehrmyjigmcp2gb6nlhmjqcv'
188 config_name:
189 description:
190 - The name of the created config object.
191 returned: success and O(state=present)
192 type: str
193 sample: 'awesome_config'
194 version_added: 2.2.0
195 """
196
197 import base64
198 import hashlib
199 import traceback
200 import typing as t
201
202 try:
203 from docker.errors import APIError, DockerException
204 except ImportError:
205 # missing Docker SDK for Python handled in ansible.module_utils.docker.common
206 pass
207
208 from ansible.module_utils.common.text.converters import to_bytes
209
210 from ansible_collections.community.docker.plugins.module_utils._common import (
211 AnsibleDockerClient,
212 RequestException,
213 )
214 from ansible_collections.community.docker.plugins.module_utils._util import (
215 DockerBaseClass,
216 compare_generic,
217 sanitize_labels,
218 )
219
220
221 class ConfigManager(DockerBaseClass):
222 def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None:
223 super().__init__()
224
225 self.client = client
226 self.results = results
227 self.check_mode = self.client.check_mode
228
229 parameters = self.client.module.params
230 self.name = parameters.get("name")
231 self.state = parameters.get("state")
232 self.data = parameters.get("data")
233 if self.data is not None:
234 if parameters.get("data_is_b64"):
235 self.data = base64.b64decode(self.data)
236 else:
237 self.data = to_bytes(self.data)
238 data_src = parameters.get("data_src")
239 if data_src is not None:
240 try:
241 with open(data_src, "rb") as f:
242 self.data = f.read()
243 except Exception as exc: # pylint: disable=broad-exception-caught
244 self.client.fail(f"Error while reading {data_src}: {exc}")
245 self.labels = parameters.get("labels")
246 self.force = parameters.get("force")
247 self.rolling_versions = parameters.get("rolling_versions")
248 self.versions_to_keep = parameters.get("versions_to_keep")
249 self.template_driver = parameters.get("template_driver")
250
251 if self.rolling_versions:
252 self.version = 0
253 self.data_key: str | None = None
254 self.configs: list[dict[str, t.Any]] = []
255
256 def __call__(self) -> None:
257 self.get_config()
258 if self.state == "present":
259 self.data_key = hashlib.sha224(self.data).hexdigest()
260 self.present()
261 self.remove_old_versions()
262 elif self.state == "absent":
263 self.absent()
264
265 def get_version(self, config: dict[str, t.Any]) -> int:
266 try:
267 return int(
268 config.get("Spec", {}).get("Labels", {}).get("ansible_version", 0)
269 )
270 except ValueError:
271 return 0
272
273 def remove_old_versions(self) -> None:
274 if not self.rolling_versions or self.versions_to_keep < 0:
275 return
276 if not self.check_mode:
277 while len(self.configs) > max(self.versions_to_keep, 1):
278 self.remove_config(self.configs.pop(0))
279
280 def get_config(self) -> None:
281 """Find an existing config."""
282 try:
283 configs = self.client.configs(filters={"name": self.name})
284 except APIError as exc:
285 self.client.fail(f"Error accessing config {self.name}: {exc}")
286
287 if self.rolling_versions:
288 self.configs = [
289 config
290 for config in configs
291 if config["Spec"]["Name"].startswith(f"{self.name}_v")
292 ]
293 self.configs.sort(key=self.get_version)
294 else:
295 self.configs = [
296 config for config in configs if config["Spec"]["Name"] == self.name
297 ]
298
299 def create_config(self) -> str | None:
300 """Create a new config"""
301 config_id: str | dict[str, t.Any] | None = None
302 # We ca not see the data after creation, so adding a label we can use for idempotency check
303 labels = {"ansible_key": self.data_key}
304 if self.rolling_versions:
305 self.version += 1
306 labels["ansible_version"] = str(self.version)
307 self.name = f"{self.name}_v{self.version}"
308 if self.labels:
309 labels.update(self.labels)
310
311 try:
312 if not self.check_mode:
313 # only use templating argument when self.template_driver is defined
314 kwargs = {}
315 if self.template_driver:
316 kwargs["templating"] = {"name": self.template_driver}
317 config_id = self.client.create_config(
318 self.name, self.data, labels=labels, **kwargs
319 )
320 self.configs += self.client.configs(filters={"id": config_id})
321 except APIError as exc:
322 self.client.fail(f"Error creating config: {exc}")
323
324 if isinstance(config_id, dict):
325 return config_id["ID"]
326
327 return config_id
328
329 def remove_config(self, config: dict[str, t.Any]) -> None:
330 try:
331 if not self.check_mode:
332 self.client.remove_config(config["ID"])
333 except APIError as exc:
334 self.client.fail(f"Error removing config {config['Spec']['Name']}: {exc}")
335
336 def present(self) -> None:
337 """Handles state == 'present', creating or updating the config"""
338 if self.configs:
339 config = self.configs[-1]
340 self.results["config_id"] = config["ID"]
341 self.results["config_name"] = config["Spec"]["Name"]
342 data_changed = False
343 template_driver_changed = False
344 attrs = config.get("Spec", {})
345 if attrs.get("Labels", {}).get("ansible_key"):
346 if attrs["Labels"]["ansible_key"] != self.data_key:
347 data_changed = True
348 else:
349 if not self.force:
350 self.client.module.warn(
351 "'ansible_key' label not found. Config will not be changed unless the force parameter is set to 'true'"
352 )
353 # template_driver has changed if it was set in the previous config
354 # and now it differs, or if it was not set but now it is.
355 if attrs.get("Templating", {}).get("Name"):
356 if attrs["Templating"]["Name"] != self.template_driver:
357 template_driver_changed = True
358 elif self.template_driver:
359 template_driver_changed = True
360 labels_changed = not compare_generic(
361 self.labels, attrs.get("Labels"), "allow_more_present", "dict"
362 )
363 if self.rolling_versions:
364 self.version = self.get_version(config)
365 if data_changed or template_driver_changed or labels_changed or self.force:
366 # if something changed or force, delete and re-create the config
367 if not self.rolling_versions:
368 self.absent()
369 config_id = self.create_config()
370 self.results["changed"] = True
371 self.results["config_id"] = config_id
372 self.results["config_name"] = self.name
373 else:
374 self.results["changed"] = True
375 self.results["config_id"] = self.create_config()
376 self.results["config_name"] = self.name
377
378 def absent(self) -> None:
379 """Handles state == 'absent', removing the config"""
380 if self.configs:
381 for config in self.configs:
382 self.remove_config(config)
383 self.results["changed"] = True
384
385
386 def main() -> None:
387 argument_spec = {
388 "name": {"type": "str", "required": True},
389 "state": {
390 "type": "str",
391 "default": "present",
392 "choices": ["absent", "present"],
393 },
394 "data": {"type": "str"},
395 "data_is_b64": {"type": "bool", "default": False},
396 "data_src": {"type": "path"},
397 "labels": {"type": "dict"},
398 "force": {"type": "bool", "default": False},
399 "rolling_versions": {"type": "bool", "default": False},
400 "versions_to_keep": {"type": "int", "default": 5},
401 "template_driver": {"type": "str", "choices": ["golang"]},
402 }
403
404 required_if = [
405 ("state", "present", ["data", "data_src"], True),
406 ]
407
408 mutually_exclusive = [
409 ("data", "data_src"),
410 ]
411
412 option_minimal_versions = {
413 "template_driver": {"docker_py_version": "5.0.3", "docker_api_version": "1.37"},
414 }
415
416 client = AnsibleDockerClient(
417 argument_spec=argument_spec,
418 supports_check_mode=True,
419 required_if=required_if,
420 mutually_exclusive=mutually_exclusive,
421 min_docker_version="2.6.0",
422 min_docker_api_version="1.30",
423 option_minimal_versions=option_minimal_versions,
424 )
425 sanitize_labels(client.module.params["labels"], "labels", client)
426
427 try:
428 results = {
429 "changed": False,
430 }
431
432 ConfigManager(client, results)()
433 client.module.exit_json(**results)
434 except DockerException as e:
435 client.fail(
436 f"An unexpected Docker error occurred: {e}",
437 exception=traceback.format_exc(),
438 )
439 except RequestException as e:
440 client.fail(
441 f"An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}",
442 exception=traceback.format_exc(),
443 )
444
445
446 if __name__ == "__main__":
447 main()