Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Johan Wiren <[email protected]>
4 # Copyright (c) 2017, Ansible Project
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
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: zfs
12 short_description: Manage ZFS
13 description:
14 - Manages ZFS file systems, volumes, clones and snapshots.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: partial
20 details:
21 - In certain situations it may report a task as changed that is not reported as changed when C(check_mode) is disabled.
22 - For example, this might occur when the zpool C(altroot) option is set or when a size is written using human-readable
23 notation, such as V(1M) or V(1024K), instead of as an unqualified byte count, such as V(1048576).
24 diff_mode:
25 support: full
26 options:
27 name:
28 description:
29 - File system, snapshot or volume name, for example V(rpool/myfs).
30 required: true
31 type: str
32 state:
33 description:
34 - Whether to create (V(present)), or remove (V(absent)) a file system, snapshot or volume. All parents/children are
35 created/destroyed as needed to reach the desired state.
36 choices: [absent, present]
37 required: true
38 type: str
39 origin:
40 description:
41 - Snapshot from which to create a clone.
42 type: str
43 extra_zfs_properties:
44 description:
45 - A dictionary of zfs properties to be set.
46 - See the zfs(8) man page for more information.
47 type: dict
48 default: {}
49 author:
50 - Johan Wiren (@johanwiren)
51 """
52
53 EXAMPLES = r"""
54 - name: Create a new file system called myfs in pool rpool with the setuid property turned off
55 community.general.zfs:
56 name: rpool/myfs
57 state: present
58 extra_zfs_properties:
59 setuid: 'off'
60
61 - name: Create a new volume called myvol in pool rpool.
62 community.general.zfs:
63 name: rpool/myvol
64 state: present
65 extra_zfs_properties:
66 volsize: 10M
67
68 - name: Create a snapshot of rpool/myfs file system.
69 community.general.zfs:
70 name: rpool/myfs@mysnapshot
71 state: present
72
73 - name: Create a new file system called myfs2 with snapdir enabled
74 community.general.zfs:
75 name: rpool/myfs2
76 state: present
77 extra_zfs_properties:
78 snapdir: enabled
79
80 - name: Create a new file system by cloning a snapshot
81 community.general.zfs:
82 name: rpool/cloned_fs
83 state: present
84 origin: rpool/myfs@mysnapshot
85
86 - name: Destroy a filesystem
87 community.general.zfs:
88 name: rpool/myfs
89 state: absent
90 """
91
92 import os
93
94 from ansible.module_utils.basic import AnsibleModule
95
96
97 class Zfs:
98 def __init__(self, module, name, extra_zfs_properties):
99 self.module = module
100 self.name = name
101 self.extra_zfs_properties = extra_zfs_properties
102 self.changed = False
103 self.zfs_cmd = module.get_bin_path("zfs", True)
104 self.zpool_cmd = module.get_bin_path("zpool", True)
105 self.pool = name.split("/")[0].split("@")[0]
106 self.is_solaris = os.uname()[0] == "SunOS"
107 self.is_openzfs = self.check_openzfs()
108 self.enhanced_sharing = self.check_enhanced_sharing()
109
110 def check_openzfs(self):
111 cmd = [self.zpool_cmd]
112 cmd.extend(["get", "version"])
113 cmd.append(self.pool)
114 (rc, out, err) = self.module.run_command(cmd, check_rc=True)
115 version = out.splitlines()[-1].split()[2]
116 if version == "-":
117 return True
118 return int(version) == 5000
119
120 def check_enhanced_sharing(self):
121 if self.is_solaris and not self.is_openzfs:
122 cmd = [self.zpool_cmd]
123 cmd.extend(["get", "version"])
124 cmd.append(self.pool)
125 (rc, out, err) = self.module.run_command(cmd, check_rc=True)
126 version = out.splitlines()[-1].split()[2]
127 if int(version) >= 34:
128 return True
129 return False
130
131 def exists(self):
132 cmd = [self.zfs_cmd, "list", "-t", "all", self.name]
133 rc, dummy, dummy = self.module.run_command(cmd)
134 return rc == 0
135
136 def create(self):
137 if self.module.check_mode:
138 self.changed = True
139 return
140 extra_zfs_properties = self.extra_zfs_properties
141 origin = self.module.params.get("origin")
142 cmd = [self.zfs_cmd]
143
144 if "@" in self.name:
145 action = "snapshot"
146 elif origin:
147 action = "clone"
148 else:
149 action = "create"
150
151 cmd.append(action)
152
153 if action in ["create", "clone"]:
154 cmd += ["-p"]
155
156 if extra_zfs_properties:
157 for prop, value in extra_zfs_properties.items():
158 if prop == "volsize":
159 cmd += ["-V", value]
160 elif prop == "volblocksize":
161 cmd += ["-b", value]
162 else:
163 cmd += ["-o", f"{prop}={value}"]
164 if origin and action == "clone":
165 cmd.append(origin)
166 cmd.append(self.name)
167 self.module.run_command(cmd, check_rc=True)
168 self.changed = True
169
170 def destroy(self):
171 if self.module.check_mode:
172 self.changed = True
173 return
174 cmd = [self.zfs_cmd, "destroy", "-R", self.name]
175 self.module.run_command(cmd, check_rc=True)
176 self.changed = True
177
178 def set_property(self, prop, value):
179 if self.module.check_mode:
180 self.changed = True
181 return
182 cmd = [self.zfs_cmd, "set", f"{prop}={value!s}", self.name]
183 self.module.run_command(cmd, check_rc=True)
184
185 def set_properties_if_changed(self):
186 diff = {"before": {"extra_zfs_properties": {}}, "after": {"extra_zfs_properties": {}}}
187 current_properties = self.list_properties()
188 previous_values = {}
189 for prop, value in self.extra_zfs_properties.items():
190 current_value = self.get_property(prop, current_properties)
191 if current_value != value:
192 previous_values[prop] = current_value
193 self.set_property(prop, value)
194 diff["before"]["extra_zfs_properties"][prop] = current_value
195 diff["after"]["extra_zfs_properties"][prop] = value
196 if self.module.check_mode:
197 return diff
198 updated_properties = self.list_properties()
199 for prop in self.extra_zfs_properties:
200 value = self.get_property(prop, updated_properties)
201 if value is None:
202 self.module.fail_json(msg=f"zfsprop was not present after being successfully set: {prop}")
203 if prop in previous_values and previous_values[prop] != value:
204 self.changed = True
205 if prop in diff["after"]["extra_zfs_properties"]:
206 diff["after"]["extra_zfs_properties"][prop] = value
207 return diff
208
209 def list_properties(self):
210 cmd = [self.zfs_cmd, "get", "-H", "-p", "-o", "property,source"]
211 if self.enhanced_sharing:
212 cmd += ["-e"]
213 cmd += ["all", self.name]
214 rc, out, err = self.module.run_command(cmd)
215 properties = []
216 for line in out.splitlines():
217 prop, source = line.split("\t")
218 # include source '-' so that creation-only properties are not removed
219 # to avoids errors when the dataset already exists and the property is not changed
220 # this scenario is most likely when the same playbook is run more than once
221 if source in ("local", "received", "-"):
222 properties.append(prop)
223 return properties
224
225 def get_property(self, name, list_of_properties):
226 # Add alias for enhanced sharing properties
227 if self.enhanced_sharing:
228 if name == "sharenfs":
229 name = "share.nfs"
230 elif name == "sharesmb":
231 name = "share.smb"
232 if name not in list_of_properties:
233 return None
234 cmd = [self.zfs_cmd, "get", "-H", "-p", "-o", "value"]
235 if self.enhanced_sharing:
236 cmd += ["-e"]
237 cmd += [name, self.name]
238 rc, out, err = self.module.run_command(cmd)
239 if rc != 0:
240 return None
241 #
242 # Strip last newline
243 #
244 return out[:-1]
245
246
247 def main():
248 module = AnsibleModule(
249 argument_spec=dict(
250 name=dict(type="str", required=True),
251 state=dict(type="str", required=True, choices=["absent", "present"]),
252 origin=dict(type="str"),
253 extra_zfs_properties=dict(type="dict", default={}),
254 ),
255 supports_check_mode=True,
256 )
257 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
258
259 state = module.params.get("state")
260 name = module.params.get("name")
261
262 if module.params.get("origin") and "@" in name:
263 module.fail_json(msg="cannot specify origin when operating on a snapshot")
264
265 # Reverse the boolification of zfs properties
266 for prop, value in module.params["extra_zfs_properties"].items():
267 if isinstance(value, bool):
268 if value is True:
269 module.params["extra_zfs_properties"][prop] = "on"
270 else:
271 module.params["extra_zfs_properties"][prop] = "off"
272 else:
273 module.params["extra_zfs_properties"][prop] = value
274
275 result = dict(
276 name=name,
277 state=state,
278 )
279
280 zfs = Zfs(module, name, module.params["extra_zfs_properties"])
281
282 if state == "present":
283 if zfs.exists():
284 result["diff"] = zfs.set_properties_if_changed()
285 else:
286 zfs.create()
287 result["diff"] = {"before": {"state": "absent"}, "after": {"state": state}}
288
289 elif state == "absent":
290 if zfs.exists():
291 zfs.destroy()
292 result["diff"] = {"before": {"state": "present"}, "after": {"state": state}}
293 else:
294 result["diff"] = {}
295
296 result["diff"]["before_header"] = name
297 result["diff"]["after_header"] = name
298
299 result.update(zfs.extra_zfs_properties)
300 result["changed"] = zfs.changed
301 module.exit_json(**result)
302
303
304 if __name__ == "__main__":
305 main()