Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2025, Klention Mali <[email protected]>
4 # Based on lvol module by Jeroen Hoekx <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: lvm_pv
11 short_description: Manage LVM Physical Volumes
12 version_added: "11.0.0"
13 description:
14 - Creates, resizes or removes LVM Physical Volumes.
15 author:
16 - Klention Mali (@klention)
17 options:
18 device:
19 description:
20 - Path to the block device to manage.
21 type: path
22 required: true
23 state:
24 description:
25 - Control if the physical volume exists.
26 type: str
27 choices: [present, absent]
28 default: present
29 force:
30 description:
31 - Force the operation.
32 - When O(state=present) (creating a PV), this uses C(pvcreate -f) to force creation.
33 - When O(state=absent) (removing a PV), this uses C(pvremove -ff) to force removal even if part of a volume group.
34 type: bool
35 default: false
36 resize:
37 description:
38 - Resize PV to device size when O(state=present).
39 type: bool
40 default: false
41 notes:
42 - Requires LVM2 utilities installed on the target system.
43 - Device path must exist when creating a PV.
44 """
45
46 EXAMPLES = r"""
47 - name: Creating physical volume on /dev/sdb
48 community.general.lvm_pv:
49 device: /dev/sdb
50
51 - name: Creating and resizing (if needed) physical volume
52 community.general.lvm_pv:
53 device: /dev/sdb
54 resize: true
55
56 - name: Removing physical volume that is not part of any volume group
57 community.general.lvm_pv:
58 device: /dev/sdb
59 state: absent
60
61 - name: Force removing physical volume that is already part of a volume group
62 community.general.lvm_pv:
63 device: /dev/sdb
64 force: true
65 state: absent
66 """
67
68 RETURN = r"""
69 """
70
71
72 import os
73
74 from ansible.module_utils.basic import AnsibleModule
75
76 from ansible_collections.community.general.plugins.module_utils._lvm import (
77 pvcreate_runner,
78 pvremove_runner,
79 pvresize_runner,
80 pvs_runner,
81 )
82
83
84 def rescan_device(module, device):
85 """Perform storage rescan for the device."""
86 base_device = os.path.basename(device)
87 is_partition = f"/sys/class/block/{base_device}/partition"
88
89 # Determine parent device if partition exists
90 parent_device = base_device
91 if os.path.exists(is_partition):
92 parent_device = (
93 base_device.rpartition("p")[0] if base_device.startswith("nvme") else base_device.rstrip("0123456789")
94 )
95
96 # Determine rescan path
97 rescan_path = (
98 f"/sys/block/{parent_device}/device/{'rescan_controller' if base_device.startswith('nvme') else 'rescan'}"
99 )
100
101 if os.path.exists(rescan_path):
102 try:
103 with open(rescan_path, "w") as f:
104 f.write("1")
105 return True
106 except OSError as e:
107 module.warn(f"Failed to rescan device {device}: {e!s}")
108 else:
109 module.warn(f"Rescan path does not exist for device {device}")
110 return False
111
112
113 def main():
114 module = AnsibleModule(
115 argument_spec=dict(
116 device=dict(type="path", required=True),
117 state=dict(type="str", default="present", choices=["present", "absent"]),
118 force=dict(type="bool", default=False),
119 resize=dict(type="bool", default=False),
120 ),
121 supports_check_mode=True,
122 )
123
124 device = module.params["device"]
125 state = module.params["state"]
126 resize = module.params["resize"]
127 changed = False
128 actions = []
129
130 pvs = pvs_runner(module)
131 pvcreate = pvcreate_runner(module)
132 pvresize = pvresize_runner(module)
133 pvremove = pvremove_runner(module)
134
135 def get_pv_status():
136 with pvs("noheadings readonly devices", check_rc=False) as ctx:
137 rc, dummy, dummy = ctx.run(devices=[device])
138 return rc == 0
139
140 def get_pv_size():
141 with pvs("noheadings nosuffix readonly units fields devices") as ctx:
142 dummy, out, dummy = ctx.run(units="b", fields="pv_size", devices=[device])
143 return int(out.strip())
144
145 # Validate device existence for present state
146 if state == "present" and not os.path.exists(device):
147 module.fail_json(msg=f"Device {device} not found")
148
149 is_pv = get_pv_status()
150
151 if state == "present":
152 # Create PV if needed
153 if not is_pv:
154 if module.check_mode:
155 changed = True
156 actions.append("would be created")
157 else:
158 pvcreate("force device", check_rc=True).run()
159 changed = True
160 actions.append("created")
161 is_pv = True
162
163 # Handle resizing
164 elif resize and is_pv:
165 if module.check_mode:
166 # In check mode, assume resize would change
167 changed = True
168 actions.append("would be resized")
169 else:
170 # Perform device rescan each time
171 if rescan_device(module, device):
172 actions.append("rescanned")
173 original_size = get_pv_size()
174 pvresize("device", check_rc=True).run()
175 new_size = get_pv_size()
176 if new_size != original_size:
177 changed = True
178 actions.append("resized")
179
180 elif state == "absent":
181 if is_pv:
182 if module.check_mode:
183 changed = True
184 actions.append("would be removed")
185 else:
186 pvremove("force device", check_rc=True).run()
187 changed = True
188 actions.append("removed")
189
190 # Generate final message
191 if actions:
192 msg = f"PV {device}: {', '.join(actions)}"
193 else:
194 msg = f"No changes needed for PV {device}"
195 module.exit_json(changed=changed, msg=msg)
196
197
198 if __name__ == "__main__":
199 main()