Debian Codegraph @

ansible_collections/ibm/storage_virtualize/plugins/modules/ibm_svc_hostcluster.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2021 IBM CORPORATION
5 # Author(s): Shilpi Jain <[email protected]>
6 # Lavanya C R <[email protected]>
7 # Sandip Gulab Rajbanshi <[email protected]>
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13 DOCUMENTATION = '''
14 ---
15 module: ibm_svc_hostcluster
16 short_description: This module manages host cluster on IBM Storage Virtualize family systems
17 version_added: "1.5.0"
18 description:
19 - Ansible interface to manage 'mkhostcluster', 'chhostcluster' and 'rmhostcluster' host commands.
20 options:
21 name:
22 description:
23 - Specifies a name or label for the new host cluster object.
24 required: true
25 type: str
26 state:
27 description:
28 - Creates (C(present)) or removes (C(absent)) a host cluster.
29 choices: [ absent, present ]
30 required: true
31 type: str
32 clustername:
33 description:
34 - The hostname or management IP or Partition IP of the Storage Virtualize system.
35 required: true
36 type: str
37 domain:
38 description:
39 - Domain for the Storage Virtualize system.
40 - Valid when hostname is used for the parameter I(clustername).
41 type: str
42 username:
43 description:
44 - REST API username for the Storage Virtualize system.
45 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
46 type: str
47 password:
48 description:
49 - REST API password for the Storage Virtualize system.
50 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
51 type: str
52 token:
53 description:
54 - The authentication token to verify a user on the Storage Virtualize system.
55 - To generate a token, use the M(ibm.storage_virtualize.ibm_svc_auth) module.
56 type: str
57 ownershipgroup:
58 description:
59 - The name of the ownership group to which the host cluster object is being added.
60 - Parameters I(ownershipgroup) and I(noownershipgroup) are mutually exclusive.
61 - Applies when I(state=present).
62 type: str
63 version_added: '1.6.0'
64 noownershipgroup:
65 description:
66 - If specified True, the host cluster object is removed from the ownership group to which it belongs.
67 - Parameters I(ownershipgroup) and I(noownershipgroup) are mutually exclusive.
68 - Applies when I(state=present) to modify an existing hostcluster.
69 type: bool
70 version_added: '1.6.0'
71 removeallhosts:
72 description:
73 - Specifies that all hosts in the host cluster and the associated host cluster object be deleted.
74 - Applies when I(state=absent), to delete a host cluster with all its hosts.
75 - Parameters I(removeallhosts) and I(removemappings) are mutually exclusive.
76 type: bool
77 site:
78 description:
79 - Specifies the site name of the all hosts in the hostcluster.
80 - Valid when I(state=present), to modify an existing hostcluster.
81 type: str
82 version_added: '2.7.0'
83 partition:
84 description:
85 - Specifies the partition or draft partition name in which user wants to create the hostcluster.
86 - Valid when I(state=present), to create and modify an existing hostcluster.
87 type: str
88 version_added: '3.0.0'
89 removemappings:
90 description:
91 - Removes specified mappings from the hostcluster.
92 - Valid when I(state=absent), to delete a hostcluster.
93 - If specified as true, removes all the host-to-volume mappings.
94 - If specified as false, keeps the host-to-volume mappings (works as keepmappings).
95 - Parameters I(removeallhosts) and I(removemappings) are mutually exclusive.
96 type: bool
97 version_added: '3.0.0'
98 log_path:
99 description:
100 - Path of debug log file.
101 type: str
102 validate_certs:
103 description:
104 - Validates certification.
105 default: false
106 type: bool
107 author:
108 - Shilpi Jain (@Shilpi-J)
109 - Lavanya C R (@lavanyacr)
110 - Sandip Gulab Rajbanshi (@Sandip-Rajbanshi)
111 notes:
112 - This module supports C(check_mode).
113 - This module supports logging in via partition IP.
114 - Parameters not supported when logged in via partition IP are 'ownershipgroup', 'noownershipgroup', 'removeallhosts', 'site',
115 'removemappings'.
116 '''
117
118 EXAMPLES = '''
119 - name: Define a new host cluster
120 ibm.storage_virtualize.ibm_svc_hostcluster:
121 clustername: "{{ clustername }}"
122 domain: "{{ domain }}"
123 username: "{{ username }}"
124 password: "{{ password }}"
125 log_path: /tmp/playbook.debug
126 name: hostcluster0
127 state: present
128 ownershipgroup: group1
129 - name: Define a new host cluster with partition
130 ibm.storage_virtualize.ibm_svc_hostcluster:
131 clustername: "{{ clustername }}"
132 domain: "{{ domain }}"
133 username: "{{ username }}"
134 password: "{{ password }}"
135 log_path: /tmp/playbook.debug
136 name: hostcluster0
137 state: present
138 partition: partition1
139 - name: Update the ownershipgroup of a host cluster
140 ibm.storage_virtualize.ibm_svc_hostcluster:
141 clustername: "{{ clustername }}"
142 domain: "{{ domain }}"
143 username: "{{ username }}"
144 password: "{{ password }}"
145 log_path: /tmp/playbook.debug
146 name: hostcluster0
147 state: present
148 noownershipgroup: 'True'
149 - name: Update the draftpartition of a host cluster
150 ibm.storage_virtualize.ibm_svc_hostcluster:
151 clustername: "{{ clustername }}"
152 domain: "{{ domain }}"
153 username: "{{ username }}"
154 password: "{{ password }}"
155 log_path: /tmp/playbook.debug
156 name: hostcluster0
157 state: present
158 partition: draft_ptn
159 - name: Delete a host cluster
160 ibm.storage_virtualize.ibm_svc_hostcluster:
161 clustername: "{{ clustername }}"
162 domain: "{{ domain }}"
163 username: "{{ username }}"
164 password: "{{ password }}"
165 log_path: /tmp/playbook.debug
166 name: hostcluster0
167 state: absent
168 removeallhosts: 'True'
169 '''
170
171 RETURN = '''#'''
172
173 from traceback import format_exc
174 from ansible.module_utils.basic import AnsibleModule
175 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
176 from ansible.module_utils._text import to_native
177
178
179 class IBMSVChostcluster(object):
180 def __init__(self):
181 argument_spec = svc_argument_spec()
182
183 argument_spec.update(
184 dict(
185 name=dict(type='str', required=True),
186 state=dict(type='str', required=True, choices=['absent', 'present']),
187 ownershipgroup=dict(type='str'),
188 noownershipgroup=dict(type='bool'),
189 removeallhosts=dict(type='bool'),
190 site=dict(type='str'),
191 partition=dict(type='str'),
192 removemappings=dict(type='bool'),
193 )
194 )
195
196 self.changed = ""
197
198 self.module = AnsibleModule(argument_spec=argument_spec,
199 supports_check_mode=True)
200
201 # logging setup
202 log_path = self.module.params['log_path']
203 log = get_logger(self.__class__.__name__, log_path)
204 self.log = log.info
205
206 # Required
207 self.name = self.module.params['name']
208 self.state = self.module.params['state']
209
210 # Optional
211 self.ownershipgroup = self.module.params.get('ownershipgroup', '')
212 self.noownershipgroup = self.module.params.get('noownershipgroup', '')
213 self.removeallhosts = self.module.params.get('removeallhosts', '')
214 self.site = self.module.params.get('site', '')
215 self.partition = self.module.params.get('partition', '')
216 self.removemappings = self.module.params.get('removemappings', '')
217 self.restapi = IBMSVCRestApi(
218 module=self.module,
219 clustername=self.module.params['clustername'],
220 domain=self.module.params['domain'],
221 username=self.module.params['username'],
222 password=self.module.params['password'],
223 validate_certs=self.module.params['validate_certs'],
224 log_path=log_path,
225 token=self.module.params['token']
226 )
227
228 def basic_checks(self):
229 if self.state == 'present':
230 if self.removemappings or self.removeallhosts:
231 self.module.fail_json(msg="Parameter [removemappings] or [removeallhosts] can be used only while deleting hostcluster")
232
233 if self.ownershipgroup and self.noownershipgroup:
234 self.module.fail_json(msg='Mutually exclusive parameters: [ownershipgroup, noownershipgroup]')
235
236 if self.state == 'absent':
237 if self.removeallhosts and self.removemappings:
238 self.module.fail_json(msg='Mutually exclusive parameters: [removeallhosts, removemappings]')
239
240 fields = [f for f in ['ownershipgroup', 'noownershipgroup', 'site', 'partition'] if getattr(self, f)]
241 if any(fields):
242 self.module.fail_json(msg='Parameters [{0}] not supported while deleting a hostcluster'.format(', '.join(fields)))
243
244 def get_existing_hostcluster(self):
245 return self.restapi.svc_obj_info(cmd='lshostcluster', cmdopts=None, cmdargs=[self.name]) or {}
246
247 def get_existing_partition(self, partition_name):
248 return self.restapi.svc_obj_info(cmd='lspartition', cmdopts=None, cmdargs=[partition_name]) or {}
249
250 def hostcluster_probe(self, data):
251 props = []
252
253 if self.ownershipgroup and self.ownershipgroup != data['owner_name']:
254 props.append('ownershipgroup')
255
256 if self.noownershipgroup and data['owner_name'] != "":
257 props.append('noownershipgroup')
258
259 if self.partition:
260 partition_result = self.get_existing_partition(self.partition)
261 if not partition_result:
262 self.module.fail_json(msg="Partition [{0}] does not exist".format(self.partition))
263
264 if partition_result.get('draft') == 'yes':
265 if self.partition != data['draft_partition_name']:
266 if data['partition_name']:
267 self.module.fail_json(msg="Hostcluster is already associated with a partition.")
268 props.append('partition')
269 else:
270 if self.partition != data['partition_name']:
271 self.module.fail_json(msg="Published partition is not supported while updating host cluster")
272
273 if self.site:
274 if data['host_count'] == '0':
275 self.module.fail_json(msg="Cannot update host cluster [{0}] site to [{1}] as it has no hosts.".format(self.name, self.site))
276
277 site_update_required = False
278 existing_hosts = self.restapi.svc_obj_info(cmd='lshost', cmdopts={'filtervalue' : 'host_cluster_name={0}'.format(self.name)}, cmdargs=None)
279
280 conflict_hosts = []
281 for host in existing_hosts:
282 if host['site_name'] == "":
283 site_update_required = True
284 elif self.site != host['site_name'] and self.site != host['site_id']:
285 conflict_hosts.append(f"{host['name']} (Current site: {host['site_name']})")
286
287 if conflict_hosts:
288 self.module.fail_json(
289 msg=f"Cannot update host cluster site to [{self.site}]. "
290 f"The following hosts already have a different site: {', '.join(conflict_hosts)}"
291 )
292 if site_update_required:
293 props.append('site')
294
295 self.log("hostcluster_probe props='%s'", props)
296
297 return props
298
299 def hostcluster_create(self):
300 if self.module.check_mode:
301 self.changed = True
302 return
303 # Make command
304 cmd = 'mkhostcluster'
305 cmdopts = {'name': self.name}
306
307 fields = [f for f in ['site'] if getattr(self, f)]
308 if any(fields):
309 self.module.fail_json(msg='Parameters [{0}] not supported while creating a hostcluster'.format(', '.join(fields)))
310
311 if self.ownershipgroup:
312 cmdopts['ownershipgroup'] = self.ownershipgroup
313
314 if self.partition:
315 partition_result = self.get_existing_partition(self.partition)
316 if not partition_result:
317 self.module.fail_json(msg="Partition [{0}] does not exist".format(self.partition))
318 if partition_result.get('draft') == 'yes':
319 cmdopts['draftpartition'] = self.partition
320 else:
321 cmdopts['partition'] = self.partition
322
323 self.log("Command options for creating host: '%s'", cmdopts)
324
325 # Run command
326 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=None)
327 self.changed = True
328
329 def hostcluster_update(self, modify):
330 if self.module.check_mode:
331 self.changed = True
332 return
333
334 self.log("updating host cluster '%s'", self.name)
335 cmd = 'chhostcluster'
336 cmdopts = {}
337
338 for param in modify:
339 if param == 'partition':
340 cmdopts['draftpartition'] = self.partition
341 else:
342 cmdopts[param] = getattr(self, param)
343
344 if cmdopts:
345 self.restapi.svc_run_command(cmd, cmdopts, cmdargs=[self.name])
346 # Any error will have been raised in svc_run_command
347 # chhost does not output anything when successful.
348 self.changed = True
349 self.log("Properties of %s updated", self.name)
350
351 def hostcluster_delete(self, data):
352 if self.module.check_mode:
353 self.changed = True
354 return
355
356 self.log("deleting host cluster '%s'", self.name)
357
358 cmd = 'rmhostcluster'
359 cmdopts = {}
360 cmdargs = [self.name]
361
362 is_partition_associated = bool(data.get('partition_name') or data.get('draft_partition_name'))
363 mapping_count = data.get('mapping_count')
364 has_mappings = mapping_count and mapping_count != "0"
365
366 if self.removemappings:
367 if is_partition_associated:
368 self.module.fail_json(
369 msg=f"Cannot remove host cluster [{self.name}] as it is associated with a partition. "
370 f"Use removemappings=false to delete the host cluster to keep host to volume mappings."
371 )
372 if has_mappings:
373 cmdopts['removemappings'] = True
374 elif (is_partition_associated or has_mappings) and not self.removeallhosts:
375 cmdopts['keepmappings'] = True
376
377 if self.removeallhosts:
378 cmdopts['force'] = True
379 cmdopts['removeallhosts'] = True
380
381 self.restapi.svc_run_command(cmd, cmdopts, cmdargs)
382 # Any error will have been raised in svc_run_command
383 # chhost does not output anything when successful.
384 self.changed = True
385
386 def apply(self):
387 changed = False
388 msg = None
389 modify = []
390
391 self.basic_checks()
392 hc_data = self.get_existing_hostcluster()
393
394 if hc_data:
395 if self.state == 'absent':
396 self.log("CHANGED: host cluster exists, but requested "
397 "state is 'absent'")
398 changed = True
399 elif self.state == 'present':
400 # This is where we detect if chhostcluster should be called
401 modify = self.hostcluster_probe(hc_data)
402 if modify:
403 changed = True
404 else:
405 if self.state == 'present':
406 self.log("CHANGED: host cluster does not exist, "
407 "but requested state is 'present'")
408 changed = True
409
410 if changed:
411 if self.state == 'present':
412 if not hc_data:
413 self.hostcluster_create()
414 msg = "host cluster %s has been created." % self.name
415 else:
416 # This is where we would modify
417 self.hostcluster_update(modify)
418 msg = "host cluster [%s] has been modified." % self.name
419 elif self.state == 'absent':
420 self.hostcluster_delete(hc_data)
421 msg = "host cluster [%s] has been deleted." % self.name
422
423 if self.module.check_mode:
424 msg = "skipping changes due to check mode"
425 else:
426 self.log("exiting with no changes")
427 if self.state == 'absent':
428 msg = "host cluster [%s] did not exist." % self.name
429 else:
430 msg = "host cluster [%s] already exists. No modifications done." % self.name
431
432 self.module.exit_json(msg=msg, changed=changed)
433
434
435 def main():
436 v = IBMSVChostcluster()
437 try:
438 v.apply()
439 except Exception as e:
440 v.log("Exception in apply(): \n%s", format_exc())
441 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
442
443
444 if __name__ == '__main__':
445 main()