Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox_template.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright Ansible Project
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
8 DOCUMENTATION = r"""
9 module: proxmox_template
10 short_description: Management of OS templates in Proxmox VE cluster
11 description:
12 - Allows you to upload/delete templates in Proxmox VE cluster.
13 attributes:
14 check_mode:
15 support: none
16 diff_mode:
17 support: none
18 options:
19 node:
20 description:
21 - Proxmox VE node on which to operate.
22 type: str
23 src:
24 description:
25 - Path to uploaded file.
26 - Exactly one of O(src) or O(url) is required for O(state=present).
27 type: path
28 url:
29 description:
30 - URL to file to download.
31 - Exactly one of O(src) or O(url) is required for O(state=present).
32 type: str
33 template:
34 description:
35 - The template name.
36 - Required for O(state=absent) to delete a template.
37 - Required for O(state=present) to download an appliance container template (pveam).
38 type: str
39 content_type:
40 description:
41 - Content type of the template.
42 - Valid values are V(vztmpl) for LXC container templates, V(iso) for ISO disc images, and V(import) for harddisk images and Open Virtual Appliances (OVA).
43 type: str
44 default: 'vztmpl'
45 choices: ['vztmpl', 'import', 'iso']
46 storage:
47 description:
48 - Target storage.
49 type: str
50 default: 'local'
51 timeout:
52 description:
53 - Timeout for operations.
54 type: int
55 default: 30
56 force:
57 description:
58 - It can only be used with O(state=present), existing template will be overwritten.
59 type: bool
60 default: false
61 state:
62 description:
63 - Indicate desired state of the template.
64 type: str
65 choices: ['present', 'absent']
66 default: present
67 checksum_algorithm:
68 description:
69 - Algorithm used to verify the checksum.
70 - If specified, O(checksum) must also be specified.
71 type: str
72 choices: ['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512']
73 checksum:
74 description:
75 - The checksum to validate against.
76 - Checksums are often provided by software distributors to verify that a download is not corrupted.
77 - Checksums can usually be found on the distributors download page in the form of a file or string.
78 - If specified, O(checksum_algorithm) must also be specified.
79 type: str
80 notes:
81 - Requires C(proxmoxer) and C(requests) modules on host. Those modules can be installed with M(ansible.builtin.pip).
82 - Requires C(requests_toolbelt) to upload files larger than 256 MB.
83 author: Sergei Antipov (@UnderGreen)
84 extends_documentation_fragment:
85 - community.proxmox.proxmox.actiongroup_proxmox
86 - community.proxmox.proxmox.documentation
87 - community.proxmox.attributes
88 """
89
90 EXAMPLES = r"""
91 ---
92 - name: Upload new openvz template with minimal options
93 community.proxmox.proxmox_template:
94 node: uk-mc02
95 src: ~/ubuntu-14.04-x86_64.tar.gz
96
97 - name: Pull new openvz template with minimal options
98 community.proxmox.proxmox_template:
99 node: uk-mc02
100 url: https://ubuntu-mirror/ubuntu-14.04-x86_64.tar.gz
101
102 - name: >
103 Upload new openvz template with minimal options use environment
104 PROXMOX_PASSWORD variable(you should export it before)
105 community.proxmox.proxmox_template:
106 node: uk-mc02
107 src: ~/ubuntu-14.04-x86_64.tar.gz
108
109 - name: Upload new openvz template with all options and force overwrite
110 community.proxmox.proxmox_template:
111 node: uk-mc02
112 storage: local
113 content_type: vztmpl
114 src: ~/ubuntu-14.04-x86_64.tar.gz
115 force: true
116
117 - name: Pull new openvz template with all options and force overwrite
118 community.proxmox.proxmox_template:
119 node: uk-mc02
120 storage: local
121 content_type: vztmpl
122 url: https://ubuntu-mirror/ubuntu-14.04-x86_64.tar.gz
123 force: true
124
125 - name: Delete template with minimal options
126 community.proxmox.proxmox_template:
127 node: uk-mc02
128 template: ubuntu-14.04-x86_64.tar.gz
129 state: absent
130
131 - name: Download proxmox appliance container template
132 community.proxmox.proxmox_template:
133 node: uk-mc02
134 storage: local
135 content_type: vztmpl
136 template: ubuntu-20.04-standard_20.04-1_amd64.tar.gz
137
138 - name: Download and verify a template's checksum
139 community.proxmox.proxmox_template:
140 node: uk-mc02
141 url: ubuntu-20.04-standard_20.04-1_amd64.tar.gz
142 checksum_algorithm: sha256
143 checksum: 65d860160bdc9b98abf72407e14ca40b609417de7939897d3b58d55787aaef69
144
145 - name: Upload new disk image template with minimal options
146 community.proxmox.proxmox_template:
147 node: uk-mc02
148 content_type: import
149 src: debian-13-genericcloud-amd64.qcow2
150
151 - name: Upload new ISO with minimal options
152 community.proxmox.proxmox_template:
153 node: uk-mc02
154 content_type: iso
155 src: proxmox.iso
156 """
157
158 import os
159 import time
160 import traceback
161 from urllib.parse import urlencode, urlparse
162
163 from ansible.module_utils.basic import missing_required_lib
164
165 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
166 ProxmoxAnsible,
167 create_proxmox_module,
168 )
169
170 REQUESTS_TOOLBELT_ERR = None
171 MAX_FILE_SIZE_WITHOUT_REQUESTS_TOOLBELT = 256 * 1024 * 1024 # 256 MB
172
173 try:
174 # requests_toolbelt is used internally by proxmoxer module
175 import requests_toolbelt # noqa: F401, pylint: disable=unused-import
176
177 HAS_REQUESTS_TOOLBELT = True
178 except ImportError:
179 HAS_REQUESTS_TOOLBELT = False
180 REQUESTS_TOOLBELT_ERR = traceback.format_exc()
181
182
183 def module_args():
184 return dict(
185 node=dict(),
186 src=dict(type="path"),
187 url=dict(),
188 template=dict(),
189 content_type=dict(default="vztmpl", choices=["vztmpl", "iso", "import"]),
190 storage=dict(default="local"),
191 timeout=dict(type="int", default=30),
192 force=dict(type="bool", default=False),
193 state=dict(default="present", choices=["present", "absent"]),
194 checksum_algorithm=dict(choices=["md5", "sha1", "sha224", "sha256", "sha384", "sha512"]),
195 checksum=dict(type="str"),
196 )
197
198
199 def module_options():
200 return dict(
201 supports_check_mode=False,
202 required_together=[("checksum", "checksum_algorithm")],
203 required_if=[("state", "absent", ["template"])],
204 mutually_exclusive=[("src", "url")],
205 )
206
207
208 class ProxmoxTemplateAnsible(ProxmoxAnsible):
209 def has_template(self, node, storage, content_type, template):
210 volid = f"{storage}:{content_type}/{template}"
211 try:
212 return any(tmpl["volid"] == volid for tmpl in self.proxmox_api.nodes(node).storage(storage).content.get())
213 except Exception as e:
214 self.module.fail_json(msg=f"Failed to retrieve template '{volid}': {e}")
215
216 def task_status(self, node, taskid, timeout):
217 """
218 Check the task status and wait until the task is completed or the timeout is reached.
219 """
220 while timeout:
221 if self.api_task_ok(node, taskid):
222 return True
223 elif self.api_task_failed(node, taskid):
224 self.module.fail_json(
225 msg=f"Task error: {self.proxmox_api.nodes(node).tasks(taskid).status.get()['exitstatus']}"
226 )
227 timeout = timeout - 1
228 if timeout == 0:
229 last_log = self.proxmox_api.nodes(node).tasks(taskid).log.get()[:1]
230 self.module.fail_json(
231 msg=f"Reached timeout while waiting for uploading/downloading template. Last line in task before timeout: {last_log}"
232 )
233
234 time.sleep(1)
235 return False
236
237 def upload_template(self, node, storage, content_type, realpath, timeout):
238 stats = os.stat(realpath)
239 if stats.st_size > MAX_FILE_SIZE_WITHOUT_REQUESTS_TOOLBELT and not HAS_REQUESTS_TOOLBELT:
240 self.module.fail_json(
241 msg=missing_required_lib("requests_toolbelt", reason="to upload files larger than 256MB"),
242 exception=REQUESTS_TOOLBELT_ERR,
243 )
244
245 try:
246 taskid = (
247 self.proxmox_api.nodes(node)
248 .storage(storage)
249 .upload.post(content=content_type, filename=open(realpath, "rb")) # noqa: SIM115
250 )
251 return self.task_status(node, taskid, timeout)
252 except Exception as e:
253 self.module.fail_json(msg=f"Uploading template {realpath} failed with error: {e}")
254
255 def fetch_template(self, node, storage, content_type, url, timeout, template): # noqa: PLR0913
256 """Fetch a template from a web url source using the proxmox download-url endpoint"""
257 try:
258 taskid = (
259 self.proxmox_api.nodes(node)
260 .storage(storage)("download-url")
261 .post(url=url, content=content_type, filename=template)
262 )
263 return self.task_status(node, taskid, timeout)
264 except Exception as e:
265 self.module.fail_json(msg=f"Fetching template from url {url} failed with error: {e}")
266
267 def download_template(self, node, storage, template, timeout):
268 try:
269 taskid = self.proxmox_api.nodes(node).aplinfo.post(storage=storage, template=template)
270 return self.task_status(node, taskid, timeout)
271 except Exception as e:
272 self.module.fail_json(msg=f"Downloading template {template} failed with error: {e}")
273
274 def delete_template(self, node, storage, content_type, template, timeout):
275 volid = f"{storage}:{content_type}/{template}"
276 self.proxmox_api.nodes(node).storage(storage).content.delete(volid)
277 while timeout:
278 if not self.has_template(node, storage, content_type, template):
279 return True
280 timeout = timeout - 1
281 if timeout == 0:
282 self.module.fail_json(msg="Reached timeout while waiting for deleting template.")
283
284 time.sleep(1)
285 return False
286
287 def fetch_and_verify(self, node, storage, url, content_type, timeout, checksum, checksum_algorithm, template): # noqa: PLR0913
288 """Fetch a template from a web url, then verify it using a checksum."""
289 data = {
290 "url": url,
291 "content": content_type,
292 "filename": template,
293 "checksum": checksum,
294 "checksum-algorithm": checksum_algorithm,
295 }
296 try:
297 taskid = self.proxmox_api.nodes(node).storage(storage).post(f"download-url?{urlencode(data)}")
298 return self.task_status(node, taskid, timeout)
299 except Exception as e:
300 self.module.fail_json(msg=f"Checksum mismatch: {e}")
301
302
303 def main(): # noqa: PLR0912, PLR0915
304 module = create_proxmox_module(module_args(), **module_options())
305 proxmox = ProxmoxTemplateAnsible(module)
306
307 state = module.params["state"]
308 node = module.params["node"]
309 storage = module.params["storage"]
310 timeout = module.params["timeout"]
311 checksum = module.params["checksum"]
312 checksum_algorithm = module.params["checksum_algorithm"]
313
314 if state == "present":
315 content_type = module.params["content_type"]
316 src = module.params["src"]
317 url = module.params["url"]
318 template = module.params["template"]
319
320 # download appliance template
321 if content_type == "vztmpl" and not (src or url):
322 if not template:
323 module.fail_json(msg="template param for downloading appliance template is mandatory")
324
325 if proxmox.has_template(node, storage, content_type, template) and not module.params["force"]:
326 module.exit_json(
327 changed=False, msg=f"template with volid={storage}:{content_type}/{template} already exists"
328 )
329
330 if proxmox.download_template(node, storage, template, timeout):
331 module.exit_json(
332 changed=True, msg=f"template with volid={storage}:{content_type}/{template} downloaded"
333 )
334
335 if not src and not url:
336 module.fail_json(msg="src or url param for uploading template file is mandatory")
337 elif not url:
338 template = os.path.basename(src)
339 if proxmox.has_template(node, storage, content_type, template) and not module.params["force"]:
340 module.exit_json(
341 changed=False, msg=f"template with volid={storage}:{content_type}/{template} already exists"
342 )
343 elif not (os.path.exists(src) and os.path.isfile(src)):
344 module.fail_json(msg=f"template file on path {src} not exists")
345
346 if proxmox.upload_template(node, storage, content_type, src, timeout):
347 module.exit_json(changed=True, msg=f"template with volid={storage}:{content_type}/{template} uploaded")
348 elif not src:
349 if not template:
350 template = os.path.basename(urlparse(url).path)
351
352 if proxmox.has_template(node, storage, content_type, template):
353 if not module.params["force"]:
354 module.exit_json(
355 changed=False,
356 msg=f"template with volid={storage}:{content_type}/{template} already exists",
357 )
358 elif not proxmox.delete_template(node, storage, content_type, template, timeout):
359 module.fail_json(
360 changed=False,
361 msg=f"failed to delete template with volid={storage}:{content_type}/{template}",
362 )
363
364 if checksum and proxmox.fetch_and_verify(
365 node, storage, url, content_type, timeout, checksum, checksum_algorithm, template
366 ):
367 module.exit_json(
368 changed=True,
369 msg=f"Checksum verified, template with volid={storage}:{content_type}/{template} uploaded",
370 )
371 if proxmox.fetch_template(node, storage, content_type, url, timeout, template):
372 module.exit_json(changed=True, msg=f"template with volid={storage}:{content_type}/{template} uploaded")
373
374 elif state == "absent":
375 try:
376 content_type = module.params["content_type"]
377 template = module.params["template"]
378
379 if not proxmox.has_template(node, storage, content_type, template):
380 module.exit_json(
381 changed=False,
382 msg=f"template with volid={storage}:{content_type}/{template} is already deleted",
383 )
384
385 if proxmox.delete_template(node, storage, content_type, template, timeout):
386 module.exit_json(changed=True, msg=f"template with volid={storage}:{content_type}/{template} deleted")
387 except Exception as e:
388 module.fail_json(msg=f"deleting of template {template} failed with exception: {e}")
389
390
391 if __name__ == "__main__":
392 main()