Debian Codegraph @

ansible_collections/netapp/storagegrid/plugins/modules/na_sg_grid_tenant.py

raw
1 #!/usr/bin/python
2
3 # (c) 2025, NetApp Inc
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 """NetApp StorageGRID - Manage Tenant Accounts"""
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 ANSIBLE_METADATA = {
14 "metadata_version": "1.1",
15 "status": ["preview"],
16 "supported_by": "community",
17 }
18
19
20 DOCUMENTATION = """
21 module: na_sg_grid_tenant
22 short_description: NetApp StorageGRID manage tenant accounts.
23 extends_documentation_fragment:
24 - netapp.storagegrid.netapp.sg
25 version_added: '21.15.0'
26 author: NetApp Ansible Team (@joshedmonds) <[email protected]>
27 description:
28 - Create, Update, Delete Tenant Accounts on NetApp StorageGRID.
29 options:
30 state:
31 description:
32 - Whether the specified account should exist or not.
33 - Required for all operations.
34 type: str
35 choices: ['present', 'absent']
36 default: present
37 name:
38 description:
39 - Name of the tenant.
40 - Required for create or modify operation.
41 type: str
42 description:
43 description:
44 - Additional identifying information for the tenant account.
45 type: str
46 account_id:
47 description:
48 - Account Id of the tenant.
49 - May be used for modify or delete operation.
50 type: str
51 protocol:
52 description:
53 - Object Storage protocol used by the tenancy.
54 - Required for create operation.
55 type: str
56 choices: ['s3', 'swift']
57 management:
58 description:
59 - Whether the tenant can login to the StorageGRID tenant portal.
60 type: bool
61 default: true
62 use_own_identity_source:
63 description:
64 - Whether the tenant account should configure its own identity source.
65 type: bool
66 allow_platform_services:
67 description:
68 - Allows tenant to use platform services features such as CloudMirror.
69 type: bool
70 allow_select_object_content:
71 description:
72 - Allows tenant to use the S3 SelectObjectContent API to filter and retrieve object data.
73 type: bool
74 allow_compliance_mode:
75 description:
76 - Whether a tenant can use compliance mode for object lock and retention.
77 - Requires storageGRID 11.9 or later.
78 type: bool
79 max_retention_days:
80 description:
81 - The maximum retention period in days allowed for new objects in compliance or governance mode.
82 - Requires storageGRID 11.9 or later.
83 type: int
84 root_access_group:
85 description:
86 - Existing federated group to have initial Root Access permissions for the tenant.
87 - Must begin with C(federated-group/)
88 type: str
89 quota_size:
90 description:
91 - Quota to apply to the tenant specified in I(quota_size_unit).
92 - If you intend to have no limits, assign C(0).
93 type: int
94 default: 0
95 quota_size_unit:
96 description:
97 - The unit used to interpret the size parameter.
98 choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
99 type: str
100 default: 'gb'
101 tenant_password:
102 description:
103 - Root password for tenant account.
104 - Requires root privilege.
105 type: str
106 update_password:
107 description:
108 - Choose when to update the tenant password.
109 - When set to C(always), the tenant password will always be updated.
110 - When set to C(on_create) the tenant password will only be set upon a new user creation.
111 default: on_create
112 choices:
113 - on_create
114 - always
115 type: str
116 """
117
118 EXAMPLES = """
119 - name: create a tenant account
120 netapp.storagegrid.na_sg_grid_tenant:
121 api_url: "https://<storagegrid-endpoint-url>"
122 auth_token: "storagegrid-auth-token"
123 validate_certs: false
124 state: present
125 name: storagegrid-tenant-1
126 protocol: s3
127 management: true
128 allow_compliance_mode: true
129 max_retention_days: 365
130 use_own_identity_source: false
131 allow_platform_services: false
132 tenant_password: "tenant-password"
133 quota_size: 0
134
135 - name: update a tenant account
136 netapp.storagegrid.na_sg_grid_tenant:
137 api_url: "https://<storagegrid-endpoint-url>"
138 auth_token: "storagegrid-auth-token"
139 validate_certs: false
140 state: present
141 name: storagegrid-tenant-1
142 protocol: s3
143 management: true
144 allow_compliance_mode: true
145 max_retention_days: 500
146 use_own_identity_source: false
147 allow_platform_services: true
148 tenant_password: "tenant-password"
149 quota_size: 10240
150
151 - name: delete a tenant account
152 netapp.storagegrid.na_sg_grid_tenant:
153 api_url: "https://<storagegrid-endpoint-url>"
154 auth_token: "storagegrid-auth-token"
155 validate_certs: false
156 state: absent
157 name: storagegrid-tenant-1
158 protocol: s3
159 """
160
161 RETURN = """
162 resp:
163 description: Returns information about the StorageGRID tenant account.
164 returned: success
165 type: dict
166 sample: {
167 "name": "Example Account",
168 "capabilities": ["management", "s3"],
169 "policy": {
170 "useAccountIdentitySource": true,
171 "allowPlatformServices": false,
172 "quotaObjectBytes": 100000000000
173 },
174 "id": "12345678901234567890"
175 }
176 """
177
178 import ansible_collections.netapp.storagegrid.plugins.module_utils.netapp as netapp_utils
179 from ansible.module_utils.basic import AnsibleModule
180 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp_module import (
181 NetAppModule,
182 )
183 from ansible_collections.netapp.storagegrid.plugins.module_utils.netapp import (
184 SGRestAPI,
185 )
186
187
188 class SgGridTenantAccount(object):
189 """
190 Create, modify and delete StorageGRID Tenant Account
191 """
192
193 def __init__(self):
194 """
195 Parse arguments, setup state variables,
196 check parameters and ensure request module is installed
197 """
198 self.argument_spec = netapp_utils.na_storagegrid_host_argument_spec()
199 self.argument_spec.update(
200 dict(
201 state=dict(
202 required=False,
203 type="str",
204 choices=["present", "absent"],
205 default="present",
206 ),
207 name=dict(required=False, type="str"),
208 description=dict(required=False, type="str"),
209 account_id=dict(required=False, type="str"),
210 protocol=dict(required=False, choices=["s3", "swift"]),
211 management=dict(required=False, type="bool", default=True),
212 use_own_identity_source=dict(required=False, type="bool"),
213 allow_platform_services=dict(required=False, type="bool"),
214 allow_select_object_content=dict(required=False, type="bool"),
215 allow_compliance_mode=dict(required=False, type="bool"),
216 max_retention_days=dict(required=False, type="int"),
217 root_access_group=dict(required=False, type="str"),
218 quota_size=dict(required=False, type="int", default=0),
219 quota_size_unit=dict(
220 default="gb",
221 choices=[
222 "bytes",
223 "b",
224 "kb",
225 "mb",
226 "gb",
227 "tb",
228 "pb",
229 "eb",
230 "zb",
231 "yb",
232 ],
233 type="str",
234 ),
235 tenant_password=dict(required=False, type="str", no_log=True),
236 update_password=dict(default="on_create", choices=["on_create", "always"]),
237 )
238 )
239
240 self.module = AnsibleModule(
241 argument_spec=self.argument_spec,
242 required_if=[
243 (
244 "state",
245 "present",
246 [
247 "name",
248 "protocol",
249 "use_own_identity_source",
250 "allow_platform_services",
251 ],
252 )
253 ],
254 supports_check_mode=True,
255 )
256
257 self.na_helper = NetAppModule()
258
259 # set up state variables
260 self.parameters = self.na_helper.set_parameters(self.module.params)
261 # Calling generic SG rest_api class
262 self.rest_api = SGRestAPI(self.module)
263 # Get API version
264 self.rest_api.get_sg_product_version()
265 self.api_version = self.rest_api.get_api_version()
266
267 # Checking for the parameters passed and create new parameters list
268 self.data = {}
269 self.data["name"] = self.parameters["name"]
270 self.data["capabilities"] = [self.parameters["protocol"]]
271
272 if self.parameters.get("description") is not None:
273 self.data["description"] = self.parameters["description"]
274
275 if self.parameters.get("tenant_password") is not None:
276 self.data["password"] = self.parameters["tenant_password"]
277
278 # Append "management" to the capability list only if parameter is True
279 if self.parameters.get("management"):
280 self.data["capabilities"].append("management")
281
282 self.data["policy"] = {}
283
284 if "use_own_identity_source" in self.parameters:
285 self.data["policy"]["useAccountIdentitySource"] = self.parameters["use_own_identity_source"]
286
287 if "allow_platform_services" in self.parameters:
288 self.data["policy"]["allowPlatformServices"] = self.parameters["allow_platform_services"]
289
290 if "allow_compliance_mode" in self.parameters:
291 self.rest_api.fail_if_not_sg_minimum_version("Compliance Mode", 11, 9)
292 self.data["policy"]["allowComplianceMode"] = self.parameters["allow_compliance_mode"]
293
294 if "max_retention_days" in self.parameters:
295 self.rest_api.fail_if_not_sg_minimum_version("Max Retention Days", 11, 9)
296 self.data["policy"]["maxRetentionDays"] = self.parameters["max_retention_days"]
297
298 if self.parameters.get("root_access_group") is not None:
299 self.data["grantRootAccessToGroup"] = self.parameters["root_access_group"]
300
301 if self.parameters["quota_size"] > 0:
302 self.parameters["quota_size"] = (
303 self.parameters["quota_size"] * netapp_utils.POW2_BYTE_MAP[self.parameters["quota_size_unit"]]
304 )
305 self.data["policy"]["quotaObjectBytes"] = self.parameters["quota_size"]
306 elif self.parameters["quota_size"] == 0:
307 self.data["policy"]["quotaObjectBytes"] = None
308
309 self.pw_change = {}
310 if self.parameters.get("tenant_password") is not None:
311 self.pw_change["password"] = self.parameters["tenant_password"]
312
313 if "allow_select_object_content" in self.parameters:
314 self.rest_api.fail_if_not_sg_minimum_version("S3 SelectObjectContent API", 11, 6)
315 self.data["policy"]["allowSelectObjectContent"] = self.parameters["allow_select_object_content"]
316
317 def get_tenant_account_id(self):
318 # Check if tenant account exists
319 # Return tenant account info if found, or None
320 api = "api/%s/grid/accounts" % self.api_version
321 params = {"limit": 20}
322 params["marker"] = ""
323
324 while params["marker"] is not None:
325 list_accounts, error = self.rest_api.get(api, params)
326
327 if error:
328 self.module.fail_json(msg=error)
329
330 if len(list_accounts.get("data")) > 0:
331 for account in list_accounts["data"]:
332 if account["name"] == self.parameters["name"]:
333 return account["id"]
334 # Set marker to last element
335 params["marker"] = list_accounts["data"][-1]["id"]
336 else:
337 params["marker"] = None
338
339 return None
340
341 def get_tenant_account(self, account_id):
342 api = "api/%s/grid/accounts/%s" % (self.api_version, account_id)
343 account, error = self.rest_api.get(api)
344
345 if error:
346 self.module.fail_json(msg=error)
347 else:
348 return account["data"]
349 return None
350
351 def create_tenant_account(self):
352 api = "api/%s/grid/accounts" % self.api_version
353
354 response, error = self.rest_api.post(api, self.data)
355
356 if error:
357 self.module.fail_json(msg=error)
358
359 return response["data"]
360
361 def delete_tenant_account(self, account_id):
362 api = "api/%s/grid/accounts/%s" % (self.api_version, account_id)
363
364 self.data = None
365 response, error = self.rest_api.delete(api, self.data)
366 if error:
367 self.module.fail_json(msg=error)
368
369 def update_tenant_account(self, account_id):
370 api = "api/%s/grid/accounts/%s" % (self.api_version, account_id)
371
372 if "password" in self.data:
373 del self.data["password"]
374
375 if "grantRootAccessToGroup" in self.data:
376 del self.data["grantRootAccessToGroup"]
377
378 response, error = self.rest_api.put(api, self.data)
379 if error:
380 self.module.fail_json(msg=error)
381
382 return response["data"]
383
384 def set_tenant_root_password(self, account_id):
385 api = "api/%s/grid/accounts/%s/change-password" % (self.api_version, account_id)
386 response, error = self.rest_api.post(api, self.pw_change)
387
388 if error:
389 self.module.fail_json(msg=error)
390
391 def apply(self):
392 """
393 Perform pre-checks, call functions and exit
394 """
395
396 tenant_account = None
397
398 if self.parameters.get("account_id"):
399 tenant_account = self.get_tenant_account(self.parameters["account_id"])
400
401 else:
402 tenant_account_id = self.get_tenant_account_id()
403 if tenant_account_id:
404 tenant_account = self.get_tenant_account(tenant_account_id)
405
406 cd_action = self.na_helper.get_cd_action(tenant_account, self.parameters)
407
408 if cd_action is None and self.parameters["state"] == "present":
409 # let's see if we need to update parameters
410 modify = self.na_helper.get_modified_attributes(tenant_account, self.data)
411
412 result_message = ""
413 resp_data = tenant_account
414 if self.na_helper.changed:
415 if self.module.check_mode:
416 pass
417 else:
418 if cd_action == "delete":
419 self.delete_tenant_account(tenant_account["id"])
420 result_message = "Tenant Account deleted"
421 resp_data = None
422
423 elif cd_action == "create":
424 resp_data = self.create_tenant_account()
425 result_message = "Tenant Account created"
426
427 elif modify:
428 resp_data = self.update_tenant_account(tenant_account["id"])
429 result_message = "Tenant Account updated"
430
431 # If a tenant password has been set
432 if self.pw_change:
433 if self.module.check_mode:
434 pass
435 else:
436 # Only update the tenant password if update_password is always
437 # On a create action, the tenant password is set directly by the POST /grid/accounts method
438 if self.parameters["update_password"] == "always" and cd_action != "create":
439 self.set_tenant_root_password(tenant_account["id"])
440 self.na_helper.changed = True
441
442 results = [result_message, "Tenant Account root password updated"]
443 result_message = "; ".join(filter(None, results))
444
445 self.module.exit_json(changed=self.na_helper.changed, msg=result_message, resp=resp_data)
446
447
448 def main():
449 """
450 Main function
451 """
452 na_sg_grid_tenant = SgGridTenantAccount()
453 na_sg_grid_tenant.apply()
454
455
456 if __name__ == "__main__":
457 main()