Debian Codegraph @

ansible_collections/community/general/plugins/modules/kdeconfig.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2023, Salvatore Mesoraca <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: kdeconfig
10 short_description: Manage KDE configuration files
11 version_added: "6.5.0"
12 description:
13 - Add or change individual settings in KDE configuration files.
14 - It uses B(kwriteconfig) under the hood.
15 options:
16 path:
17 description:
18 - Path to the config file. If the file does not exist it is created.
19 type: path
20 required: true
21 kwriteconfig_path:
22 description:
23 - Path to the kwriteconfig executable. If not specified, Ansible tries to discover it.
24 type: path
25 values:
26 description:
27 - List of values to set.
28 type: list
29 elements: dict
30 suboptions:
31 group:
32 description:
33 - The option's group. One between this and O(values[].groups) is required.
34 type: str
35 groups:
36 description:
37 - List of the option's groups. One between this and O(values[].group) is required.
38 type: list
39 elements: str
40 key:
41 description:
42 - The option's name.
43 type: str
44 required: true
45 value:
46 description:
47 - The option's value. One between this and O(values[].bool_value) is required.
48 type: str
49 bool_value:
50 description:
51 - Boolean value.
52 - One between this and O(values[].value) is required.
53 type: bool
54 required: true
55 backup:
56 description:
57 - Create a backup file.
58 type: bool
59 default: false
60 extends_documentation_fragment:
61 - ansible.builtin.files
62 - community.general._attributes
63 attributes:
64 check_mode:
65 support: full
66 diff_mode:
67 support: full
68 requirements:
69 - kwriteconfig
70 author:
71 - Salvatore Mesoraca (@smeso)
72 """
73
74 EXAMPLES = r"""
75 - name: Ensure "Homepage=https://www.ansible.com/" in group "Branding"
76 community.general.kdeconfig:
77 path: /etc/xdg/kickoffrc
78 values:
79 - group: Branding
80 key: Homepage
81 value: https://www.ansible.com/
82 mode: '0644'
83
84 - name: Ensure "KEY=true" in groups "Group" and "Subgroup", and "KEY=VALUE" in Group2
85 community.general.kdeconfig:
86 path: /etc/xdg/someconfigrc
87 values:
88 - groups: [Group, Subgroup]
89 key: KEY
90 bool_value: true
91 - group: Group2
92 key: KEY
93 value: VALUE
94 backup: true
95 """
96
97 RETURN = r""" # """
98
99 import os
100 import shutil
101 import tempfile
102 import traceback
103
104 from ansible.module_utils.basic import AnsibleModule
105 from ansible.module_utils.common.text.converters import to_bytes, to_text
106
107
108 class TemporaryDirectory:
109 """Basic backport of tempfile.TemporaryDirectory"""
110
111 def __init__(self, suffix="", prefix="tmp", dir=None):
112 self.name = None
113 self.name = tempfile.mkdtemp(suffix, prefix, dir)
114
115 def __enter__(self):
116 return self.name
117
118 def rm(self):
119 if self.name:
120 shutil.rmtree(self.name, ignore_errors=True)
121 self.name = None
122
123 def __exit__(self, exc, value, tb):
124 self.rm()
125
126 def __del__(self):
127 self.rm()
128
129
130 def run_kwriteconfig(module, cmd, path, groups, key, value):
131 """Invoke kwriteconfig with arguments"""
132 args = [cmd, "--file", path, "--key", key]
133 for group in groups:
134 args.extend(["--group", group])
135 if isinstance(value, bool):
136 args.extend(["--type", "bool"])
137 if value:
138 args.append("true")
139 else:
140 args.append("false")
141 else:
142 args.extend(["--", value])
143 module.run_command(args, check_rc=True)
144
145
146 def run_module(module, tmpdir, kwriteconfig):
147 result = dict(changed=False, msg="OK", path=module.params["path"])
148 b_path = to_bytes(module.params["path"])
149 tmpfile = os.path.join(tmpdir, "file")
150 b_tmpfile = to_bytes(tmpfile)
151 diff = dict(
152 before="",
153 after="",
154 before_header=result["path"],
155 after_header=result["path"],
156 )
157 try:
158 with open(b_tmpfile, "wb") as dst:
159 try:
160 with open(b_path, "rb") as src:
161 b_data = src.read()
162 except OSError:
163 result["changed"] = True
164 else:
165 dst.write(b_data)
166 try:
167 diff["before"] = to_text(b_data)
168 except UnicodeError:
169 diff["before"] = repr(b_data)
170 except OSError:
171 module.fail_json(msg="Unable to create temporary file", traceback=traceback.format_exc())
172
173 for row in module.params["values"]:
174 groups = row["groups"]
175 if groups is None:
176 groups = [row["group"]]
177 key = row["key"]
178 value = row["bool_value"]
179 if value is None:
180 value = row["value"]
181 run_kwriteconfig(module, kwriteconfig, tmpfile, groups, key, value)
182
183 with open(b_tmpfile, "rb") as tmpf:
184 b_data = tmpf.read()
185 try:
186 diff["after"] = to_text(b_data)
187 except UnicodeError:
188 diff["after"] = repr(b_data)
189
190 result["changed"] = result["changed"] or diff["after"] != diff["before"]
191
192 file_args = module.load_file_common_arguments(module.params)
193
194 if module.check_mode:
195 if not result["changed"]:
196 shutil.copystat(b_path, b_tmpfile)
197 uid, gid = module.user_and_group(b_path)
198 os.chown(b_tmpfile, uid, gid)
199 if module._diff:
200 diff = {}
201 else:
202 diff = None
203 result["changed"] = module.set_fs_attributes_if_different(file_args, result["changed"], diff=diff)
204 if module._diff:
205 result["diff"] = diff
206 module.exit_json(**result)
207
208 if result["changed"]:
209 if module.params["backup"] and os.path.exists(b_path):
210 result["backup_file"] = module.backup_local(result["path"])
211 try:
212 module.atomic_move(b_tmpfile, os.path.abspath(b_path))
213 except OSError:
214 module.ansible.fail_json(
215 msg=f"Unable to move temporary file {tmpfile} to {result['path']}, IOError",
216 traceback=traceback.format_exc(),
217 )
218
219 if result["changed"]:
220 module.set_fs_attributes_if_different(file_args, result["changed"])
221 else:
222 if module._diff:
223 diff = {}
224 else:
225 diff = None
226 result["changed"] = module.set_fs_attributes_if_different(file_args, result["changed"], diff=diff)
227 if module._diff:
228 result["diff"] = diff
229 module.exit_json(**result)
230
231
232 def main():
233 single_value_arg = dict(
234 group=dict(type="str"),
235 groups=dict(type="list", elements="str"),
236 key=dict(type="str", required=True, no_log=False),
237 value=dict(type="str"),
238 bool_value=dict(type="bool"),
239 )
240 required_alternatives = [("group", "groups"), ("value", "bool_value")]
241 module_args = dict(
242 values=dict(
243 type="list",
244 elements="dict",
245 options=single_value_arg,
246 mutually_exclusive=required_alternatives,
247 required_one_of=required_alternatives,
248 required=True,
249 ),
250 path=dict(type="path", required=True),
251 kwriteconfig_path=dict(type="path"),
252 backup=dict(type="bool", default=False),
253 )
254
255 module = AnsibleModule(
256 argument_spec=module_args,
257 add_file_common_args=True,
258 supports_check_mode=True,
259 )
260
261 kwriteconfig = None
262 if module.params["kwriteconfig_path"] is not None:
263 kwriteconfig = module.get_bin_path(module.params["kwriteconfig_path"], required=True)
264 else:
265 for progname in ("kwriteconfig6", "kwriteconfig5", "kwriteconfig", "kwriteconfig4"):
266 kwriteconfig = module.get_bin_path(progname)
267 if kwriteconfig is not None:
268 break
269 if kwriteconfig is None:
270 module.fail_json(msg="kwriteconfig is not installed")
271 for v in module.params["values"]:
272 if not v["key"]:
273 module.fail_json(msg="'key' cannot be empty")
274 with TemporaryDirectory(dir=module.tmpdir) as tmpdir:
275 run_module(module, tmpdir, kwriteconfig)
276
277
278 if __name__ == "__main__":
279 main()