Debian Codegraph @

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

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