Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2015, Nate Coraor <[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: zfs_delegate_admin
11 short_description: Manage ZFS delegated administration (user admin privileges)
12 description:
13 - Manages ZFS file system delegated administration permissions, which allow unprivileged users to perform ZFS operations
14 normally restricted to the superuser.
15 - See the C(zfs allow) section of V(zfs(1M\)) for detailed explanations of options.
16 - This module attempts to adhere to the behavior of the command line tool as much as possible.
17 requirements:
18 - "A ZFS/OpenZFS implementation that supports delegation with C(zfs allow), including: Solaris >= 10, illumos (all versions),
19 FreeBSD >= 8.0R, ZFS on Linux >= 0.7.0."
20 extends_documentation_fragment:
21 - community.general._attributes
22 attributes:
23 check_mode:
24 support: none
25 diff_mode:
26 support: none
27 options:
28 name:
29 description:
30 - File system or volume name, for example V(rpool/myfs).
31 required: true
32 type: str
33 state:
34 description:
35 - Whether to allow (V(present)), or unallow (V(absent)) a permission.
36 - When set to V(present), at least one "entity" param of O(users), O(groups), or O(everyone) are required.
37 - When set to V(absent), removes permissions from the specified entities, or removes all permissions if no entity params
38 are specified.
39 choices: [absent, present]
40 default: present
41 type: str
42 users:
43 description:
44 - List of users to whom permission(s) should be granted.
45 type: list
46 elements: str
47 groups:
48 description:
49 - List of groups to whom permission(s) should be granted.
50 type: list
51 elements: str
52 everyone:
53 description:
54 - Apply permissions to everyone.
55 type: bool
56 default: false
57 permissions:
58 description:
59 - The list of permission(s) to delegate (required if O(state=present)).
60 - Supported permissions depend on the ZFS version in use. See for example U(https://openzfs.github.io/openzfs-docs/man/8/zfs-allow.8.html)
61 for OpenZFS.
62 type: list
63 elements: str
64 local:
65 description:
66 - Apply permissions to O(name) locally (C(zfs allow -l)).
67 type: bool
68 descendents:
69 description:
70 - Apply permissions to O(name)'s descendents (C(zfs allow -d)).
71 type: bool
72 recursive:
73 description:
74 - Unallow permissions recursively (ignored when O(state=present)).
75 type: bool
76 default: false
77 author:
78 - Nate Coraor (@natefoo)
79 """
80
81 EXAMPLES = r"""
82 - name: Grant `zfs allow` and `unallow` permission to the `adm` user with the default local+descendents scope
83 community.general.zfs_delegate_admin:
84 name: rpool/myfs
85 users: adm
86 permissions: allow,unallow
87
88 - name: Grant `zfs send` to everyone, plus the group `backup`
89 community.general.zfs_delegate_admin:
90 name: rpool/myvol
91 groups: backup
92 everyone: true
93 permissions: send
94
95 - name: Grant `zfs send,receive` to users `foo` and `bar` with local scope only
96 community.general.zfs_delegate_admin:
97 name: rpool/myfs
98 users: foo,bar
99 permissions: send,receive
100 local: true
101
102 - name: Revoke all permissions from everyone (permissions specifically assigned to users and groups remain)
103 community.general.zfs_delegate_admin:
104 name: rpool/myfs
105 everyone: true
106 state: absent
107 """
108
109 # This module does not return anything other than the standard
110 # changed/state/msg/stdout
111 RETURN = r"""
112 """
113
114 from itertools import product
115
116 from ansible.module_utils.basic import AnsibleModule
117
118
119 class ZfsDelegateAdmin:
120 def __init__(self, module):
121 self.module = module
122 self.name = module.params.get("name")
123 self.state = module.params.get("state")
124 self.users = module.params.get("users")
125 self.groups = module.params.get("groups")
126 self.everyone = module.params.get("everyone")
127 self.perms = module.params.get("permissions")
128 self.scope = None
129 self.changed = False
130 self.initial_perms = None
131 self.subcommand = "allow"
132 self.recursive_opt = []
133 self.run_method = self.update
134
135 self.setup(module)
136
137 def setup(self, module):
138 """Validate params and set up for run."""
139 if self.state == "absent":
140 self.subcommand = "unallow"
141 if module.params.get("recursive"):
142 self.recursive_opt = ["-r"]
143
144 local = module.params.get("local")
145 descendents = module.params.get("descendents")
146 if (local and descendents) or (not local and not descendents):
147 self.scope = "ld"
148 elif local:
149 self.scope = "l"
150 elif descendents:
151 self.scope = "d"
152 else:
153 self.module.fail_json(msg="Impossible value for local and descendents")
154
155 if not (self.users or self.groups or self.everyone):
156 if self.state == "present":
157 self.module.fail_json(msg="One of `users`, `groups`, or `everyone` must be set")
158 elif self.state == "absent":
159 self.run_method = self.clear
160 # ansible ensures the else cannot happen here
161
162 self.zfs_path = module.get_bin_path("zfs", True)
163
164 @property
165 def current_perms(self):
166 """Parse the output of `zfs allow <name>` to retrieve current permissions."""
167 out = self.run_zfs_raw(subcommand="allow")
168 perms = {
169 "l": {"u": {}, "g": {}, "e": []},
170 "d": {"u": {}, "g": {}, "e": []},
171 "ld": {"u": {}, "g": {}, "e": []},
172 }
173 linemap = {
174 "Local permissions:": "l",
175 "Descendent permissions:": "d",
176 "Local+Descendent permissions:": "ld",
177 }
178 scope = None
179 for line in out.splitlines():
180 scope = linemap.get(line, scope)
181 if not scope:
182 continue
183 if " (unknown: " in line:
184 line = line.replace("(unknown: ", "", 1)
185 line = line.replace(")", "", 1)
186 try:
187 if line.startswith("\tuser ") or line.startswith("\tgroup "):
188 ent_type, ent, cur_perms = line.split()
189 perms[scope][ent_type[0]][ent] = cur_perms.split(",")
190 elif line.startswith("\teveryone "):
191 perms[scope]["e"] = line.split()[1].split(",")
192 except ValueError:
193 self.module.fail_json(msg=f"Cannot parse user/group permission output by `zfs allow`: '{line}'")
194 return perms
195
196 def run_zfs_raw(self, subcommand=None, args=None):
197 """Run a raw zfs command, fail on error."""
198 cmd = [self.zfs_path, subcommand or self.subcommand] + (args or []) + [self.name]
199 rc, out, err = self.module.run_command(cmd)
200 if rc:
201 self.module.fail_json(msg=f"Command `{' '.join(cmd)}` failed: {err}")
202 return out
203
204 def run_zfs(self, args):
205 """Run zfs allow/unallow with appropriate options as per module arguments."""
206 args = self.recursive_opt + [f"-{self.scope}"] + args
207 if self.perms:
208 args.append(",".join(self.perms))
209 return self.run_zfs_raw(args=args)
210
211 def clear(self):
212 """Called by run() to clear all permissions."""
213 changed = False
214 stdout = ""
215 for scope, ent_type in product(("ld", "l", "d"), ("u", "g")):
216 for ent in self.initial_perms[scope][ent_type].keys():
217 stdout += self.run_zfs([f"-{ent_type}", ent])
218 changed = True
219 for scope in ("ld", "l", "d"):
220 if self.initial_perms[scope]["e"]:
221 stdout += self.run_zfs(["-e"])
222 changed = True
223 return (changed, stdout)
224
225 def update(self):
226 """Update permissions as per module arguments."""
227 stdout = ""
228 for ent_type, entities in (("u", self.users), ("g", self.groups)):
229 if entities:
230 stdout += self.run_zfs([f"-{ent_type}", ",".join(entities)])
231 if self.everyone:
232 stdout += self.run_zfs(["-e"])
233 return (self.initial_perms != self.current_perms, stdout)
234
235 def run(self):
236 """Run an operation, return results for Ansible."""
237 exit_args = {"state": self.state}
238 self.initial_perms = self.current_perms
239 exit_args["changed"], stdout = self.run_method()
240 if exit_args["changed"]:
241 exit_args["msg"] = "ZFS delegated admin permissions updated"
242 exit_args["stdout"] = stdout
243 self.module.exit_json(**exit_args)
244
245
246 def main():
247 module = AnsibleModule(
248 argument_spec=dict(
249 name=dict(type="str", required=True),
250 state=dict(type="str", default="present", choices=["absent", "present"]),
251 users=dict(type="list", elements="str"),
252 groups=dict(type="list", elements="str"),
253 everyone=dict(type="bool", default=False),
254 permissions=dict(type="list", elements="str"),
255 local=dict(type="bool"),
256 descendents=dict(type="bool"),
257 recursive=dict(type="bool", default=False),
258 ),
259 supports_check_mode=False,
260 required_if=[("state", "present", ["permissions"])],
261 )
262 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
263 zfs_delegate_admin = ZfsDelegateAdmin(module)
264 zfs_delegate_admin.run()
265
266
267 if __name__ == "__main__":
268 main()