Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Kairo Araujo <[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 author:
11 - Kairo Araujo (@kairoaraujo)
12 module: aix_filesystem
13 short_description: Configure LVM and NFS file systems for AIX
14 description:
15 - This module creates, removes, mount and unmount LVM and NFS file system for AIX using C(/etc/filesystems).
16 - For LVM file systems is possible to resize a file system.
17 deprecated:
18 removed_in: 15.0.0
19 why: The module is not actively maintained.
20 alternative: >-
21 Use C(ibm.power_aix.filesystem) instead.
22 See U(https://ibm.github.io/ansible-power-aix/modules/filesystem.html) for details.
23 extends_documentation_fragment:
24 - community.general._attributes
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: none
30 options:
31 account_subsystem:
32 description:
33 - Specifies whether the file system is to be processed by the accounting subsystem.
34 type: bool
35 default: false
36 attributes:
37 description:
38 - Specifies attributes for files system separated by comma.
39 type: list
40 elements: str
41 default:
42 - agblksize=4096
43 - isnapshot=no
44 auto_mount:
45 description:
46 - File system is automatically mounted at system restart.
47 type: bool
48 default: true
49 device:
50 description:
51 - Logical volume (LV) device name or remote export device to create a NFS file system.
52 - It is used to create a file system on an already existing logical volume or the exported NFS file system.
53 - If not mentioned a new logical volume name is created following AIX standards (LVM).
54 type: str
55 fs_type:
56 description:
57 - Specifies the virtual file system type.
58 type: str
59 default: jfs2
60 permissions:
61 description:
62 - Set file system permissions. V(rw) (read-write) or V(ro) (read-only).
63 type: str
64 choices: [ro, rw]
65 default: rw
66 mount_group:
67 description:
68 - Specifies the mount group.
69 type: str
70 filesystem:
71 description:
72 - Specifies the mount point, which is the directory where the file system will be mounted.
73 type: str
74 required: true
75 nfs_server:
76 description:
77 - Specifies a Network File System (NFS) server.
78 type: str
79 rm_mount_point:
80 description:
81 - Removes the mount point directory when used with state V(absent).
82 type: bool
83 default: false
84 size:
85 description:
86 - Specifies the file system size.
87 - For already present it resizes the filesystem.
88 - 512-byte blocks, megabytes or gigabytes. If the value has M specified it is in megabytes. If the value has G specified
89 it is in gigabytes.
90 - If no M or G the value is 512-byte blocks.
91 - If V(+) is specified in begin of value, the value is added.
92 - If V(-) is specified in begin of value, the value is removed.
93 - If neither V(+) nor V(-) is specified, then the total value is the specified.
94 - Size respects the LVM AIX standards.
95 type: str
96 state:
97 description:
98 - Controls the file system state.
99 - V(present) check if file system exists, creates or resize.
100 - V(absent) removes existing file system if already V(unmounted).
101 - V(mounted) checks if the file system is mounted or mount the file system.
102 - V(unmounted) check if the file system is unmounted or unmount the file system.
103 type: str
104 choices: [absent, mounted, present, unmounted]
105 default: present
106 vg:
107 description:
108 - Specifies an existing volume group (VG).
109 type: str
110 notes:
111 - For more O(attributes), please check C(crfs) AIX manual.
112 """
113
114 EXAMPLES = r"""
115 - name: Create filesystem in a previously defined logical volume.
116 community.general.aix_filesystem:
117 device: testlv
118 filesystem: /testfs
119 state: present
120
121 - name: Creating NFS filesystem from nfshost.
122 community.general.aix_filesystem:
123 device: /home/ftp
124 nfs_server: nfshost
125 filesystem: /home/ftp
126 state: present
127
128 - name: Creating a new file system without a previously logical volume.
129 community.general.aix_filesystem:
130 filesystem: /newfs
131 size: 1G
132 state: present
133 vg: datavg
134
135 - name: Unmounting /testfs.
136 community.general.aix_filesystem:
137 filesystem: /testfs
138 state: unmounted
139
140 - name: Resizing /mksysb to +512M.
141 community.general.aix_filesystem:
142 filesystem: /mksysb
143 size: +512M
144 state: present
145
146 - name: Resizing /mksysb to 11G.
147 community.general.aix_filesystem:
148 filesystem: /mksysb
149 size: 11G
150 state: present
151
152 - name: Resizing /mksysb to -2G.
153 community.general.aix_filesystem:
154 filesystem: /mksysb
155 size: -2G
156 state: present
157
158 - name: Remove NFS filesystem /home/ftp.
159 community.general.aix_filesystem:
160 filesystem: /home/ftp
161 rm_mount_point: true
162 state: absent
163
164 - name: Remove /newfs.
165 community.general.aix_filesystem:
166 filesystem: /newfs
167 rm_mount_point: true
168 state: absent
169 """
170
171
172 import re
173 from os.path import ismount
174
175 from ansible.module_utils.basic import AnsibleModule
176
177
178 def _fs_exists(module, filesystem):
179 """
180 Check if file system already exists on /etc/filesystems.
181
182 :param module: Ansible module.
183 :param community.general.filesystem: filesystem name.
184 :return: True or False.
185 """
186 lsfs_cmd = module.get_bin_path("lsfs", True)
187 rc, lsfs_out, err = module.run_command([lsfs_cmd, "-l", filesystem])
188 if rc == 1:
189 if re.findall("No record matching", err):
190 return False
191
192 else:
193 module.fail_json(msg=f"Failed to run lsfs. Error message: {err}")
194
195 else:
196 return True
197
198
199 def _check_nfs_device(module, nfs_host, device):
200 """
201 Validate if NFS server is exporting the device (remote export).
202
203 :param module: Ansible module.
204 :param nfs_host: nfs_host parameter, NFS server.
205 :param device: device parameter, remote export.
206 :return: True or False.
207 """
208 showmount_cmd = module.get_bin_path("showmount", True)
209 rc, showmount_out, err = module.run_command([showmount_cmd, "-a", nfs_host])
210 if rc != 0:
211 module.fail_json(msg=f"Failed to run showmount. Error message: {err}")
212 else:
213 showmount_data = showmount_out.splitlines()
214 return any(line.split(":")[1] == device for line in showmount_data)
215
216
217 def _validate_vg(module, vg):
218 """
219 Check the current state of volume group.
220
221 :param module: Ansible module argument spec.
222 :param vg: Volume Group name.
223 :return: True (VG in varyon state) or False (VG in varyoff state) or
224 None (VG does not exist), message.
225 """
226 lsvg_cmd = module.get_bin_path("lsvg", True)
227 rc, current_active_vgs, err = module.run_command([lsvg_cmd, "-o"])
228 if rc != 0:
229 module.fail_json(msg=f"Failed executing {lsvg_cmd} command.")
230
231 rc, current_all_vgs, err = module.run_command([lsvg_cmd])
232 if rc != 0:
233 module.fail_json(msg=f"Failed executing {lsvg_cmd} command.")
234
235 if vg in current_all_vgs and vg not in current_active_vgs:
236 msg = f"Volume group {vg} is in varyoff state."
237 return False, msg
238 elif vg in current_active_vgs:
239 msg = f"Volume group {vg} is in varyon state."
240 return True, msg
241 else:
242 msg = f"Volume group {vg} does not exist."
243 return None, msg
244
245
246 def resize_fs(module, filesystem, size):
247 """Resize LVM file system."""
248
249 chfs_cmd = module.get_bin_path("chfs", True)
250 if not module.check_mode:
251 rc, chfs_out, err = module.run_command([chfs_cmd, "-a", f"size={size}", filesystem])
252
253 if rc == 28:
254 changed = False
255 return changed, chfs_out
256 elif rc != 0:
257 if re.findall("Maximum allocation for logical", err):
258 changed = False
259 return changed, err
260 else:
261 module.fail_json(msg=f"Failed to run chfs. Error message: {err}")
262
263 else:
264 if re.findall("The filesystem size is already", chfs_out):
265 changed = False
266 else:
267 changed = True
268
269 return changed, chfs_out
270 else:
271 changed = True
272 msg = ""
273
274 return changed, msg
275
276
277 def create_fs(
278 module,
279 fs_type,
280 filesystem,
281 vg,
282 device,
283 size,
284 mount_group,
285 auto_mount,
286 account_subsystem,
287 permissions,
288 nfs_server,
289 attributes,
290 ):
291 """Create LVM file system or NFS remote mount point."""
292
293 attributes = " -a ".join(attributes)
294
295 # Parameters definition.
296 account_subsys_opt = {True: "-t yes", False: "-t no"}
297
298 if nfs_server is not None:
299 auto_mount_opt = {True: "-A", False: "-a"}
300
301 else:
302 auto_mount_opt = {True: "-A yes", False: "-A no"}
303
304 if size is None:
305 size = ""
306 else:
307 size = f"-a size={size}"
308
309 if device is None:
310 device = ""
311 else:
312 device = f"-d {device}"
313
314 if vg is None:
315 vg = ""
316 else:
317 vg_state, msg = _validate_vg(module, vg)
318 if vg_state:
319 vg = f"-g {vg}"
320 else:
321 changed = False
322
323 return changed, msg
324
325 if mount_group is None:
326 mount_group = ""
327
328 else:
329 mount_group = f"-u {mount_group}"
330
331 auto_mount = auto_mount_opt[auto_mount]
332 account_subsystem = account_subsys_opt[account_subsystem]
333
334 if nfs_server is not None:
335 # Creates a NFS file system.
336 mknfsmnt_cmd = module.get_bin_path("mknfsmnt", True)
337 if not module.check_mode:
338 rc, mknfsmnt_out, err = module.run_command(
339 [mknfsmnt_cmd, "-f", filesystem, device, "-h", nfs_server, "-t", permissions, auto_mount, "-w", "bg"]
340 )
341 if rc != 0:
342 module.fail_json(msg=f"Failed to run mknfsmnt. Error message: {err}")
343 else:
344 changed = True
345 msg = f"NFS file system {filesystem} created."
346
347 return changed, msg
348 else:
349 changed = True
350 msg = ""
351
352 return changed, msg
353
354 else:
355 # Creates a LVM file system.
356 crfs_cmd = module.get_bin_path("crfs", True)
357 if not module.check_mode:
358 cmd = [crfs_cmd]
359
360 cmd.append("-v")
361 cmd.append(fs_type)
362
363 if vg:
364 (flag, value) = vg.split()
365 cmd.append(flag)
366 cmd.append(value)
367
368 if device:
369 (flag, value) = device.split()
370 cmd.append(flag)
371 cmd.append(value)
372
373 cmd.append("-m")
374 cmd.append(filesystem)
375
376 if mount_group:
377 (flag, value) = mount_group.split()
378 cmd.append(flag)
379 cmd.append(value)
380
381 if auto_mount:
382 (flag, value) = auto_mount.split()
383 cmd.append(flag)
384 cmd.append(value)
385
386 if account_subsystem:
387 (flag, value) = account_subsystem.split()
388 cmd.append(flag)
389 cmd.append(value)
390
391 cmd.append("-p")
392 cmd.append(permissions)
393
394 if size:
395 (flag, value) = size.split()
396 cmd.append(flag)
397 cmd.append(value)
398
399 if attributes:
400 splitted_attributes = attributes.split()
401 cmd.append("-a")
402 for value in splitted_attributes:
403 cmd.append(value)
404
405 rc, crfs_out, err = module.run_command(cmd)
406
407 if rc == 10:
408 module.exit_json(
409 msg=f"Using a existent previously defined logical volume, volume group needs to be empty. {err}"
410 )
411
412 elif rc != 0:
413 module.fail_json(msg=f"Failed to run {cmd}. Error message: {err}")
414
415 else:
416 changed = True
417 return changed, crfs_out
418 else:
419 changed = True
420 msg = ""
421
422 return changed, msg
423
424
425 def remove_fs(module, filesystem, rm_mount_point):
426 """Remove an LVM file system or NFS entry."""
427
428 # Command parameters.
429 rm_mount_point_opt = {True: "-r", False: ""}
430
431 rm_mount_point = rm_mount_point_opt[rm_mount_point]
432
433 rmfs_cmd = module.get_bin_path("rmfs", True)
434 if not module.check_mode:
435 cmd = [rmfs_cmd, "-r", rm_mount_point, filesystem]
436 rc, rmfs_out, err = module.run_command(cmd)
437 if rc != 0:
438 module.fail_json(msg=f"Failed to run {cmd}. Error message: {err}")
439 else:
440 changed = True
441 msg = rmfs_out
442 if not rmfs_out:
443 msg = f"File system {filesystem} removed."
444
445 return changed, msg
446 else:
447 changed = True
448 msg = ""
449
450 return changed, msg
451
452
453 def mount_fs(module, filesystem):
454 """Mount a file system."""
455 mount_cmd = module.get_bin_path("mount", True)
456
457 if not module.check_mode:
458 rc, mount_out, err = module.run_command([mount_cmd, filesystem])
459 if rc != 0:
460 module.fail_json(msg=f"Failed to run mount. Error message: {err}")
461 else:
462 changed = True
463 msg = f"File system {filesystem} mounted."
464
465 return changed, msg
466 else:
467 changed = True
468 msg = ""
469
470 return changed, msg
471
472
473 def unmount_fs(module, filesystem):
474 """Unmount a file system."""
475 unmount_cmd = module.get_bin_path("unmount", True)
476
477 if not module.check_mode:
478 rc, unmount_out, err = module.run_command([unmount_cmd, filesystem])
479 if rc != 0:
480 module.fail_json(msg=f"Failed to run unmount. Error message: {err}")
481 else:
482 changed = True
483 msg = f"File system {filesystem} unmounted."
484
485 return changed, msg
486 else:
487 changed = True
488 msg = ""
489
490 return changed, msg
491
492
493 def main():
494 module = AnsibleModule(
495 argument_spec=dict(
496 account_subsystem=dict(type="bool", default=False),
497 attributes=dict(type="list", elements="str", default=["agblksize=4096", "isnapshot=no"]),
498 auto_mount=dict(type="bool", default=True),
499 device=dict(type="str"),
500 filesystem=dict(type="str", required=True),
501 fs_type=dict(type="str", default="jfs2"),
502 permissions=dict(type="str", default="rw", choices=["rw", "ro"]),
503 mount_group=dict(type="str"),
504 nfs_server=dict(type="str"),
505 rm_mount_point=dict(type="bool", default=False),
506 size=dict(type="str"),
507 state=dict(type="str", default="present", choices=["absent", "mounted", "present", "unmounted"]),
508 vg=dict(type="str"),
509 ),
510 supports_check_mode=True,
511 )
512
513 account_subsystem = module.params["account_subsystem"]
514 attributes = module.params["attributes"]
515 auto_mount = module.params["auto_mount"]
516 device = module.params["device"]
517 fs_type = module.params["fs_type"]
518 permissions = module.params["permissions"]
519 mount_group = module.params["mount_group"]
520 filesystem = module.params["filesystem"]
521 nfs_server = module.params["nfs_server"]
522 rm_mount_point = module.params["rm_mount_point"]
523 size = module.params["size"]
524 state = module.params["state"]
525 vg = module.params["vg"]
526
527 result = dict(
528 changed=False,
529 msg="",
530 )
531
532 if state == "present":
533 fs_mounted = ismount(filesystem)
534 fs_exists = _fs_exists(module, filesystem)
535
536 # Check if fs is mounted or exists.
537 if fs_mounted or fs_exists:
538 result["msg"] = f"File system {filesystem} already exists."
539 result["changed"] = False
540
541 # If parameter size was passed, resize fs.
542 if size is not None:
543 result["changed"], result["msg"] = resize_fs(module, filesystem, size)
544
545 # If fs doesn't exist, create it.
546 else:
547 # Check if fs will be a NFS device.
548 if nfs_server is not None:
549 if device is None:
550 result["msg"] = 'Parameter "device" is required when "nfs_server" is defined.'
551 module.fail_json(**result)
552 else:
553 # Create a fs from NFS export.
554 if _check_nfs_device(module, nfs_server, device):
555 result["changed"], result["msg"] = create_fs(
556 module,
557 fs_type,
558 filesystem,
559 vg,
560 device,
561 size,
562 mount_group,
563 auto_mount,
564 account_subsystem,
565 permissions,
566 nfs_server,
567 attributes,
568 )
569
570 if device is None:
571 if vg is None:
572 result["msg"] = 'Required parameter "device" and/or "vg" is missing for filesystem creation.'
573 module.fail_json(**result)
574 else:
575 # Create a fs from
576 result["changed"], result["msg"] = create_fs(
577 module,
578 fs_type,
579 filesystem,
580 vg,
581 device,
582 size,
583 mount_group,
584 auto_mount,
585 account_subsystem,
586 permissions,
587 nfs_server,
588 attributes,
589 )
590
591 if device is not None and nfs_server is None:
592 # Create a fs from a previously lv device.
593 result["changed"], result["msg"] = create_fs(
594 module,
595 fs_type,
596 filesystem,
597 vg,
598 device,
599 size,
600 mount_group,
601 auto_mount,
602 account_subsystem,
603 permissions,
604 nfs_server,
605 attributes,
606 )
607
608 elif state == "absent":
609 if ismount(filesystem):
610 result["msg"] = f"File system {filesystem} mounted."
611
612 else:
613 fs_status = _fs_exists(module, filesystem)
614 if not fs_status:
615 result["msg"] = f"File system {filesystem} does not exist."
616 else:
617 result["changed"], result["msg"] = remove_fs(module, filesystem, rm_mount_point)
618
619 elif state == "mounted":
620 if ismount(filesystem):
621 result["changed"] = False
622 result["msg"] = f"File system {filesystem} already mounted."
623 else:
624 result["changed"], result["msg"] = mount_fs(module, filesystem)
625
626 elif state == "unmounted":
627 if not ismount(filesystem):
628 result["changed"] = False
629 result["msg"] = f"File system {filesystem} already unmounted."
630 else:
631 result["changed"], result["msg"] = unmount_fs(module, filesystem)
632
633 else:
634 # Unreachable codeblock
635 result["msg"] = f"Unexpected state {state}."
636 module.fail_json(**result)
637
638 module.exit_json(**result)
639
640
641 if __name__ == "__main__":
642 main()