Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Jeroen Hoekx <[email protected]>
4 # Copyright (c) 2016, Matt Robinson <[email protected]>
5 # Copyright (c) 2017, Dag Wieers <[email protected]>
6 # Copyright (c) 2017, Ansible Project
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 author:
14 - Jeroen Hoekx (@jhoekx)
15 - Matt Robinson (@ribbons)
16 - Dag Wieers (@dagwieers)
17 module: iso_extract
18 short_description: Extract files from an ISO image
19 description:
20 - This module has two possible ways of operation.
21 - If 7zip is installed on the system, this module extracts files from an ISO into a temporary directory and copies files
22 to a given destination, if needed.
23 - If the user has mount-capabilities (CAP_SYS_ADMIN on Linux) this module mounts the ISO image to a temporary location,
24 and copies files to a given destination, if needed.
25 requirements:
26 - Either 7z (from C(7zip) or C(p7zip) package)
27 - Or mount capabilities (root-access, or CAP_SYS_ADMIN capability on Linux)
28 extends_documentation_fragment:
29 - community.general._attributes
30 attributes:
31 check_mode:
32 support: full
33 diff_mode:
34 support: none
35 options:
36 image:
37 description:
38 - The ISO image to extract files from.
39 type: path
40 required: true
41 aliases: [path, src]
42 dest:
43 description:
44 - The destination directory to extract files to.
45 type: path
46 required: true
47 files:
48 description:
49 - A list of files to extract from the image.
50 - Extracting directories does not work.
51 - File paths should not include a leading V(/); any leading path separator is automatically stripped.
52 type: list
53 elements: str
54 required: true
55 force:
56 description:
57 - If V(true), it replaces the remote file when contents are different than the source.
58 - If V(false), the file is only extracted and copied if the destination does not already exist.
59 type: bool
60 default: true
61 executable:
62 description:
63 - The path to the C(7z) executable to use for extracting files from the ISO.
64 - If not provided, it assumes the value V(7z).
65 type: path
66 password:
67 description:
68 - Password used to decrypt files from the ISO.
69 - It is only used if C(7z) is used.
70 - The password is used as a command line argument to 7z. This is a B(potential security risk) that allows passwords
71 to be revealed if someone else can list running processes on the same machine in the right moment.
72 type: str
73 version_added: 10.1.0
74 notes:
75 - Only the file checksum (content) is taken into account when extracting files from the ISO image. If O(force=false), only
76 checks the presence of the file.
77 """
78
79 EXAMPLES = r"""
80 - name: Extract kernel and ramdisk from a LiveCD
81 community.general.iso_extract:
82 image: /tmp/rear-test.iso
83 dest: /tmp/virt-rear/
84 files:
85 - isolinux/kernel
86 - isolinux/initrd.cgz
87 """
88
89 RETURN = r"""
90 #
91 """
92
93 import os.path
94 import shutil
95 import tempfile
96 import time
97
98 from ansible.module_utils.basic import AnsibleModule
99
100
101 def main():
102 module = AnsibleModule(
103 argument_spec=dict(
104 image=dict(type="path", required=True, aliases=["path", "src"]),
105 dest=dict(type="path", required=True),
106 files=dict(type="list", elements="str", required=True),
107 force=dict(type="bool", default=True),
108 password=dict(type="str", no_log=True),
109 executable=dict(type="path"), # No default on purpose
110 ),
111 supports_check_mode=True,
112 )
113 image = module.params["image"]
114 dest = module.params["dest"]
115 files = module.params["files"]
116 force = module.params["force"]
117 password = module.params["password"]
118 executable = module.params["executable"]
119
120 result = dict(
121 changed=False,
122 dest=dest,
123 image=image,
124 )
125
126 # We want to know if the user provided it or not, so we set default here
127 if executable is None:
128 executable = "7z"
129
130 binary = module.get_bin_path(executable, None)
131
132 # When executable was provided and binary not found, warn user !
133 if module.params["executable"] is not None and not binary:
134 module.warn(f"Executable '{executable}' is not found on the system, trying to mount ISO instead.")
135
136 if not os.path.exists(dest):
137 module.fail_json(msg=f"Directory '{dest}' does not exist")
138
139 if not os.path.exists(os.path.dirname(image)):
140 module.fail_json(msg=f"ISO image '{image}' does not exist")
141
142 result["files"] = []
143 extract_files = [f.lstrip(os.sep) for f in files]
144
145 if not force:
146 # Check if we have to process any files based on existence
147 for f in extract_files[:]:
148 dest_file = os.path.join(dest, os.path.basename(f))
149 if os.path.exists(dest_file):
150 result["files"].append(
151 dict(
152 checksum=None,
153 dest=dest_file,
154 src=f,
155 )
156 )
157 extract_files.remove(f)
158
159 if not extract_files:
160 module.exit_json(**result)
161
162 tmp_dir = tempfile.mkdtemp()
163
164 # Use 7zip when we have a binary, otherwise try to mount
165 if binary:
166 cmd = [binary, "x", image, f"-o{tmp_dir}"]
167 if password:
168 cmd += [f"-p{password}"]
169 cmd += extract_files
170 else:
171 cmd = [module.get_bin_path("mount"), "-o", "loop,ro", image, tmp_dir]
172
173 rc, out, err = module.run_command(cmd)
174 if rc != 0:
175 result.update(
176 dict(
177 cmd=cmd,
178 rc=rc,
179 stderr=err,
180 stdout=out,
181 )
182 )
183 shutil.rmtree(tmp_dir)
184
185 if binary:
186 module.fail_json(msg=f"Failed to extract from ISO image '{image}' to '{tmp_dir}'", **result)
187 else:
188 module.fail_json(
189 msg=f"Failed to mount ISO image '{image}' to '{tmp_dir}', and we could not find executable '{executable}'.",
190 **result,
191 )
192
193 try:
194 for f in extract_files:
195 tmp_src = os.path.join(tmp_dir, f)
196 if not os.path.exists(tmp_src):
197 module.fail_json(msg=f"Failed to extract '{f}' from ISO image", **result)
198
199 src_checksum = module.sha1(tmp_src)
200
201 dest_file = os.path.join(dest, os.path.basename(f))
202
203 if os.path.exists(dest_file):
204 dest_checksum = module.sha1(dest_file)
205 else:
206 dest_checksum = None
207
208 result["files"].append(
209 dict(
210 checksum=src_checksum,
211 dest=dest_file,
212 src=f,
213 )
214 )
215
216 if src_checksum != dest_checksum:
217 if not module.check_mode:
218 shutil.copy(tmp_src, dest_file)
219
220 result["changed"] = True
221 finally:
222 if not binary:
223 umount_cmd = [module.get_bin_path("umount"), tmp_dir]
224 for dummy in range(5):
225 rc, dummy, dummy = module.run_command(umount_cmd)
226 if rc == 0:
227 break
228 time.sleep(1)
229 else:
230 module.warn(f"Failed to unmount ISO image from '{tmp_dir}' after 5 attempts.")
231
232 shutil.rmtree(tmp_dir)
233
234 module.exit_json(**result)
235
236
237 if __name__ == "__main__":
238 main()