Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (C) 2022 IBM CORPORATION
5 # Author(s): Sreshtant Bohidar <[email protected]>
6 # Rahul Pawar <[email protected]>
7 #
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_manage_ip
16 short_description: This module manages IP provisioning on IBM Storage Virtualize family systems
17 description:
18 - Ansible interface to manage 'mkip' and 'rmip' commands.
19 - This module can run on all IBM Storage Virtualize systems running on 8.4.2.0 or later.
20 version_added: "1.8.0"
21 options:
22 state:
23 description:
24 - Creates (C(present)) or removes (C(absent)) an IP address.
25 choices: [ present, absent ]
26 required: true
27 type: str
28 clustername:
29 description:
30 - The hostname or management IP of the Storage Virtualize system.
31 type: str
32 required: true
33 domain:
34 description:
35 - Domain for the Storage Virtualize system.
36 - Valid when hostname is used for the parameter I(clustername).
37 type: str
38 username:
39 description:
40 - REST API username for the Storage Virtualize system.
41 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
42 type: str
43 password:
44 description:
45 - REST API password for the Storage Virtualize system.
46 - The parameters I(username) and I(password) are required if not using I(token) to authenticate a user.
47 type: str
48 token:
49 description:
50 - The authentication token to verify a user on the Storage Virtualize system.
51 - To generate a token, use the ibm_svc_auth module.
52 type: str
53 node:
54 description:
55 - Specifies the name of the node.
56 type: str
57 port:
58 description:
59 - Specifies a port ranging from 1 - 16 to which IP shall be assigned.
60 type: int
61 portset:
62 description:
63 - Specifies the name of the portset object.
64 type: str
65 ip_address:
66 description:
67 - Specifies a valid ipv4/ipv6 address.
68 type: str
69 required: true
70 subnet_prefix:
71 description:
72 - Specifies the prefix of subnet mask.
73 - Required when I(state=present).
74 type: int
75 gateway:
76 description:
77 - Specifies the gateway address.
78 - Applies when I(state=present).
79 type: str
80 vlan:
81 description:
82 - Specifies a vlan id ranging from 1 - 4096.
83 - Applies when I(state=present).
84 type: int
85 resetgateway:
86 description:
87 - Specifies whether to reset the gateway to None.
88 - Applies when I(state=present).
89 type: bool
90 default: false
91 version_added: '3.1.0'
92 resetvlan:
93 description:
94 - Specifies whether to reset the vlan to None.
95 - Applies when I(state=present).
96 type: bool
97 default: false
98 version_added: '3.1.0'
99 old_ip_address:
100 description:
101 - Specifies the old IP address to be changed.
102 - If not provided, the value of I(ip_address) will be used.
103 - Applies when I(state=present).
104 type: str
105 version_added: '3.1.0'
106 shareip:
107 description:
108 - Specifies the flag when IP is shared between multiple portsets.
109 - Applies when I(state=present).
110 type: bool
111 validate_certs:
112 description:
113 - Validates certification.
114 default: false
115 type: bool
116 log_path:
117 description:
118 - Path of debug log file.
119 type: str
120 author:
121 - Sreshtant Bohidar(@Sreshtant-Bohidar)
122 notes:
123 - This module supports C(check_mode).
124 '''
125
126 EXAMPLES = '''
127 - name: Create IP provisioning
128 ibm.storage_virtualize.ibm_svc_manage_ip:
129 clustername: "{{ cluster }}"
130 username: "{{ username }}"
131 password: "{{ password }}"
132 log_path: /tmp/playbook.debug
133 node: node1
134 port: 1
135 portset: portset0
136 ip_address: x.x.x.a
137 subnet_prefix: 20
138 gateway: x.x.x.y
139 vlan: 1
140 shareip: true
141 state: present
142 - name: Change IP provisioning
143 ibm.storage_virtualize.ibm_svc_manage_ip:
144 clustername: "{{ cluster }}"
145 username: "{{ username }}"
146 password: "{{ password }}"
147 log_path: /tmp/ansible.log
148 portset: test_mgmt1
149 old_ip_address: x.x.x.a
150 ip_address: x.x.x.b
151 subnet_prefix: 20
152 gateway: x.x.x.y
153 vlan: 1
154 state: present
155 - name: Reset Vlan and Gateway of an IP
156 ibm.storage_virtualize.ibm_svc_manage_ip:
157 clustername: "{{ cluster }}"
158 username: "{{ username }}"
159 password: "{{ password }}"
160 log_path: /tmp/ansible.log
161 portset: test_mgmt1
162 ip_address: x.x.x.b
163 subnet_prefix: 20
164 resetgateway: true
165 resetvlan: true
166 state: present
167 - name: Remove IP provisioning
168 ibm.storage_virtualize.ibm_svc_manage_ip:
169 clustername: "{{ cluster }}"
170 username: "{{ username }}"
171 password: "{{ password }}"
172 log_path: /tmp/playbook.debug
173 ip_address: x.x.x.x
174 state: absent
175 - name: Create IP provisioning for management portset
176 ibm.storage_virtualize.ibm_svc_manage_ip:
177 clustername: "{{ cluster }}"
178 username: "{{ username }}"
179 password: "{{ password }}"
180 log_path: /tmp/playbook.debug
181 node: node1
182 portset: mgmt_portset
183 ip_address: x.x.x.a
184 subnet_prefix: 20
185 gateway: x.x.x.y
186 vlan: 1
187 shareip: true
188 state: present
189 '''
190
191 RETURN = '''#'''
192
193 from traceback import format_exc
194 from ansible.module_utils.basic import AnsibleModule
195 from ansible_collections.ibm.storage_virtualize.plugins.module_utils.ibm_svc_utils import IBMSVCRestApi, svc_argument_spec, get_logger
196 from ansible.module_utils._text import to_native
197
198
199 class IBMSVCIp(object):
200 def __init__(self):
201 argument_spec = svc_argument_spec()
202 argument_spec.update(
203 dict(
204 node=dict(type='str'),
205 state=dict(type='str', required=True, choices=['present', 'absent']),
206 port=dict(type='int'),
207 portset=dict(type='str'),
208 ip_address=dict(type='str', required=True),
209 subnet_prefix=dict(type='int'),
210 gateway=dict(type='str'),
211 vlan=dict(type='int'),
212 shareip=dict(type='bool'),
213 old_ip_address=dict(type='str'),
214 resetgateway=dict(type='bool', default=False),
215 resetvlan=dict(type='bool', default=False)
216 )
217 )
218
219 mutually_exclusive = [
220 ['gateway', 'resetgateway'],
221 ['vlan', 'resetvlan'],
222 ]
223 self.module = AnsibleModule(argument_spec=argument_spec,
224 required_if=[
225 ('state', 'present', ['ip_address', 'subnet_prefix']),
226 ('state', 'absent', ['ip_address'])
227 ],
228 mutually_exclusive=mutually_exclusive,
229 supports_check_mode=True)
230
231 # logging setup
232 log_path = self.module.params['log_path']
233 log = get_logger(self.__class__.__name__, log_path)
234 self.log = log.info
235
236 # Required
237 self.state = self.module.params['state']
238 self.ip_address = self.module.params.get('ip_address', False)
239
240 # Optional
241 self.portset = self.module.params.get('portset', None)
242 self.subnet_prefix = self.module.params.get('subnet_prefix', None)
243 self.gateway = self.module.params.get('gateway', None)
244 self.vlan = self.module.params.get('vlan', None)
245 self.shareip = self.module.params.get('shareip', None)
246 self.port = self.module.params.get('port', None)
247 self.old_ip_address = self.module.params.get('old_ip_address', None)
248 self.resetgateway = self.module.params.get('resetgateway', False)
249 self.resetvlan = self.module.params.get('resetvlan', False)
250 self.node = self.module.params.get('node', None)
251
252 # Initialize changed variable
253 self.changed = False
254
255 # creating an instance of IBMSVCRestApi
256 self.restapi = IBMSVCRestApi(
257 module=self.module,
258 clustername=self.module.params['clustername'],
259 domain=self.module.params['domain'],
260 username=self.module.params['username'],
261 password=self.module.params['password'],
262 validate_certs=self.module.params['validate_certs'],
263 log_path=log_path,
264 token=self.module.params['token']
265 )
266
267 def basic_checks(self):
268 if self.state == 'absent':
269 not_required_when_absent = {
270 'old_ip_address': self.old_ip_address,
271 'subnet_prefix': self.subnet_prefix,
272 'gateway': self.gateway,
273 'vlan': self.vlan,
274 'shareip': self.shareip,
275 'node': self.node,
276 'port': self.port
277 }
278 not_applicable_absent = [item for item, value in not_required_when_absent.items() if value]
279 if not_applicable_absent:
280 self.module.fail_json(msg="The parameter {0} are not applicable when state is absent.".format(not_applicable_absent))
281
282 def get_ip_info(self, ip_address):
283 all_data = self.restapi.svc_obj_info(cmd='lsip', cmdopts=None, cmdargs=None)
284 ip_data = [item for item in all_data if item['IP_address'] == ip_address]
285 ip_addr = None
286
287 if not ip_data:
288 self.log('No IP found')
289 return None
290
291 if self.portset:
292 ip_addr = next((item for item in ip_data if item['portset_name'] == self.portset), None)
293 if not ip_addr and not self.shareip and self.state == 'present':
294 self.module.fail_json(
295 msg="IP {0} already exists. Portset cannot be changed. To create shared data IP, use shareip parameter.".format(ip_address)
296 )
297 else:
298 if len(ip_data) > 1:
299 self.module.fail_json(
300 msg="Multiple objects found with IP {0}. Please specify portset.".format(ip_address)
301 )
302 ip_addr = ip_data[0]
303
304 return ip_addr
305
306 def create_ip(self):
307 if self.module.check_mode:
308 self.changed = True
309 return
310 command = 'mkip'
311 command_options = {
312 'ip': self.ip_address,
313 'prefix': self.subnet_prefix
314 }
315 if self.gateway:
316 command_options['gw'] = self.gateway
317 for field in ['node', 'port', 'portset', 'vlan', 'shareip']:
318 value = getattr(self, field, None)
319 if value:
320 command_options[field] = value
321
322 result = self.restapi.svc_run_command(command, command_options, cmdargs=None)
323 self.log("create IP result %s", result)
324 self.changed = True
325
326 def ip_probe(self, data):
327 props = {}
328
329 if self.old_ip_address and self.ip_address != data['IP_address']:
330 props['ip_address'] = self.ip_address
331 if self.subnet_prefix != int(data['prefix']):
332 props['prefix'] = self.subnet_prefix
333 if self.node and (self.node != data['node_name']):
334 props['node'] = self.node
335 if self.port and (self.port != int(data['port_id'])):
336 props['port'] = self.port
337
338 if self.gateway and (self.gateway != data['gateway']):
339 props['gateway'] = self.gateway
340 if self.resetgateway and data['gateway']:
341 props['gateway'] = ""
342 if isinstance(self.vlan, int) and (self.vlan != (int(data.get('vlan') or 0))):
343 props['vlan'] = self.vlan
344 if self.resetvlan and data['vlan']:
345 props['vlan'] = ""
346
347 self.log("IP probe props='%s'", props)
348 return props
349
350 def update_ip(self, old_data, modify):
351 if self.module.check_mode:
352 self.changed = True
353 return
354
355 unsupported_parameters = ['node', 'port']
356 unsupported_exists = [param for param in unsupported_parameters if param in modify]
357 if unsupported_exists:
358 self.module.fail_json(msg=f"Update is not supported for parameter(s): {', '.join(unsupported_exists)}")
359
360 command = 'chip'
361 command_options = {}
362 command_options['ip'] = self.ip_address
363 cmdargs = [old_data['id']]
364
365 command_options['ip'] = modify.get('ip_address', old_data['IP_address'])
366 command_options['prefix'] = modify.get('prefix', old_data['prefix'])
367
368 if 'gateway' in modify and modify['gateway'] != "":
369 command_options['gw'] = modify['gateway']
370 elif not self.resetgateway and old_data['gateway']:
371 command_options['gw'] = old_data['gateway']
372
373 if 'vlan' in modify and modify['vlan'] != "":
374 command_options['vlan'] = modify['vlan']
375 elif not self.resetvlan and old_data['vlan']:
376 command_options['vlan'] = old_data['vlan']
377
378 self.restapi.svc_run_command(command, command_options, cmdargs)
379 self.log("IP parameters successfully changed.")
380 self.changed = True
381
382 def remove_ip(self, ip_address_id):
383 if self.module.check_mode:
384 self.changed = True
385 return
386 command = 'rmip'
387 command_options = None
388 cmdargs = [ip_address_id]
389 self.restapi.svc_run_command(command, command_options, cmdargs)
390 self.changed = True
391 self.log("IP removed")
392
393 def apply(self):
394 msg = None
395 self.basic_checks()
396
397 ip_data = None
398 if self.old_ip_address:
399 if self.old_ip_address == self.ip_address:
400 self.old_ip_address = None
401
402 old_data = self.get_ip_info(self.old_ip_address) if self.old_ip_address else None
403 new_data = self.get_ip_info(self.ip_address)
404
405 if old_data and new_data:
406 self.module.fail_json(msg="Both IP '{0}' and '{1}' exist. Cannot update IP address.".format(self.old_ip_address, self.ip_address))
407
408 if not old_data:
409 if not new_data:
410 self.module.fail_json(msg="IP '{0}' does not exist.".format(self.old_ip_address))
411
412 self.log("IP '%s' already exists. Continuing updates on it.", self.ip_address)
413 ip_data = new_data
414 else:
415 ip_data = old_data
416 else:
417 ip_data = self.get_ip_info(self.ip_address)
418
419 if self.state == 'present':
420 if not ip_data:
421 self.create_ip()
422 msg = "IP address {0} has been created.".format(self.ip_address)
423 else:
424 modify = self.ip_probe(ip_data)
425 if modify:
426 self.update_ip(ip_data, modify)
427 msg = "IP address {0} changed.".format(self.ip_address)
428 else:
429 msg = 'No modifications done.'
430 else:
431 if ip_data:
432 self.remove_ip(ip_data['id'])
433 msg = "IP address {0} has been removed.".format(self.ip_address)
434 else:
435 msg = "IP address {0} does not exist.".format(self.ip_address)
436 if self.portset:
437 msg = "IP address {0} with specified portset does not exist.".format(self.ip_address)
438
439 self.module.exit_json(msg=msg, changed=self.changed)
440
441
442 def main():
443 v = IBMSVCIp()
444 try:
445 v.apply()
446 except Exception as e:
447 v.log("Exception in apply(): \n%s", format_exc())
448 v.module.fail_json(msg="Module failed. Error [%s]." % to_native(e))
449
450
451 if __name__ == '__main__':
452 main()