Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2025, Tom Hesse <[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 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: zpool
11 short_description: Manage ZFS zpools
12 version_added: 11.0.0
13 description:
14 - Create, destroy, and modify ZFS zpools and their vdev layouts, pool properties, and filesystem properties.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: partial
20 details:
21 - In check mode, any C(zpool) subcommand that supports the dry-run flag (C(-n)) is run with C(-n) and its simulated
22 output is included in the module's diff results.
23 diff_mode:
24 support: full
25 author:
26 - Tom Hesse (@tomhesse)
27 options:
28 name:
29 description:
30 - Name of the zpool to manage.
31 required: true
32 type: str
33 state:
34 description:
35 - Whether the pool should exist.
36 choices: [present, absent]
37 default: present
38 type: str
39 disable_new_features:
40 description:
41 - If V(true), disable new ZFS feature flags when creating.
42 type: bool
43 default: false
44 force:
45 description:
46 - If V(true), force operations (for example overwrite existing devices).
47 type: bool
48 default: false
49 pool_properties:
50 description:
51 - Dictionary of ZFS pool properties to set (for example V(autoexpand), V(cachefile)).
52 type: dict
53 default: {}
54 filesystem_properties:
55 description:
56 - Dictionary of ZFS filesystem properties to set on the root dataset (for example V(compression), V(dedup)).
57 type: dict
58 default: {}
59 mountpoint:
60 description:
61 - Filesystem mountpoint for the root dataset.
62 type: str
63 altroot:
64 description:
65 - Alternate root for mounting filesystems.
66 type: str
67 temp_name:
68 description:
69 - Temporary name used during pool creation.
70 type: str
71 vdevs:
72 description:
73 - List of vdev definitions for the pool.
74 type: list
75 elements: dict
76 suboptions:
77 role:
78 description:
79 - Special vdev role (for example V(log), V(cache), V(spare)).
80 type: str
81 choices: [log, cache, spare, dedup, special]
82 type:
83 description:
84 - Vdev topology (for example V(stripe), V(mirror), V(raidz)).
85 type: str
86 choices: [stripe, mirror, raidz, raidz1, raidz2, raidz3]
87 default: stripe
88 disks:
89 description:
90 - List of device paths to include in this vdev.
91 required: true
92 type: list
93 elements: path
94 """
95
96 EXAMPLES = r"""
97 - name: Create pool "tank" on /dev/sda
98 community.general.zpool:
99 name: tank
100 vdevs:
101 - disks:
102 - /dev/sda
103
104 - name: Create mirrored pool "tank"
105 community.general.zpool:
106 name: tank
107 vdevs:
108 - type: mirror
109 disks:
110 - /dev/sda
111 - /dev/sdb
112
113 - name: Add a cache device to tank
114 community.general.zpool:
115 name: tank
116 vdevs:
117 - disks:
118 - /dev/sda
119 - role: cache
120 disks:
121 - /dev/nvme0n1
122
123 - name: Set pool and filesystem properties
124 community.general.zpool:
125 name: tank
126 ashift: 12
127 compression: lz4
128 vdevs:
129 - disks:
130 - /dev/sda
131
132 - name: Destroy pool "tank"
133 community.general.zpool:
134 name: tank
135 state: absent
136 """
137
138 import re
139
140 from ansible.module_utils.basic import AnsibleModule
141
142 from ansible_collections.community.general.plugins.module_utils._cmd_runner import CmdRunner, cmd_runner_fmt
143
144
145 class Zpool:
146 def __init__(
147 self,
148 module,
149 name,
150 disable_new_features,
151 force,
152 pool_properties,
153 filesystem_properties,
154 mountpoint,
155 altroot,
156 temp_name,
157 vdevs,
158 ):
159 self.module = module
160 self.name = name
161 self.disable_new_features = disable_new_features
162 self.force = force
163 self.pool_properties = pool_properties
164 self.filesystem_properties = filesystem_properties
165 self.mountpoint = mountpoint
166 self.altroot = altroot
167 self.temp_name = temp_name
168 self.vdevs = vdevs
169 self.zpool_cmd = module.get_bin_path("zpool", required=True)
170 self.zfs_cmd = module.get_bin_path("zfs", required=True)
171 self.changed = False
172
173 self.zpool_runner = CmdRunner(
174 module,
175 command=self.zpool_cmd,
176 arg_formats=dict(
177 subcommand=cmd_runner_fmt.as_list(),
178 disable_new_features=cmd_runner_fmt.as_bool("-d"),
179 force=cmd_runner_fmt.as_bool("-f"),
180 dry_run=cmd_runner_fmt.as_bool("-n"),
181 pool_properties=cmd_runner_fmt.as_func(
182 lambda props: sum([["-o", f"{prop}={value}"] for prop, value in (props or {}).items()], [])
183 ),
184 filesystem_properties=cmd_runner_fmt.as_func(
185 lambda props: sum([["-O", f"{prop}={value}"] for prop, value in (props or {}).items()], [])
186 ),
187 mountpoint=cmd_runner_fmt.as_opt_val("-m"),
188 altroot=cmd_runner_fmt.as_opt_val("-R"),
189 temp_name=cmd_runner_fmt.as_opt_val("-t"),
190 name=cmd_runner_fmt.as_list(),
191 vdevs=cmd_runner_fmt.as_func(
192 lambda vdevs: sum(
193 [
194 ([vdev["role"]] if vdev.get("role") else [])
195 + ([] if vdev.get("type", "stripe") == "stripe" else [vdev["type"]])
196 + vdev.get("disks", [])
197 for vdev in (vdevs or [])
198 ],
199 [],
200 )
201 ),
202 vdev_name=cmd_runner_fmt.as_list(),
203 scripted=cmd_runner_fmt.as_bool("-H"),
204 parsable=cmd_runner_fmt.as_bool("-p"),
205 columns=cmd_runner_fmt.as_opt_val("-o"),
206 properties=cmd_runner_fmt.as_list(),
207 assignment=cmd_runner_fmt.as_list(),
208 full_paths=cmd_runner_fmt.as_bool("-P"),
209 real_paths=cmd_runner_fmt.as_bool("-L"),
210 ),
211 )
212
213 self.zfs_runner = CmdRunner(
214 module,
215 command=self.zfs_cmd,
216 arg_formats=dict(
217 subcommand=cmd_runner_fmt.as_list(),
218 scripted=cmd_runner_fmt.as_bool("-H"),
219 columns=cmd_runner_fmt.as_opt_val("-o"),
220 properties=cmd_runner_fmt.as_list(),
221 assignment=cmd_runner_fmt.as_list(),
222 name=cmd_runner_fmt.as_list(),
223 ),
224 )
225
226 def exists(self):
227 with self.zpool_runner("subcommand name") as ctx:
228 rc, stdout, stderr = ctx.run(subcommand="list", name=self.name)
229 return rc == 0
230
231 def create(self):
232 with self.zpool_runner(
233 "subcommand disable_new_features force dry_run pool_properties filesystem_properties mountpoint altroot temp_name name vdevs",
234 check_rc=True,
235 ) as ctx:
236 rc, stdout, stderr = ctx.run(subcommand="create", dry_run=self.module.check_mode)
237 self.changed = True
238 if self.module.check_mode:
239 return {"prepared": stdout}
240
241 def destroy(self):
242 if self.module.check_mode:
243 self.changed = True
244 return
245 with self.zpool_runner("subcommand name", check_rc=True) as ctx:
246 rc, stdout, stderr = ctx.run(subcommand="destroy")
247 self.changed = True
248
249 def list_pool_properties(self):
250 with self.zpool_runner("subcommand scripted columns properties name", check_rc=True) as ctx:
251 rc, stdout, stderr = ctx.run(
252 subcommand="get",
253 scripted=True,
254 columns="property,value",
255 properties="all",
256 )
257
258 props = {}
259 for line in stdout.splitlines():
260 prop, value = line.split("\t", 1)
261 props[prop] = value
262 return props
263
264 def set_pool_properties_if_changed(self):
265 current = self.list_pool_properties()
266 before = {}
267 after = {}
268 for prop, value in self.pool_properties.items():
269 if current.get(prop) != str(value):
270 before[prop] = current.get(prop)
271 if not self.module.check_mode:
272 with self.zpool_runner("subcommand assignment name", check_rc=True) as ctx:
273 rc, stdout, stderr = ctx.run(subcommand="set", assignment=f"{prop}={value}")
274 after[prop] = str(value)
275 self.changed = True
276 return {"before": {"pool_properties": before}, "after": {"pool_properties": after}}
277
278 def list_filesystem_properties(self):
279 with self.zfs_runner("subcommand scripted columns properties name", check_rc=True) as ctx:
280 rc, stdout, stderr = ctx.run(
281 subcommand="get",
282 scripted=True,
283 columns="property,value",
284 properties="all",
285 )
286
287 props = {}
288 for line in stdout.splitlines():
289 prop, value = line.split("\t", 1)
290 props[prop] = value
291 return props
292
293 def set_filesystem_properties_if_changed(self):
294 current = self.list_filesystem_properties()
295 before = {}
296 after = {}
297 for prop, value in self.filesystem_properties.items():
298 if current.get(prop) != str(value):
299 before[prop] = current.get(prop)
300 if not self.module.check_mode:
301 with self.zfs_runner("subcommand assignment name", check_rc=True) as ctx:
302 rc, stdout, stderr = ctx.run(subcommand="set", assignment=f"{prop}={value}")
303 after[prop] = str(value)
304 self.changed = True
305 return {"before": {"filesystem_properties": before}, "after": {"filesystem_properties": after}}
306
307 def base_device(self, device):
308 if not device.startswith("/dev/"):
309 return device
310
311 # loop devices
312 match = re.match(r"^(/dev/loop\d+)$", device)
313 if match:
314 return match.group(1)
315
316 # nvme drives
317 match = re.match(r"^(.*?)(p\d+)$", device)
318 if match:
319 return match.group(1)
320
321 # sata/scsi drives
322 match = re.match(r"^(/dev/(?:sd|vd)[a-z])\d+$", device)
323 if match:
324 return match.group(1)
325
326 return device
327
328 def get_current_layout(self):
329 with self.zpool_runner("subcommand full_paths real_paths name", check_rc=True) as ctx:
330 rc, stdout, stderr = ctx.run(subcommand="status", full_paths=True, real_paths=True)
331
332 vdevs = []
333 current = None
334 in_config = False
335
336 def flush_current(current):
337 if current:
338 if current.get("role") is None:
339 current.pop("role", None)
340 vdevs.append(current)
341 return None
342
343 for line in stdout.splitlines():
344 if not in_config:
345 if line.strip().startswith("config:"):
346 in_config = True
347 continue
348
349 if not line.strip() or line.strip().startswith("NAME"):
350 continue
351
352 partitions = line.split()
353 device = partitions[0]
354
355 if device == self.name:
356 continue
357
358 if device in ("logs", "cache", "spares"):
359 current = flush_current(current)
360 role = "spare" if device == "spares" else device.rstrip("s")
361 current = {"role": role, "type": None, "disks": []}
362 continue
363
364 match_group = re.match(r"^(mirror|raidz\d?)-\d+$", device)
365 if match_group:
366 if current and current.get("type") is not None:
367 current = flush_current(current)
368 kind = match_group.group(1)
369 role = current.get("role") if current and current.get("type") is None else None
370 current = {"role": role, "type": kind, "disks": []}
371 continue
372
373 if device.startswith("/"):
374 base_device = self.base_device(device)
375 if current:
376 if current.get("type") is None:
377 entry = {"type": "stripe", "disks": [base_device]}
378 if current.get("role"):
379 entry["role"] = current["role"]
380 vdevs.append(entry)
381 current = None
382 else:
383 current["disks"].append(base_device)
384 else:
385 vdevs.append({"type": "stripe", "disks": [base_device]})
386 continue
387
388 if current and current.get("type") is not None:
389 current = flush_current(current)
390
391 return vdevs
392
393 def normalize_vdevs(self, vdevs):
394 alias = {"raidz": "raidz1"}
395 normalized = []
396 for vdev in vdevs:
397 normalized_type = alias.get(vdev.get("type", "stripe"), vdev.get("type", "stripe"))
398 entry = {
399 "type": normalized_type,
400 "disks": sorted(vdev["disks"]),
401 }
402 role = vdev.get("role")
403 if role is not None:
404 entry["role"] = role
405 normalized.append(entry)
406 return sorted(normalized, key=lambda x: (x.get("role", ""), x["type"], x["disks"]))
407
408 def diff_layout(self):
409 current = self.normalize_vdevs(self.get_current_layout())
410 desired = self.normalize_vdevs(self.vdevs)
411
412 before = {"vdevs": current}
413 after = {"vdevs": desired}
414
415 if current != desired:
416 self.changed = True
417
418 return {"before": before, "after": after}
419
420 def add_vdevs(self):
421 invalid_properties = [k for k in self.pool_properties if k != "ashift"]
422 if invalid_properties:
423 self.module.warn(f"zpool add only supports 'ashift', ignoring: {invalid_properties}")
424
425 diff = self.diff_layout()
426 before_vdevs = diff["before"]["vdevs"]
427 after_vdevs = diff["after"]["vdevs"]
428
429 to_add = [vdev for vdev in after_vdevs if vdev not in before_vdevs]
430 if not to_add:
431 return {}
432
433 with self.zpool_runner("subcommand force dry_run pool_properties name vdevs", check_rc=True) as ctx:
434 rc, stdout, stderr = ctx.run(
435 subcommand="add",
436 dry_run=self.module.check_mode,
437 pool_properties={"ashift": self.pool_properties["ashift"]} if "ashift" in self.pool_properties else {},
438 vdevs=to_add,
439 )
440
441 self.changed = True
442 if self.module.check_mode:
443 return {"prepared": stdout}
444
445 def list_vdevs_with_names(self):
446 with self.zpool_runner("subcommand full_paths real_paths name", check_rc=True) as ctx:
447 rc, stdout, stderr = ctx.run(subcommand="status", full_paths=True, real_paths=True)
448 in_cfg = False
449 saw_pool = False
450 vdevs = []
451 current = None
452 for line in stdout.splitlines():
453 if not in_cfg:
454 if line.strip().startswith("config:"):
455 in_cfg = True
456 continue
457 if not line.strip() or line.strip().startswith("NAME"):
458 continue
459 partitions = line.strip().split()
460 device = partitions[0]
461 if not saw_pool:
462 if device == self.name:
463 saw_pool = True
464 continue
465 if re.match(r"^(mirror|raidz\d?)\-\d+$", device) or device in ("cache", "logs", "spares"):
466 if current:
467 vdevs.append(current)
468 vdev_type = (
469 "stripe"
470 if device in ("cache", "logs", "spares")
471 else ("mirror" if device.startswith("mirror") else "raidz")
472 )
473 current = {"name": device, "type": vdev_type, "disks": []}
474 continue
475 if device.startswith("/") and current:
476 current["disks"].append(self.base_device(device))
477 continue
478 if device.startswith("/"):
479 base_device = self.base_device(device)
480 vdevs.append({"name": base_device, "type": "stripe", "disks": [base_device]})
481 if current:
482 vdevs.append(current)
483 return vdevs
484
485 def remove_vdevs(self):
486 current = self.list_vdevs_with_names()
487 current_disks = {disk for vdev in current for disk in vdev["disks"]}
488 desired_disks = {disk for vdev in self.vdevs for disk in vdev.get("disks", [])}
489 gone = current_disks - desired_disks
490 to_remove = [vdev["name"] for vdev in current if any(disk in gone for disk in vdev["disks"])]
491 if not to_remove:
492 return {}
493 with self.zpool_runner("subcommand dry_run name vdev_name", check_rc=True) as ctx:
494 rc, stdout, stderr = ctx.run(subcommand="remove", dry_run=self.module.check_mode, vdev_name=to_remove)
495 self.changed = True
496 if self.module.check_mode:
497 return {"prepared": stdout}
498 before = [vdev["name"] for vdev in current]
499 after = [name for name in before if name not in to_remove]
500 return {"before": {"vdevs": before}, "after": {"vdevs": after}}
501
502
503 def main():
504 module = AnsibleModule(
505 argument_spec=dict(
506 name=dict(type="str", required=True),
507 state=dict(type="str", choices=["present", "absent"], default="present"),
508 disable_new_features=dict(type="bool", default=False),
509 force=dict(type="bool", default=False),
510 pool_properties=dict(type="dict", default={}),
511 filesystem_properties=dict(type="dict", default={}),
512 mountpoint=dict(type="str"),
513 altroot=dict(type="str"),
514 temp_name=dict(type="str"),
515 vdevs=dict(
516 type="list",
517 elements="dict",
518 options=dict(
519 role=dict(
520 type="str",
521 choices=["log", "cache", "spare", "dedup", "special"],
522 ),
523 type=dict(
524 type="str",
525 choices=["stripe", "mirror", "raidz", "raidz1", "raidz2", "raidz3"],
526 default="stripe",
527 ),
528 disks=dict(
529 type="list",
530 elements="path",
531 required=True,
532 ),
533 ),
534 ),
535 ),
536 supports_check_mode=True,
537 required_if=[("state", "present", ["vdevs"])],
538 )
539
540 name = module.params.get("name")
541 state = module.params.get("state")
542 disable_new_features = module.params.get("disable_new_features")
543 force = module.params.get("force")
544 pool_properties = module.params.get("pool_properties")
545 filesystem_properties = module.params.get("filesystem_properties")
546 mountpoint = module.params.get("mountpoint")
547 altroot = module.params.get("altroot")
548 temp_name = module.params.get("temp_name")
549 vdevs = module.params.get("vdevs")
550
551 for property_key in ("pool_properties", "filesystem_properties"):
552 for key, value in list(module.params.get(property_key, {}).items()):
553 if isinstance(value, bool):
554 module.params[property_key][key] = "on" if value else "off"
555
556 if state != "absent":
557 for idx, vdev in enumerate(vdevs, start=1):
558 disks = vdev.get("disks")
559 if not isinstance(disks, list) or len(disks) == 0:
560 module.fail_json(msg=f"vdev #{idx}: at least one disk is required (got: {disks!r})")
561
562 result = dict(
563 name=name,
564 state=state,
565 )
566
567 zpool = Zpool(
568 module,
569 name,
570 disable_new_features,
571 force,
572 pool_properties,
573 filesystem_properties,
574 mountpoint,
575 altroot,
576 temp_name,
577 vdevs,
578 )
579
580 if state == "present":
581 if zpool.exists():
582 vdev_layout_diff = zpool.diff_layout()
583
584 add_vdev_diff = zpool.add_vdevs() or {}
585 remove_vdev_diff = zpool.remove_vdevs() or {}
586 pool_properties_diff = zpool.set_pool_properties_if_changed()
587 filesystem_properties_diff = zpool.set_filesystem_properties_if_changed()
588
589 before = {}
590 after = {}
591 for diff in (vdev_layout_diff, pool_properties_diff, filesystem_properties_diff):
592 before.update(diff.get("before", {}))
593 after.update(diff.get("after", {}))
594
595 result["diff"] = {"before": before, "after": after}
596
597 if module.check_mode:
598 prepared = ""
599 for diff in (add_vdev_diff, remove_vdev_diff):
600 if "prepared" in diff:
601 prepared += diff["prepared"] if not prepared else f"\n{diff['prepared']}"
602 result["diff"]["prepared"] = prepared
603 else:
604 if module.check_mode:
605 result["diff"] = zpool.create()
606 else:
607 before_vdevs = []
608 desired_vdevs = zpool.normalize_vdevs(zpool.vdevs)
609 zpool.create()
610 result["diff"] = {
611 "before": {"state": "absent", "vdevs": before_vdevs},
612 "after": {"state": state, "vdevs": desired_vdevs},
613 }
614
615 elif state == "absent":
616 if zpool.exists():
617 before_vdevs = zpool.get_current_layout()
618 zpool.destroy()
619 result["diff"] = {
620 "before": {"state": "present", "vdevs": before_vdevs},
621 "after": {"state": state, "vdevs": []},
622 }
623 else:
624 result["diff"] = {}
625
626 result["diff"]["before_header"] = name
627 result["diff"]["after_header"] = name
628
629 result["changed"] = zpool.changed
630 module.exit_json(**result)
631
632
633 if __name__ == "__main__":
634 main()