Debian Codegraph @

ansible_collections/dellemc/unity/plugins/modules/interface.py

raw symbols SCIP
1 #!/usr/bin/python
2 # Copyright: (c) 2022-2025, Dell Technologies
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 """Ansible module for managing Interfaces on Unity"""
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 module: interface
13 version_added: '1.4.0'
14 short_description: Manage Interfaces on Unity storage system
15 description:
16 - Managing the Interfaces on the Unity storage system includes adding Interfaces to NAS Server, getting
17 details of interface and deleting configured interfaces.
18
19 extends_documentation_fragment:
20 - dellemc.unity.unity
21
22 author:
23 - Meenakshi Dembi (@dembim) <[email protected]>
24
25 options:
26 nas_server_name:
27 description:
28 - Name of the NAS server for which interface will be configured.
29 type: str
30 nas_server_id:
31 description:
32 - ID of the NAS server for which interface will be configured.
33 type: str
34 ethernet_port_name:
35 description:
36 - Name of the ethernet port.
37 type: str
38 ethernet_port_id:
39 description:
40 - ID of the ethernet port.
41 type: str
42 role:
43 description:
44 - Indicates whether interface is configured as production or backup.
45 choices: [PRODUCTION, BACKUP]
46 type: str
47 interface_ip:
48 description:
49 - IP of network interface.
50 required: true
51 type: str
52 netmask:
53 description:
54 - Netmask of network interface.
55 type: str
56 prefix_length:
57 description:
58 - Prefix length is mutually exclusive with I(netmask).
59 type: int
60 gateway:
61 description:
62 - Gateway of network interface.
63 type: str
64 vlan_id:
65 description:
66 - Vlan id of the interface.
67 type: int
68 state:
69 description:
70 - Define whether the interface should exist or not.
71 choices: [present, absent]
72 required: true
73 type: str
74 notes:
75 - The I(check_mode) is supported.
76 - Modify operation for interface is not supported.
77 '''
78
79 EXAMPLES = r'''
80
81 - name: Add Interface as Backup to NAS Server
82 interface:
83 unispherehost: "{{unispherehost}}"
84 username: "{{username}}"
85 password: "{{password}}"
86 validate_certs: "{{validate_certs}}"
87 nas_server_name: "dummy_nas"
88 ethernet_port_name: "SP A 4-Port Card Ethernet Port 0"
89 role: "BACKUP"
90 interface_ip: "xx.xx.xx.xx"
91 netmask: "xx.xx.xx.xx"
92 gateway: "xx.xx.xx.xx"
93 vlan_id: 324
94 state: "present"
95
96 - name: Add Interface as Production to NAS Server
97 interface:
98 unispherehost: "{{unispherehost}}"
99 username: "{{username}}"
100 password: "{{password}}"
101 validate_certs: "{{validate_certs}}"
102 nas_server_name: "dummy_nas"
103 ethernet_port_name: "SP A 4-Port Card Ethernet Port 0"
104 role: "PRODUCTION"
105 interface_ip: "xx.xx.xx.xx"
106 netmask: "xx.xx.xx.xx"
107 gateway: "xx.xx.xx.xx"
108 vlan_id: 324
109 state: "present"
110
111 - name: Get interface details
112 interface:
113 unispherehost: "{{unispherehost}}"
114 username: "{{username}}"
115 password: "{{password}}"
116 validate_certs: "{{validate_certs}}"
117 nas_server_name: "dummy_nas"
118 interface_ip: "xx.xx.xx.xx"
119 state: "present"
120
121 - name: Delete Interface
122 interface:
123 unispherehost: "{{unispherehost}}"
124 username: "{{username}}"
125 password: "{{password}}"
126 validate_certs: "{{validate_certs}}"
127 nas_server_name: "dummy_nas"
128 interface_ip: "xx.xx.xx.xx"
129 state: "absent"
130 '''
131
132 RETURN = r'''
133 changed:
134 description: Whether or not the resource has changed.
135 returned: always
136 type: bool
137 sample: true
138 interface_details:
139 description: Details of the interface.
140 returned: When interface is configured for NAS Server.
141 type: dict
142 contains:
143 existed:
144 description: Indicates if interface exists.
145 type: bool
146 gateway:
147 description: Gateway of network interface.
148 type: str
149 id:
150 description: Unique identifier interface.
151 type: str
152 ip_address:
153 description: IP address of interface.
154 type: str
155 ip_port:
156 description: Port on which network interface is configured.
157 type: dict
158 contains:
159 id:
160 description: ID of ip_port.
161 type: str
162 ip_protocol_version:
163 description: IP protocol version.
164 type: str
165 is_disabled:
166 description: Indicates whether interface is disabled.
167 type: bool
168 is_preferred:
169 description: Indicates whether interface is preferred.
170 type: bool
171 mac_address:
172 description: Mac address of ip_port.
173 type: bool
174 name:
175 description: System configured name of interface.
176 type: bool
177 nas_server:
178 description: Details of NAS server where interface is configured.
179 type: dict
180 contains:
181 id:
182 description: ID of NAS Server.
183 type: str
184 sample: {
185 "existed": true,
186 "gateway": "xx.xx.xx.xx",
187 "hash": 8785300560421,
188 "health": {
189 "UnityHealth": {
190 "hash": 8785300565468
191 }
192 },
193 "id": "if_69",
194 "ip_address": "10.10.10.10",
195 "ip_port": {
196 "UnityIpPort": {
197 "hash": 8785300565300,
198 "id": "spb_ocp_0_eth0"
199 }
200 },
201 "ip_protocol_version": "IpProtocolVersionEnum.IPv4",
202 "is_disabled": false,
203 "is_preferred": true,
204 "mac_address": "0C:48:C6:9F:57:BF",
205 "name": "36_APM00213404194",
206 "nas_server": {
207 "UnityNasServer": {
208 "hash": 8785300565417,
209 "id": "nas_10"
210 }
211 },
212 "netmask": "10.10.10.10",
213 "replication_policy": null,
214 "role": "FileInterfaceRoleEnum.PRODUCTION",
215 "source_parameters": null,
216 "v6_prefix_length": null,
217 "vlan_id": 324
218 }
219 '''
220
221 from ansible.module_utils.basic import AnsibleModule
222 from ansible_collections.dellemc.unity.plugins.module_utils.storage.dell \
223 import utils
224 import ipaddress
225 from ipaddress import ip_network
226
227 LOG = utils.get_logger('interface')
228
229 application_type = "Ansible/1.7.1"
230
231
232 class Interface(object):
233 """Class with Interface operations"""
234
235 def __init__(self):
236 """Define all parameters required by this module"""
237 self.module_params = utils.get_unity_management_host_parameters()
238 self.module_params.update(get_interface_parameters())
239
240 mutually_exclusive = [['nas_server_name', 'nas_server_id'], ['ethernet_port_id', 'ethernet_port_name'], ['netmask', 'prefix_length']]
241 required_one_of = [['nas_server_name', 'nas_server_id']]
242
243 # initialize the Ansible module
244 self.module = AnsibleModule(
245 argument_spec=self.module_params,
246 supports_check_mode=True,
247 mutually_exclusive=mutually_exclusive,
248 required_one_of=required_one_of
249 )
250 utils.ensure_required_libs(self.module)
251
252 self.unity_conn = utils.get_unity_unisphere_connection(
253 self.module.params, application_type)
254 LOG.info('Check Mode Flag %s', self.module.check_mode)
255
256 def get_interface_details(self, nas_server_obj):
257 """Get interface details.
258 :param: nas_server_obj: NAS server object.
259 :return: Returns interface details configured on NAS server.
260 """
261
262 try:
263 nas_server_obj_properties = nas_server_obj._get_properties()
264 if nas_server_obj_properties['file_interface']:
265 for item in nas_server_obj_properties['file_interface']['UnityFileInterfaceList']:
266 interface_id = self.unity_conn.get_file_interface(_id=item['UnityFileInterface']['id'])
267 if interface_id.ip_address == self.module.params['interface_ip']:
268 return interface_id
269 return None
270 except Exception as e:
271 error_msg = "Getting Interface details failed" \
272 " with error %s" % (str(e))
273 LOG.error(error_msg)
274 self.module.fail_json(msg=error_msg)
275
276 def get_nas_server_obj(self, nas_server_name, nas_server_id):
277 """Get NAS server ID.
278 :param: nas_server_name: The name of NAS server
279 :param: nas_server_id: ID of NAS server
280 :return: Return NAS server object if exists
281 """
282
283 LOG.info("Getting NAS server object")
284 try:
285 if nas_server_name:
286 obj_nas = self.unity_conn.get_nas_server(name=nas_server_name)
287 return obj_nas
288 elif nas_server_id:
289 obj_nas = self.unity_conn.get_nas_server(_id=nas_server_id)
290 if obj_nas._get_properties()['existed']:
291 return obj_nas
292 else:
293 msg = "NAS server with id %s does not exist" % (nas_server_id)
294 LOG.error(msg)
295 self.module.fail_json(msg=msg)
296 except Exception as e:
297 msg = "Failed to get details of NAS server with error: %s" % (str(e))
298 LOG.error(msg)
299 self.module.fail_json(msg=msg)
300
301 def add_interface(self, nas_server_obj, ethernet_port_id=None, ethernet_port_name=None, role=None, interface_ip=None,
302 netmask=None, prefix_length=None, gateway=None, vlan_id=None):
303 """Adding interface to NAS server.
304 :param: nas_server_obj: The NAS server object.
305 :param: ethernet_port_id: ID of ethernet port.
306 :param: ethernet_port_name: Name of ethernet port.
307 :param: role: Role of the interface.
308 :param: interface_ip: IP of interface.
309 :param: netmask: Netmask for interface.
310 :param: prefix_length: Prefix length.
311 :param: gateway: Gateway for interface.
312 :param: vlan_id: vlan_id for interface.
313 :return: Return True if interface is configured successfully.
314 """
315
316 LOG.info("Adding interface to NAS Server")
317 try:
318 nas_server_obj_properties = nas_server_obj._get_properties()
319 if nas_server_obj_properties['file_interface']:
320 for item in nas_server_obj_properties['file_interface']['UnityFileInterfaceList']:
321 interface_id = self.unity_conn.get_file_interface(_id=item['UnityFileInterface']['id'])
322 if interface_id._get_properties()['ip_address'] == self.module.params['interface_ip']:
323 return False
324 if role:
325 role_value = get_role_enum(role)
326 if ethernet_port_name:
327 ethernet_port_info = self.unity_conn.get_ethernet_port(name=ethernet_port_name)
328 ethernet_port_id = ethernet_port_info.id
329 if not self.module.check_mode:
330 utils.UnityFileInterface.create(cli=self.unity_conn._cli, nas_server=nas_server_obj.get_id(), ip_port=ethernet_port_id,
331 role=role_value, ip=interface_ip, netmask=netmask, v6_prefix_length=prefix_length,
332 gateway=gateway, vlan_id=vlan_id)
333 return True
334 except Exception as e:
335 msg = "Failed to add interface to NAS Server with error: %s" % (str(e))
336 LOG.error(msg)
337 self.module.fail_json(msg=msg)
338
339 def is_modification_required(self, interface_details):
340 """Check if modification is required in existing interface/s configured for NAS Server
341 :param: interface_details: Existing interface details
342 :return: True if modification is required
343 """
344 key_list = ['vlan_id', 'gateway', 'netmask']
345 for item in key_list:
346 if self.module.params[item] and self.module.params[item] != interface_details[item]:
347 return True
348 return False
349
350 def delete_interface(self, interface_obj):
351 """Delete NFS server.
352 :param: interface_obj: Interface object.
353 :return: Return True if interface is deleted.
354 """
355
356 LOG.info("Deleting interface")
357 try:
358 if not self.module.check_mode:
359 interface_obj.delete()
360 return True
361 except Exception as e:
362 msg = "Failed to delete interface with error: %s" % (str(e))
363 LOG.error(msg)
364 self.module.fail_json(msg=msg)
365
366 def validate_input_params(self):
367 """Validates input parameters"""
368 param_list = ["nas_server_id", "nas_server_name",
369 "ethernet_port_name", "ethernet_port_id", "role",
370 "interface_ip", "netmask", "gateway"]
371
372 for param in param_list:
373 msg = "Please provide valid value for: %s" % param
374 if self.module.params[param] is not None and \
375 len(self.module.params[param].strip()) == 0:
376 errmsg = msg.format(param)
377 self.module.fail_json(msg=errmsg)
378
379 if self.module.params['vlan_id'] is not None and \
380 (self.module.params['vlan_id'] <= 3 or
381 self.module.params['vlan_id'] >= 4094):
382 self.module.fail_json(msg='vlan_id should be in the '
383 'range of 3 to 4094')
384
385 if self.module.params['interface_ip'] and \
386 not is_valid_ip(self.module.params['interface_ip']):
387 self.module.fail_json(msg='The value for interface ip is invalid')
388
389 if self.module.params['gateway'] and \
390 not is_valid_ip(self.module.params['gateway']):
391 self.module.fail_json(msg='The value for gateway is invalid')
392
393 if self.module.params['netmask'] and not \
394 utils.is_valid_netmask(self.module.params['netmask']):
395 self.module.fail_json(msg='Invalid IPV4 address specified '
396 'for netmask')
397
398 if self.module.params['interface_ip'] and \
399 (get_ip_version(self.module.params['interface_ip']) == 6):
400 self.module.fail_json(msg='IPv6 format is not supported')
401
402 def validate_create_params(self):
403 """Validates input parameters for adding interface"""
404 if self.module.params['role'] is None:
405 self.module.fail_json(msg='Role is a mandatory parameter'
406 ' for adding interface to NAS Server.')
407 if self.module.params['ethernet_port_name'] is None and \
408 self.module.params['ethernet_port_id'] is None:
409 self.module.fail_json(msg='ethernet_port_name/ethernet_port_id '
410 'is mandatory parameter for adding '
411 'interface to NAS Server.')
412
413 def perform_module_operation(self):
414 """
415 Perform different actions on Interface module based on parameters
416 passed in the playbook
417 """
418 nas_server_id = self.module.params['nas_server_id']
419 nas_server_name = self.module.params['nas_server_name']
420 ethernet_port_name = self.module.params['ethernet_port_name']
421 ethernet_port_id = self.module.params['ethernet_port_id']
422 role = self.module.params['role']
423 interface_ip = self.module.params['interface_ip']
424 netmask = self.module.params['netmask']
425 prefix_length = self.module.params['prefix_length']
426 gateway = self.module.params['gateway']
427 vlan_id = self.module.params['vlan_id']
428 state = self.module.params['state']
429
430 # result is a dictionary that contains changed status and Interface details
431 result = dict(
432 changed=False,
433 interface_details={}
434 )
435 modify_flag = False
436
437 self.validate_input_params()
438
439 interface_details = None
440
441 nas_server_obj = self.get_nas_server_obj(nas_server_name, nas_server_id)
442
443 interface_obj = self.get_interface_details(nas_server_obj)
444
445 if interface_obj and state == 'present':
446 interface_details = interface_obj._get_properties()
447 modify_flag = self.is_modification_required(interface_details)
448 if modify_flag:
449 self.module.fail_json(msg="Modification of Interfaces for NAS server is not supported through Ansible module")
450
451 if not interface_obj and state == 'present':
452 self.validate_create_params()
453
454 result['changed'] = self.add_interface(nas_server_obj, ethernet_port_id, ethernet_port_name, role,
455 interface_ip, netmask, prefix_length, gateway, vlan_id)
456
457 if interface_obj and state == 'absent':
458 result['changed'] = self.delete_interface(interface_obj)
459
460 if result['changed']:
461 nas_server_obj = self.get_nas_server_obj(nas_server_name, nas_server_id)
462 interface_obj = self.get_interface_details(nas_server_obj)
463 if interface_obj:
464 interface_details = interface_obj._get_properties()
465
466 result['interface_details'] = interface_details
467
468 self.module.exit_json(**result)
469
470
471 def get_interface_parameters():
472 """This method provide parameters required for the ansible
473 Interface module on Unity"""
474 return dict(
475 nas_server_id=dict(type='str'),
476 nas_server_name=dict(type='str'),
477 ethernet_port_name=dict(type='str'),
478 ethernet_port_id=dict(type='str'),
479 role=dict(type='str', choices=['PRODUCTION', 'BACKUP']),
480 interface_ip=dict(required=True, type='str'),
481 netmask=dict(type='str'),
482 prefix_length=dict(type='int'),
483 gateway=dict(type='str'),
484 vlan_id=dict(type='int'),
485 state=dict(required=True, type='str', choices=['present', 'absent'])
486 )
487
488
489 def get_role_enum(role):
490 """Getting correct enum values for role
491 :param: role: Indicates role of interface.
492 :return: enum value for role.
493 """
494 if utils.FileInterfaceRoleEnum[role]:
495 role = utils.FileInterfaceRoleEnum[role]
496 return role
497
498
499 def is_valid_ip(address):
500 """Validating IP address format
501 :param: address: IP address to be validated for format.
502 """
503 try:
504 ipaddress.ip_address(address)
505 return True
506 except ValueError:
507 return False
508
509
510 def get_ip_version(val):
511 """Returns IP address version
512 :param: val: IP address to be validated for version.
513 """
514 try:
515 val = u'{0}'.format(val)
516 ip = ip_network(val, strict=False)
517 return ip.version
518 except ValueError:
519 return 0
520
521
522 def main():
523 """Create Unity Interface object and perform action on it
524 based on user input from playbook"""
525 obj = Interface()
526 obj.perform_module_operation()
527
528
529 if __name__ == '__main__':
530 main()