Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2025, Florian Paul Azim Hoberg (@gyptazy) <[email protected]>
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_storage
10 version_added: 1.3.0
11 short_description: Manage storage in PVE clusters and nodes
12 description:
13 - Manage storage in PVE clusters and nodes.
14 author: Florian Paul Azim Hoberg (@gyptazy)
15 attributes:
16 check_mode:
17 support: full
18 diff_mode:
19 support: none
20 options:
21 name:
22 description:
23 - The name of the storage displayed in the storage list.
24 type: str
25 required: true
26 state:
27 description:
28 - The state of the defined storage type to perform.
29 choices: ["present", "absent"]
30 type: str
31 default: present
32 type:
33 description:
34 - The storage type/protocol to use when adding the storage.
35 choices: ['cephfs', 'cifs', 'dir', 'iscsi', 'nfs', 'pbs', 'rbd', 'zfspool']
36 type: str
37 required: true
38 nodes:
39 description:
40 - A list of nodes where this storage is available.
41 - Required when C(state=present).
42 type: list
43 elements: str
44 content:
45 description:
46 - The content types that can be stored on this storage.
47 - V(backup) VM backups.
48 - V(images) VM disk images.
49 - V(import) VM disk images for import.
50 - V(iso) ISO images.
51 - V(rootdir) container root directories.
52 - V(snippets) cloud-init, hook scripts, etc.
53 - V(vztmpl) container templates.
54 type: list
55 elements: str
56 choices: ["backup", "images", "import", "iso", "rootdir", "snippets", "vztmpl"]
57 cephfs_options:
58 description:
59 - Extended information for adding CephFS storage.
60 type: dict
61 suboptions:
62 path:
63 description:
64 - The path to be used within the CephFS.
65 default: '/'
66 type: str
67 monhost:
68 description:
69 - The hostname or IP address of the monhost.
70 type: list
71 elements: str
72 subdir:
73 description:
74 - The subdir to be used within the CephFS.
75 - The Proxmox default is '/'.
76 type: str
77 username:
78 description:
79 - The username for the storage system.
80 type: str
81 password:
82 description:
83 - The password for the storage system.
84 type: str
85 client_keyring:
86 description:
87 - The client keyring to be used.
88 type: str
89 fs_name:
90 description:
91 - The Ceph filesystem name
92 type: str
93 cifs_options:
94 description:
95 - Extended information for adding CIFS storage.
96 type: dict
97 suboptions:
98 server:
99 description:
100 - The required hostname or IP address of the remote storage system.
101 type: str
102 required: true
103 share:
104 description:
105 - The required share to be used from the remote storage system.
106 type: str
107 required: true
108 username:
109 description:
110 - The required username for the storage system.
111 type: str
112 required: true
113 password:
114 description:
115 - The required password for the storage system.
116 type: str
117 required: true
118 domain:
119 description:
120 - The required domain for the CIFS share.
121 type: str
122 subdir:
123 description:
124 - The subdir to be used within the CIFS.
125 aliases: ["subdirectory"]
126 type: str
127 smb_version:
128 description:
129 - The minimum SMB version to use for.
130 type: str
131 snapshot_as_volume_chain:
132 description:
133 - Enable support for creating snapshots through volume backing-chains.
134 type: bool
135 preallocation:
136 description:
137 - The preallocation mode for raw and qcow2 images.
138 type: str
139 dir_options:
140 description:
141 - Extended information for adding Directory storage.
142 type: dict
143 suboptions:
144 path:
145 description:
146 - The required path of the direcotry on the node(s).
147 type: str
148 required: true
149 iscsi_options:
150 description:
151 - Extended information for adding iSCSI storage.
152 type: dict
153 suboptions:
154 portal:
155 description:
156 - The required hostname or IP address of the remote storage system as the portal address.
157 type: str
158 required: true
159 target:
160 description:
161 - The required iSCSI target.
162 type: str
163 required: true
164 nfs_options:
165 description:
166 - Extended information for adding NFS storage.
167 type: dict
168 suboptions:
169 server:
170 description:
171 - The required IP address or DNS name of the NFS server.
172 type: str
173 required: true
174 export:
175 description:
176 - The required path of the NFS export.
177 type: str
178 required: true
179 options:
180 description:
181 - The options to pass to the NFS service. (e.g., version, pNFS).
182 type: str
183 preallocation:
184 description:
185 - The preallocation mode for raw and qcow2 images.
186 type: str
187 pbs_options:
188 description:
189 - Extended information for adding Proxmox Backup Server as storage.
190 type: dict
191 suboptions:
192 server:
193 description:
194 - The hostname or IP address of the Proxmox Backup Server.
195 type: str
196 required: true
197 datastore:
198 description:
199 - The required datastore to use from the Proxmox Backup Server.
200 type: str
201 required: true
202 username:
203 description:
204 - The required username for the Proxmox Backup Server.
205 type: str
206 required: true
207 password:
208 description:
209 - The required password for the Proxmox Backup Server.
210 type: str
211 required: true
212 namespace:
213 description:
214 - The namespace to use from the Proxmox Backup Server.
215 type: str
216 fingerprint:
217 description:
218 - The fingerprint of the Proxmox Backup Server system.
219 type: str
220 encryption_key:
221 description:
222 - An existing encryption key for the datastore.
223 - Use V(autogen) to generate one automatically without passphrase.
224 - Must be provided as a JSON-encoded string.
225 type: str
226 rbd_options:
227 description:
228 - Extended information for adding RBD storage.
229 type: dict
230 suboptions:
231 pool:
232 description:
233 - The required RBD pool name.
234 type: str
235 required: false
236 zfspool_options:
237 description:
238 - Extended information for adding ZFS storage.
239 type: dict
240 suboptions:
241 pool:
242 description:
243 - The required name of the ZFS pool to use.
244 type: str
245 required: true
246 sparse:
247 description:
248 - Use ZFS thin-provisioning.
249 type: bool
250 extends_documentation_fragment:
251 - community.proxmox.proxmox.actiongroup_proxmox
252 - community.proxmox.proxmox.documentation
253 - community.proxmox.attributes
254 """
255
256 EXAMPLES = r"""
257 - name: Add PBS storage to Proxmox VE Cluster
258 community.proxmox.proxmox_storage:
259 nodes: ["de-cgn01-virt01", "de-cgn01-virt02"]
260 state: present
261 name: backup-backupserver01
262 type: pbs
263 pbs_options:
264 server: proxmox-backup-server.example.com
265 username: backup@pbs
266 password: password123
267 datastore: backup
268 fingerprint: "F3:04:D2:C1:33:B7:35:B9:88:D8:7A:24:85:21:DC:75:EE:7C:A5:2A:55:2D:99:38:6B:48:5E:CA:0D:E3:FE:66"
269 export: "/mnt/storage01/b01pbs01"
270 content: ["backup"]
271
272 - name: Add NFS storage to Proxmox VE Cluster
273 community.proxmox.proxmox_storage:
274 nodes: ["de-cgn01-virt01", "de-cgn01-virt02"]
275 state: present
276 name: net-nfsshare01
277 type: nfs
278 nfs_options:
279 server: 10.10.10.94
280 export: "/mnt/storage01/s01nfs01"
281 content: ["rootdir", "images"]
282
283 - name: Add iSCSI storage to Proxmox VE Cluster
284 community.proxmox.proxmox_storage:
285 nodes: ["de-cgn01-virt01", "de-cgn01-virt02", "de-cgn01-virt03"]
286 state: present
287 type: iscsi
288 name: net-iscsi01
289 iscsi_options:
290 portal: 10.10.10.94
291 target: "iqn.2005-10.org.freenas.ctl:s01-isci01"
292 content: ["rootdir", "images"]
293
294 - name: Remove storage from Proxmox VE Cluster
295 community.proxmox.proxmox_storage:
296 state: absent
297 name: net-nfsshare01
298 type: nfs
299
300 - name: Add ZFS storage to Proxmox VE Cluster
301 community.proxmox.proxmox_storage:
302 state: present
303 name: zfspool-storage
304 type: zfspool
305 content: ["rootdir", "images"]
306 zfspool_options:
307 pool: rpool/data
308 sparse: true
309 """
310
311 RETURN = r"""
312 storage:
313 description: Status message about the storage action.
314 returned: success
315 type: str
316 sample: "Storage 'net-nfsshare01' created successfully."
317 """
318
319
320 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
321 ProxmoxAnsible,
322 ansible_to_proxmox_bool,
323 create_proxmox_module,
324 is_not_found_error,
325 )
326
327 STORAGE_BACKENDS = {
328 "cephfs": {
329 "path": ("path", False),
330 "monhost": ("monhost", False),
331 "subdir": ("subdir", False),
332 "username": ("username", False),
333 "password": ("password", False),
334 "client_keyring": ("keyring", False),
335 "fs_name": ("fs-name", False),
336 },
337 "cifs": {
338 "server": ("server", True),
339 "share": ("share", True),
340 "username": ("username", True),
341 "password": ("password", True),
342 "domain": ("domain", False),
343 "subdir": ("subdir", False),
344 "smb_version": ("smbversion", False),
345 "snapshot_as_volume_chain": ("snapshot-as-volume-chain", False),
346 "preallocation": ("preallocation", False),
347 },
348 "dir": {"path": ("path", True)},
349 "iscsi": {"portal": ("portal", True), "target": ("target", True)},
350 "nfs": {
351 "server": ("server", True),
352 "export": ("export", True),
353 "options": ("options", False),
354 "preallocation": ("preallocation", False),
355 },
356 "pbs": {
357 "server": ("server", True),
358 "datastore": ("datastore", True),
359 "username": ("username", True),
360 "password": ("password", True),
361 "namespace": ("namespace", False),
362 "fingerprint": ("fingerprint", False),
363 "encryption_key": ("encryption-key", False),
364 },
365 "rbd": {
366 "pool": ("pool", True),
367 },
368 "zfspool": {
369 "pool": ("pool", True),
370 "sparse": ("sparse", False),
371 },
372 }
373
374
375 def module_args():
376 return dict(
377 name=dict(type="str", required=True),
378 state=dict(type="str", choices=["present", "absent"], default="present"),
379 type=dict(
380 type="str", choices=["cephfs", "cifs", "dir", "iscsi", "nfs", "pbs", "rbd", "zfspool"], required=True
381 ),
382 content=dict(
383 type="list", elements="str", choices=["backup", "images", "import", "iso", "rootdir", "snippets", "vztmpl"]
384 ),
385 nodes=dict(
386 type="list",
387 elements="str",
388 ),
389 cephfs_options=dict(
390 type="dict",
391 options={
392 "monhost": dict(type="list", elements="str"),
393 "username": dict(type="str"),
394 "password": dict(type="str", no_log=True),
395 "path": dict(type="str", default="/"),
396 "subdir": dict(type="str"),
397 "fs_name": dict(type="str"),
398 "client_keyring": dict(type="str", no_log=True),
399 },
400 ),
401 cifs_options=dict(
402 type="dict",
403 options={
404 "server": dict(type="str", required=True),
405 "share": dict(type="str", required=True),
406 "username": dict(type="str", required=True),
407 "password": dict(type="str", no_log=True, required=True),
408 "domain": dict(type="str"),
409 "subdir": dict(type="str", aliases=["subdirectory"]),
410 "smb_version": dict(type="str"),
411 "snapshot_as_volume_chain": dict(type="bool"),
412 "preallocation": dict(type="str"),
413 },
414 ),
415 dir_options=dict(
416 type="dict",
417 options={"path": dict(type="str", required=True)},
418 ),
419 iscsi_options=dict(
420 type="dict",
421 options={"portal": dict(type="str", required=True), "target": dict(type="str", required=True)},
422 ),
423 nfs_options=dict(
424 type="dict",
425 options={
426 "server": dict(type="str", required=True),
427 "export": dict(type="str", required=True),
428 "options": dict(type="str"),
429 "preallocation": dict(type="str"),
430 },
431 ),
432 pbs_options=dict(
433 type="dict",
434 options={
435 "server": dict(type="str", required=True),
436 "username": dict(type="str", required=True),
437 "password": dict(type="str", required=True, no_log=True),
438 "datastore": dict(type="str", required=True),
439 "namespace": dict(type="str"),
440 "fingerprint": dict(type="str"),
441 "encryption_key": dict(type="str", no_log=True),
442 },
443 ),
444 rbd_options=dict(type="dict", options={"pool": dict(type="str")}),
445 zfspool_options=dict(
446 type="dict",
447 options={
448 "pool": dict(type="str", required=True),
449 "sparse": dict(type="bool"),
450 },
451 ),
452 )
453
454
455 def module_options():
456 return {}
457
458
459 class ProxmoxNodeAnsible(ProxmoxAnsible):
460 def __init__(self, module):
461 super().__init__(module)
462 self.params = module.params
463
464 def _get_storage(self, storage_name):
465 try:
466 return self.proxmox_api.storage.get(storage_name)
467 except Exception as e:
468 if is_not_found_error(e):
469 return None
470 self.module.fail_json(msg=f"Failed to retrieve storage {storage_name}: {e}")
471
472 def _validate_storage_params(self, storage_type, params):
473 backend = STORAGE_BACKENDS.get(storage_type, {})
474 missing_required = []
475 for ansible_key, (_proxmox_key, required) in backend.items():
476 value = params.get(ansible_key)
477 if value is None and required:
478 missing_required.append(ansible_key)
479 if missing_required:
480 self.module.fail_json(
481 msg=f"{storage_type} storage is missing required option(s): {', '.join(missing_required)}"
482 )
483
484 def _normalize_storage_params(self, storage_type, backend_params):
485 backend = STORAGE_BACKENDS.get(storage_type, {})
486 result = {}
487 for ansible_key, (proxmox_key, _required) in backend.items():
488 value = backend_params.get(ansible_key)
489 if value is not None:
490 normalized = ansible_to_proxmox_bool(value) if isinstance(value, bool) else value
491 result[proxmox_key] = normalized
492 return result
493
494 def run(self):
495 state = self.params.get("state")
496
497 storage_params = {
498 "storage": self.params.get("name"),
499 "type": self.params.get("type"),
500 }
501
502 if self.params.get("nodes") is not None:
503 storage_params["nodes"] = self.params.get("nodes")
504 if self.params.get("content") is not None:
505 storage_params["content"] = self.params.get("content")
506
507 storage_type = self.params.get("type")
508 storage_backend_params = self.params.get(f"{storage_type}_options") or {}
509
510 if state == "present":
511 self._validate_storage_params(storage_type, storage_backend_params)
512 storage_params.update(self._normalize_storage_params(storage_type, storage_backend_params))
513 self.add_storage(storage_params)
514 elif state == "absent":
515 self.remove_storage(storage_params)
516
517 def add_storage(self, storage_params):
518 name = storage_params["storage"]
519
520 if self.module.check_mode:
521 current_storage = self._get_storage(name)
522 if current_storage:
523 self.module.exit_json(changed=False, msg=f"Storage '{name}' already present.")
524 self.module.exit_json(changed=True, msg=f"Storage '{name}' would be created.")
525
526 try:
527 self.proxmox_api.storage.post(**storage_params)
528 self.module.exit_json(changed=True, msg=f"Storage '{name}' created successfully.")
529 except Exception as e:
530 error_msg = str(e)
531 if "already defined" in error_msg:
532 self.module.exit_json(changed=False, msg=f"Storage '{name}' already present.")
533 self.module.fail_json(msg=f"Failed to create storage: {error_msg}")
534
535 def remove_storage(self, storage_params):
536 name = storage_params["storage"]
537
538 if self.module.check_mode:
539 current_storage = self._get_storage(name)
540 if current_storage:
541 self.module.exit_json(changed=True, msg=f"Storage '{name}' would be deleted.")
542 self.module.exit_json(changed=False, msg=f"Storage '{name}' does not exist.")
543
544 current_storage = self._get_storage(name)
545 if not current_storage:
546 self.module.exit_json(changed=False, msg=f"Storage '{name}' does not exist.")
547
548 try:
549 self.proxmox_api.storage(name).delete()
550 self.module.exit_json(changed=True, msg=f"Storage '{name}' removed successfully.")
551 except Exception as e:
552 self.module.fail_json(msg=f"Failed to delete storage '{name}': {e}")
553
554
555 def main():
556 module = create_proxmox_module(module_args(), **module_options())
557 proxmox = ProxmoxNodeAnsible(module)
558
559 proxmox.run()
560
561
562 if __name__ == "__main__":
563 main()