Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2022, Ansible Project
4 # Copyright (c) 2022, VMware, Inc. All Rights Reserved.
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: iso_customize
12 short_description: Add/remove/change files in ISO file
13 description:
14 - This module is used to add/remove/change files in ISO file.
15 - The file inside ISO is overwritten if it exists by option O(add_files).
16 author:
17 - Yuhua Zou (@ZouYuhua) <[email protected]>
18 requirements:
19 - "pycdlib"
20 version_added: '5.8.0'
21
22 extends_documentation_fragment:
23 - community.general._attributes
24
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: none
30
31 options:
32 src_iso:
33 description:
34 - This is the path of source ISO file.
35 type: path
36 required: true
37 dest_iso:
38 description:
39 - The path of the customized ISO file.
40 type: path
41 required: true
42 delete_files:
43 description:
44 - Absolute paths for files inside the ISO file that should be removed.
45 type: list
46 elements: str
47 default: []
48 add_files:
49 description:
50 - Allows to add and replace files in the ISO file.
51 - It creates intermediate folders inside the ISO file when they do not exist.
52 type: list
53 elements: dict
54 default: []
55 suboptions:
56 src_file:
57 description:
58 - The path with file name on the machine the module is executed on.
59 type: path
60 required: true
61 dest_file:
62 description:
63 - The absolute path of the file inside the ISO file.
64 type: str
65 required: true
66 notes:
67 - The function C(add_file) in pycdlib is designed to overwrite the existing file in ISO with type ISO9660 / Rock Ridge 1.12
68 / Joliet / UDF. But it does not overwrite the existing file in ISO with Rock Ridge 1.09 / 1.10. So we take workaround
69 "delete the existing file and then add file for ISO with Rock Ridge".
70 """
71
72 EXAMPLES = r"""
73 - name: "Customize ISO file"
74 community.general.iso_customize:
75 src_iso: "/path/to/ubuntu-22.04-desktop-amd64.iso"
76 dest_iso: "/path/to/ubuntu-22.04-desktop-amd64-customized.iso"
77 delete_files:
78 - "/boot.catalog"
79 add_files:
80 - src_file: "/path/to/grub.cfg"
81 dest_file: "/boot/grub/grub.cfg"
82 - src_file: "/path/to/ubuntu.seed"
83 dest_file: "/preseed/ubuntu.seed"
84 register: customize_iso_result
85 """
86
87 RETURN = r"""
88 src_iso:
89 description: Path of source ISO file.
90 returned: on success
91 type: str
92 sample: "/path/to/file.iso"
93 dest_iso:
94 description: Path of the customized ISO file.
95 returned: on success
96 type: str
97 sample: "/path/to/customized.iso"
98 """
99
100 import os
101
102 from ansible.module_utils.basic import AnsibleModule
103
104 from ansible_collections.community.general.plugins.module_utils import _deps as deps
105
106 with deps.declare("pycdlib"):
107 import pycdlib
108
109
110 # The upper dir exist, we only add subdirectoy
111 def iso_add_dir(module, opened_iso, iso_type, dir_path):
112 parent_dir, check_dirname = dir_path.rsplit("/", 1)
113 if not parent_dir.strip():
114 parent_dir = "/"
115 check_dirname = check_dirname.strip()
116
117 for dirname, dirlist, dummy_filelist in opened_iso.walk(iso_path=parent_dir.upper()):
118 if dirname == parent_dir.upper():
119 if check_dirname.upper() in dirlist:
120 return
121
122 if parent_dir == "/":
123 current_dirpath = f"/{check_dirname}"
124 else:
125 current_dirpath = f"{parent_dir}/{check_dirname}"
126
127 current_dirpath_upper = current_dirpath.upper()
128 try:
129 if iso_type == "iso9660":
130 opened_iso.add_directory(current_dirpath_upper)
131 elif iso_type == "rr":
132 opened_iso.add_directory(current_dirpath_upper, rr_name=check_dirname)
133 elif iso_type == "joliet":
134 opened_iso.add_directory(current_dirpath_upper, joliet_path=current_dirpath)
135 elif iso_type == "udf":
136 opened_iso.add_directory(current_dirpath_upper, udf_path=current_dirpath)
137 except Exception as err:
138 msg = f"Failed to create dir {current_dirpath} with error: {err}"
139 module.fail_json(msg=msg)
140
141
142 def iso_add_dirs(module, opened_iso, iso_type, dir_path):
143 dirnames = dir_path.strip().split("/")
144
145 current_dirpath = "/"
146 for item in dirnames:
147 if not item.strip():
148 continue
149 if current_dirpath == "/":
150 current_dirpath = f"/{item}"
151 else:
152 current_dirpath = f"{current_dirpath}/{item}"
153
154 iso_add_dir(module, opened_iso, iso_type, current_dirpath)
155
156
157 def iso_check_file_exists(opened_iso, dest_file):
158 file_dir = os.path.dirname(dest_file).strip()
159 file_name = os.path.basename(dest_file)
160 dirnames = file_dir.strip().split("/")
161
162 parent_dir = "/"
163 for item in dirnames:
164 if not item.strip():
165 continue
166
167 for dirname, dirlist, dummy_filelist in opened_iso.walk(iso_path=parent_dir.upper()):
168 if dirname != parent_dir.upper():
169 break
170
171 if item.upper() not in dirlist:
172 return False
173
174 if parent_dir == "/":
175 parent_dir = f"/{item}"
176 else:
177 parent_dir = f"{parent_dir}/{item}"
178
179 if "." not in file_name:
180 file_in_iso_path = f"{file_name.upper()}.;1"
181 else:
182 file_in_iso_path = f"{file_name.upper()};1"
183
184 for dirname, dummy_dirlist, filelist in opened_iso.walk(iso_path=parent_dir.upper()):
185 if dirname != parent_dir.upper():
186 return False
187
188 return file_name.upper() in filelist or file_in_iso_path in filelist
189
190
191 def iso_add_file(module, opened_iso, iso_type, src_file, dest_file):
192 dest_file = dest_file.strip()
193 if dest_file[0] != "/":
194 dest_file = f"/{dest_file}"
195
196 file_local = src_file.strip()
197
198 file_dir = os.path.dirname(dest_file).strip()
199 file_name = os.path.basename(dest_file)
200 if "." not in file_name:
201 file_in_iso_path = f"{dest_file.upper()}.;1"
202 else:
203 file_in_iso_path = f"{dest_file.upper()};1"
204
205 if file_dir and file_dir != "/":
206 iso_add_dirs(module, opened_iso, iso_type, file_dir)
207
208 try:
209 if iso_type == "iso9660":
210 opened_iso.add_file(file_local, iso_path=file_in_iso_path)
211 elif iso_type == "rr":
212 # For ISO with Rock Ridge 1.09 / 1.10, it won't overwrite the existing file
213 # So we take workaround here: delete the existing file and then add file
214 if iso_check_file_exists(opened_iso, dest_file):
215 opened_iso.rm_file(iso_path=file_in_iso_path)
216 opened_iso.add_file(file_local, iso_path=file_in_iso_path, rr_name=file_name)
217 elif iso_type == "joliet":
218 opened_iso.add_file(file_local, iso_path=file_in_iso_path, joliet_path=dest_file)
219 elif iso_type == "udf":
220 # For ISO with UDF, it won't always succeed to overwrite the existing file
221 # So we take workaround here: delete the existing file and then add file
222 if iso_check_file_exists(opened_iso, dest_file):
223 opened_iso.rm_file(udf_path=dest_file)
224 opened_iso.add_file(file_local, iso_path=file_in_iso_path, udf_path=dest_file)
225 except Exception as err:
226 msg = f"Failed to add local file {file_local} to ISO with error: {err}"
227 module.fail_json(msg=msg)
228
229
230 def iso_delete_file(module, opened_iso, iso_type, dest_file):
231 dest_file = dest_file.strip()
232 if dest_file[0] != "/":
233 dest_file = f"/{dest_file}"
234 file_name = os.path.basename(dest_file)
235
236 if not iso_check_file_exists(opened_iso, dest_file):
237 module.fail_json(msg=f"The file {dest_file} does not exist.")
238
239 if "." not in file_name:
240 file_in_iso_path = f"{dest_file.upper()}.;1"
241 else:
242 file_in_iso_path = f"{dest_file.upper()};1"
243
244 try:
245 if iso_type == "iso9660":
246 opened_iso.rm_file(iso_path=file_in_iso_path)
247 elif iso_type == "rr":
248 opened_iso.rm_file(iso_path=file_in_iso_path)
249 elif iso_type == "joliet":
250 opened_iso.rm_file(joliet_path=dest_file)
251 elif iso_type == "udf":
252 opened_iso.rm_file(udf_path=dest_file)
253 except Exception as err:
254 msg = f"Failed to delete iso file {dest_file} with error: {err}"
255 module.fail_json(msg=msg)
256
257
258 def iso_rebuild(module, src_iso, dest_iso, delete_files_list, add_files_list):
259 iso = None
260 iso_type = "iso9660"
261
262 try:
263 iso = pycdlib.PyCdlib(always_consistent=True)
264 iso.open(src_iso)
265 if iso.has_rock_ridge():
266 iso_type = "rr"
267 elif iso.has_joliet():
268 iso_type = "joliet"
269 elif iso.has_udf():
270 iso_type = "udf"
271
272 for item in delete_files_list:
273 iso_delete_file(module, iso, iso_type, item)
274
275 for item in add_files_list:
276 iso_add_file(module, iso, iso_type, item["src_file"], item["dest_file"])
277
278 iso.write(dest_iso)
279 except Exception as err:
280 msg = f"Failed to rebuild ISO {src_iso} with error: {err}"
281 module.fail_json(msg=msg)
282 finally:
283 if iso:
284 iso.close()
285
286
287 def main():
288 argument_spec = dict(
289 src_iso=dict(type="path", required=True),
290 dest_iso=dict(type="path", required=True),
291 delete_files=dict(type="list", elements="str", default=[]),
292 add_files=dict(
293 type="list",
294 elements="dict",
295 default=[],
296 options=dict(
297 src_file=dict(type="path", required=True),
298 dest_file=dict(type="str", required=True),
299 ),
300 ),
301 )
302 module = AnsibleModule(
303 argument_spec=argument_spec,
304 required_one_of=[
305 ("delete_files", "add_files"),
306 ],
307 supports_check_mode=True,
308 )
309 deps.validate(module)
310
311 src_iso = module.params["src_iso"]
312 if not os.path.exists(src_iso):
313 module.fail_json(msg=f"ISO file {src_iso} does not exist.")
314
315 dest_iso = module.params["dest_iso"]
316 dest_iso_dir = os.path.dirname(dest_iso)
317 if dest_iso_dir and not os.path.exists(dest_iso_dir):
318 module.fail_json(msg=f"The dest directory {dest_iso_dir} does not exist")
319
320 delete_files_list = [s.strip() for s in module.params["delete_files"]]
321 add_files_list = module.params["add_files"]
322 if add_files_list:
323 for item in add_files_list:
324 if not os.path.exists(item["src_file"]):
325 module.fail_json(msg=f"The file {item['src_file']} does not exist.")
326
327 result = dict(
328 src_iso=src_iso,
329 customized_iso=dest_iso,
330 delete_files=delete_files_list,
331 add_files=add_files_list,
332 changed=True,
333 )
334
335 if not module.check_mode:
336 iso_rebuild(module, src_iso, dest_iso, delete_files_list, add_files_list)
337
338 result["changed"] = True
339 module.exit_json(**result)
340
341
342 if __name__ == "__main__":
343 main()