Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2020, Ansible Project
4 # Copyright (c) 2020, 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_create
12 short_description: Generate ISO file with specified files or folders
13 description:
14 - This module is used to generate ISO file with specified path of files.
15 author:
16 - Diane Wang (@Tomorrow9) <[email protected]>
17 requirements:
18 - "pycdlib"
19 version_added: '0.2.0'
20
21 extends_documentation_fragment:
22 - community.general._attributes
23
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: none
29
30 options:
31 src_files:
32 description:
33 - This is a list of absolute paths of source files or folders to be contained in the new generated ISO file.
34 - The module fails if specified file or folder in O(src_files) does not exist on local machine.
35 - 'Note: With all ISO9660 levels from 1 to 3, all file names are restricted to uppercase letters, numbers and underscores
36 (_). File names are limited to 31 characters, directory nesting is limited to 8 levels, and path names are limited
37 to 255 characters.'
38 type: list
39 required: true
40 elements: path
41 dest_iso:
42 description:
43 - The absolute path with file name of the new generated ISO file on local machine.
44 - It creates intermediate folders when they do not exist.
45 type: path
46 required: true
47 interchange_level:
48 description:
49 - The ISO9660 interchange level to use, it dictates the rules on the names of files.
50 - Levels and valid values V(1), V(2), V(3), V(4) are supported.
51 - The default value is level V(1), which is the most conservative, level V(3) is recommended.
52 - ISO9660 file names at interchange level V(1) cannot have more than 8 characters or 3 characters in the extension.
53 type: int
54 default: 1
55 choices: [1, 2, 3, 4]
56 vol_ident:
57 description:
58 - The volume identification string to use on the new generated ISO image.
59 type: str
60 rock_ridge:
61 description:
62 - Whether to make this ISO have the Rock Ridge extensions or not.
63 - Valid values are V(1.09), V(1.10) or V(1.12), means adding the specified Rock Ridge version to the ISO.
64 - If unsure, set V(1.09) to ensure maximum compatibility.
65 - If not specified, then not add Rock Ridge extension to the ISO.
66 type: str
67 choices: ['1.09', '1.10', '1.12']
68 joliet:
69 description:
70 - Support levels and valid values are V(1), V(2), or V(3).
71 - Level V(3) is by far the most common.
72 - If not specified, then no Joliet support is added.
73 type: int
74 choices: [1, 2, 3]
75 udf:
76 description:
77 - Whether to add UDF support to this ISO.
78 - If set to V(true), then version 2.60 of the UDF spec is used.
79 - If not specified or set to V(false), then no UDF support is added.
80 type: bool
81 default: false
82 boot_options:
83 description:
84 - Options for making the ISO bootable using El Torito boot support.
85 - If not specified, the ISO will not be bootable.
86 type: dict
87 version_added: 13.0.0
88 suboptions:
89 boot_file:
90 description:
91 - Local path to the boot image file to embed in the ISO.
92 - The file is added to the root of the ISO and referenced as the El Torito boot image.
93 - The boot image must not share a filename with any file added via O(src_files), or pycdlib will raise a duplicate entry error.
94 type: path
95 required: true
96 boot_catalog:
97 description:
98 - ISO9660 path for the El Torito boot catalog file inside the ISO.
99 type: str
100 default: '/BOOT.CAT;1'
101 media_name:
102 description:
103 - Media emulation type for the El Torito boot entry.
104 type: str
105 default: 'noemul'
106 choices: ['noemul', 'floppy', '1.2m', '1.44m', '2.88m']
107 platform_id:
108 description:
109 - Target platform for the El Torito boot entry.
110 type: str
111 default: 'x86'
112 choices: ['x86', 'efi', 'mac']
113 boot_info_table:
114 description:
115 - Whether to add a boot info table to the boot image.
116 - Required by some bootloaders such as ISOLINUX.
117 type: bool
118 default: false
119 """
120
121 EXAMPLES = r"""
122 - name: Create an ISO file
123 community.general.iso_create:
124 src_files:
125 - /root/testfile.yml
126 - /root/testfolder
127 dest_iso: /tmp/test.iso
128 interchange_level: 3
129
130 - name: Create an ISO file with Rock Ridge extension
131 community.general.iso_create:
132 src_files:
133 - /root/testfile.yml
134 - /root/testfolder
135 dest_iso: /tmp/test.iso
136 rock_ridge: 1.09
137
138 - name: Create an ISO file with Joliet support
139 community.general.iso_create:
140 src_files:
141 - ./windows_config/Autounattend.xml
142 dest_iso: ./test.iso
143 interchange_level: 3
144 joliet: 3
145 vol_ident: WIN_AUTOINSTALL
146
147 - name: Create a bootable ISO file using ISOLINUX
148 community.general.iso_create:
149 src_files:
150 - /root/isocontents/isolinux.cfg
151 dest_iso: /tmp/boot.iso
152 interchange_level: 3
153 boot_options:
154 boot_file: /root/isocontents/isolinux.bin
155 media_name: noemul
156 boot_info_table: true
157 """
158
159 RETURN = r"""
160 source_file:
161 description: Configured source files or directories list.
162 returned: on success
163 type: list
164 elements: path
165 sample: ["/path/to/file.txt", "/path/to/folder"]
166 created_iso:
167 description: Created iso file path.
168 returned: on success
169 type: str
170 sample: "/path/to/test.iso"
171 interchange_level:
172 description: Configured interchange level.
173 returned: on success
174 type: int
175 sample: 3
176 vol_ident:
177 description: Configured volume identification string.
178 returned: on success
179 type: str
180 sample: "OEMDRV"
181 joliet:
182 description: Configured Joliet support level.
183 returned: on success
184 type: int
185 sample: 3
186 rock_ridge:
187 description: Configured Rock Ridge version.
188 returned: on success
189 type: str
190 sample: "1.09"
191 udf:
192 description: Configured UDF support.
193 returned: on success
194 type: bool
195 sample: false
196 boot_options:
197 description: Configured El Torito boot options, or V(null) if the ISO is not bootable.
198 returned: on success
199 type: dict
200 version_added: 13.0.0
201 contains:
202 boot_file:
203 description: Local path to the boot image file.
204 type: str
205 sample: "/root/isolinux/isolinux.bin"
206 boot_catalog:
207 description: ISO9660 path of the boot catalog inside the ISO.
208 type: str
209 sample: "/BOOT.CAT;1"
210 media_name:
211 description: Media emulation type.
212 type: str
213 sample: "noemul"
214 platform_id:
215 description: Target platform identifier.
216 type: str
217 sample: "x86"
218 boot_info_table:
219 description: Whether a boot info table was added to the boot image.
220 type: bool
221 sample: false
222 """
223
224 import os
225 import traceback
226
227 PLATFORM_ID_MAP = {
228 "x86": b"\x00",
229 "efi": b"\xef",
230 "mac": b"\x02",
231 }
232
233 PYCDLIB_IMP_ERR = None
234 try:
235 import pycdlib
236
237 HAS_PYCDLIB = True
238 except ImportError:
239 PYCDLIB_IMP_ERR = traceback.format_exc()
240 HAS_PYCDLIB = False
241
242 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
243
244
245 def add_file(module, iso_file=None, src_file=None, file_path=None, rock_ridge=None, use_joliet=None, use_udf=None):
246 rr_name = None
247 joliet_path = None
248 udf_path = None
249 # In standard ISO interchange level 1, file names have a maximum of 8 characters, followed by a required dot,
250 # followed by a maximum 3 character extension, followed by a semicolon and a version
251 file_name = os.path.basename(file_path)
252 if "." not in file_name:
253 file_in_iso_path = f"{file_path.upper()}.;1"
254 else:
255 file_in_iso_path = f"{file_path.upper()};1"
256 if rock_ridge:
257 rr_name = file_name
258 if use_joliet:
259 joliet_path = file_path
260 if use_udf:
261 udf_path = file_path
262 try:
263 iso_file.add_file(
264 src_file, iso_path=file_in_iso_path, rr_name=rr_name, joliet_path=joliet_path, udf_path=udf_path
265 )
266 except Exception as err:
267 module.fail_json(msg=f"Failed to add file {src_file} to ISO file due to {err}")
268
269
270 def add_directory(module, iso_file=None, dir_path=None, rock_ridge=None, use_joliet=None, use_udf=None):
271 rr_name = None
272 joliet_path = None
273 udf_path = None
274 iso_dir_path = dir_path.upper()
275 if rock_ridge:
276 rr_name = os.path.basename(dir_path)
277 if use_joliet:
278 joliet_path = dir_path
279 if use_udf:
280 udf_path = dir_path
281 try:
282 iso_file.add_directory(iso_path=iso_dir_path, rr_name=rr_name, joliet_path=joliet_path, udf_path=udf_path)
283 except Exception as err:
284 module.fail_json(msg=f"Failed to directory {dir_path} to ISO file due to {err}")
285
286
287 def main():
288 argument_spec = dict(
289 src_files=dict(type="list", required=True, elements="path"),
290 dest_iso=dict(type="path", required=True),
291 interchange_level=dict(type="int", choices=[1, 2, 3, 4], default=1),
292 vol_ident=dict(type="str"),
293 rock_ridge=dict(type="str", choices=["1.09", "1.10", "1.12"]),
294 joliet=dict(type="int", choices=[1, 2, 3]),
295 udf=dict(type="bool", default=False),
296 boot_options=dict(
297 type="dict",
298 options=dict(
299 boot_file=dict(type="path", required=True),
300 boot_catalog=dict(type="str", default="/BOOT.CAT;1"),
301 media_name=dict(type="str", default="noemul", choices=["noemul", "floppy", "1.2m", "1.44m", "2.88m"]),
302 platform_id=dict(type="str", default="x86", choices=["x86", "efi", "mac"]),
303 boot_info_table=dict(type="bool", default=False),
304 ),
305 ),
306 )
307 module = AnsibleModule(
308 argument_spec=argument_spec,
309 supports_check_mode=True,
310 )
311 if not HAS_PYCDLIB:
312 module.fail_json(missing_required_lib("pycdlib"), exception=PYCDLIB_IMP_ERR)
313
314 src_file_list = module.params.get("src_files")
315 if src_file_list and len(src_file_list) == 0:
316 module.fail_json(msg="Please specify source file and/or directory list using src_files parameter.")
317 for src_file in src_file_list:
318 if not os.path.exists(src_file):
319 module.fail_json(msg=f"Specified source file/directory path does not exist on local machine, {src_file}")
320
321 boot_options = module.params.get("boot_options")
322 if boot_options:
323 boot_file = boot_options["boot_file"]
324 if not os.path.exists(boot_file):
325 module.fail_json(msg=f"Specified boot file path does not exist on local machine, {boot_file}")
326
327 dest_iso = module.params.get("dest_iso")
328 if dest_iso and len(dest_iso) == 0:
329 module.fail_json(msg="Please specify the absolute path of the new created ISO file using dest_iso parameter.")
330
331 dest_iso_dir = os.path.dirname(dest_iso)
332 if dest_iso_dir and not os.path.exists(dest_iso_dir):
333 # will create intermediate dir for new ISO file
334 try:
335 os.makedirs(dest_iso_dir)
336 except OSError as err:
337 module.fail_json(msg=f"Exception caught when creating folder {dest_iso_dir}, with error {err}")
338
339 volume_id = module.params.get("vol_ident")
340 if volume_id is None:
341 volume_id = ""
342 inter_level = module.params.get("interchange_level")
343 rock_ridge = module.params.get("rock_ridge")
344 use_joliet = module.params.get("joliet")
345 use_udf = None
346 if module.params["udf"]:
347 use_udf = "2.60"
348
349 result = dict(
350 changed=False,
351 source_file=src_file_list,
352 created_iso=dest_iso,
353 interchange_level=inter_level,
354 vol_ident=volume_id,
355 rock_ridge=rock_ridge,
356 joliet=use_joliet,
357 udf=use_udf,
358 boot_options=boot_options,
359 )
360 if not module.check_mode:
361 iso_file = pycdlib.PyCdlib(always_consistent=True)
362 iso_file.new(
363 interchange_level=inter_level, vol_ident=volume_id, rock_ridge=rock_ridge, joliet=use_joliet, udf=use_udf
364 )
365
366 for src_file in src_file_list:
367 # if specify a dir then go through the dir to add files and dirs
368 if os.path.isdir(src_file):
369 dir_list = []
370 file_list = []
371 src_file = src_file.rstrip("/")
372 dir_name = os.path.basename(src_file)
373 add_directory(
374 module,
375 iso_file=iso_file,
376 dir_path=f"/{dir_name}",
377 rock_ridge=rock_ridge,
378 use_joliet=use_joliet,
379 use_udf=use_udf,
380 )
381
382 # get dir list and file list
383 for path, dirs, files in os.walk(src_file):
384 for filename in files:
385 file_list.append(os.path.join(path, filename))
386 for dir in dirs:
387 dir_list.append(os.path.join(path, dir))
388 for new_dir in dir_list:
389 add_directory(
390 module,
391 iso_file=iso_file,
392 dir_path=new_dir.split(os.path.dirname(src_file))[1],
393 rock_ridge=rock_ridge,
394 use_joliet=use_joliet,
395 use_udf=use_udf,
396 )
397 for new_file in file_list:
398 add_file(
399 module,
400 iso_file=iso_file,
401 src_file=new_file,
402 file_path=new_file.split(os.path.dirname(src_file))[1],
403 rock_ridge=rock_ridge,
404 use_joliet=use_joliet,
405 use_udf=use_udf,
406 )
407 # if specify a file then add this file directly to the '/' path in ISO
408 else:
409 add_file(
410 module,
411 iso_file=iso_file,
412 src_file=src_file,
413 file_path=f"/{os.path.basename(src_file)}",
414 rock_ridge=rock_ridge,
415 use_joliet=use_joliet,
416 use_udf=use_udf,
417 )
418
419 if boot_options:
420 boot_file = boot_options["boot_file"]
421 boot_file_basename = os.path.basename(boot_file)
422 if "." not in boot_file_basename:
423 boot_iso_path = f"/{boot_file_basename.upper()}.;1"
424 else:
425 boot_iso_path = f"/{boot_file_basename.upper()};1"
426 add_file(
427 module,
428 iso_file=iso_file,
429 src_file=boot_file,
430 file_path=f"/{boot_file_basename}",
431 rock_ridge=rock_ridge,
432 use_joliet=use_joliet,
433 use_udf=use_udf,
434 )
435 boot_catalog_basename = os.path.basename(boot_options["boot_catalog"]).split(";")[0].lower()
436 eltorito_kwargs = dict(
437 bootcatfile=boot_options["boot_catalog"],
438 media_name=boot_options["media_name"],
439 platform_id=PLATFORM_ID_MAP[boot_options["platform_id"]],
440 boot_info_table=boot_options["boot_info_table"],
441 )
442 if rock_ridge:
443 eltorito_kwargs["rr_bootcatfile"] = boot_catalog_basename
444 if use_joliet:
445 eltorito_kwargs["joliet_bootcatfile"] = f"/{boot_catalog_basename}"
446 try:
447 iso_file.add_eltorito(boot_iso_path, **eltorito_kwargs)
448 except Exception as err:
449 module.fail_json(msg=f"Failed to add El Torito boot record to ISO file: {err}")
450
451 iso_file.write(dest_iso)
452 iso_file.close()
453
454 result["changed"] = True
455 module.exit_json(**result)
456
457
458 if __name__ == "__main__":
459 main()