Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_dvswitch_uplink_pg.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Christian Kotte <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: vmware_dvswitch_uplink_pg
15 short_description: Manage uplink portgroup configuration of a Distributed Switch
16 description:
17 - This module can be used to configure the uplink portgroup of a Distributed Switch.
18 author:
19 - Christian Kotte (@ckotte)
20 options:
21 switch:
22 description:
23 - The name of the Distributed Switch.
24 type: str
25 required: true
26 aliases: ['dvswitch']
27 name:
28 description:
29 - The name of the uplink portgroup.
30 - The current name will be used if not specified.
31 type: str
32 description:
33 description:
34 - The description of the uplink portgroup.
35 type: str
36 advanced:
37 description:
38 - Dictionary which configures the advanced policy settings for the uplink portgroup.
39 suboptions:
40 port_config_reset_at_disconnect:
41 description:
42 - Indicates if the configuration of a port is reset automatically after disconnect.
43 type: bool
44 default: true
45 block_override:
46 description:
47 - Indicates if the block policy can be changed per port.
48 type: bool
49 default: true
50 netflow_override:
51 type: bool
52 description:
53 - Indicates if the NetFlow policy can be changed per port.
54 default: false
55 traffic_filter_override:
56 description:
57 - Indicates if the traffic filter can be changed per port.
58 type: bool
59 default: false
60 vendor_config_override:
61 type: bool
62 description:
63 - Indicates if the vendor config can be changed per port.
64 default: false
65 vlan_override:
66 type: bool
67 description:
68 - Indicates if the vlan can be changed per port.
69 default: false
70 required: false
71 default: {
72 port_config_reset_at_disconnect: true,
73 block_override: true,
74 vendor_config_override: false,
75 vlan_override: false,
76 netflow_override: false,
77 traffic_filter_override: false,
78 }
79 aliases: ['port_policy']
80 type: dict
81 vlan_trunk_range:
82 description:
83 - The VLAN trunk range that should be configured with the uplink portgroup.
84 - 'This can be a combination of multiple ranges and numbers, example: [ 2-3967, 4049-4092 ].'
85 type: list
86 elements: str
87 default: [ '0-4094' ]
88 lacp:
89 description:
90 - Dictionary which configures the LACP settings for the uplink portgroup.
91 - The options are only used if the LACP support mode is set to 'basic'.
92 suboptions:
93 status:
94 description: Indicates if LACP is enabled.
95 default: 'disabled'
96 type: str
97 choices: [ 'enabled', 'disabled' ]
98 mode:
99 description: The negotiating state of the uplinks/ports.
100 default: 'passive'
101 type: str
102 choices: [ 'active', 'passive' ]
103 required: false
104 default: {
105 status: 'disabled',
106 mode: 'passive',
107 }
108 type: dict
109 netflow_enabled:
110 description:
111 - Indicates if NetFlow is enabled on the uplink portgroup.
112 type: bool
113 default: false
114 block_all_ports:
115 description:
116 - Indicates if all ports are blocked on the uplink portgroup.
117 type: bool
118 default: false
119 extends_documentation_fragment:
120 - vmware.vmware.base_options
121
122 '''
123
124 EXAMPLES = r'''
125 - name: Configure Uplink portgroup
126 community.vmware.vmware_dvswitch_uplink_pg:
127 hostname: '{{ inventory_hostname }}'
128 username: '{{ vcsa_username }}'
129 password: '{{ vcsa_password }}'
130 switch: dvSwitch
131 name: dvSwitch-DVUplinks
132 advanced:
133 port_config_reset_at_disconnect: true
134 block_override: true
135 vendor_config_override: false
136 vlan_override: false
137 netflow_override: false
138 traffic_filter_override: false
139 vlan_trunk_range:
140 - '0-4094'
141 netflow_enabled: false
142 block_all_ports: false
143 delegate_to: localhost
144
145 - name: Enabled LACP on Uplink portgroup
146 community.vmware.vmware_dvswitch_uplink_pg:
147 hostname: '{{ inventory_hostname }}'
148 username: '{{ vcsa_username }}'
149 password: '{{ vcsa_password }}'
150 switch: dvSwitch
151 lacp:
152 status: enabled
153 mode: active
154 delegate_to: localhost
155 '''
156
157 RETURN = r'''
158 result:
159 description: information about performed operation
160 returned: always
161 type: str
162 sample: {
163 "adv_block_ports": true,
164 "adv_netflow": false,
165 "adv_reset_at_disconnect": true,
166 "adv_traffic_filtering": false,
167 "adv_vendor_conf": false,
168 "adv_vlan": false,
169 "block_all_ports": false,
170 "changed": false,
171 "description": null,
172 "dvswitch": "dvSwitch",
173 "lacp_status": "disabled",
174 "lacp_status_previous": "enabled",
175 "name": "dvSwitch-DVUplinks",
176 "netflow_enabled": false,
177 "result": "Uplink portgroup already configured properly",
178 "vlan_trunk_range": [
179 "2-3967",
180 "4049-4092"
181 ]
182 }
183 '''
184
185 try:
186 from pyVmomi import vim
187 except ImportError:
188 pass
189
190 from ansible.module_utils.basic import AnsibleModule
191 from ansible.module_utils.common.text.converters import to_native
192 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
193 PyVmomi, TaskError, find_dvs_by_name, wait_for_task
194 )
195 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
196
197
198 class VMwareDvSwitchUplinkPortgroup(PyVmomi):
199 """Class to manage a uplink portgroup on a Distributed Virtual Switch"""
200
201 def __init__(self, module):
202 super(VMwareDvSwitchUplinkPortgroup, self).__init__(module)
203 self.switch_name = self.module.params['switch']
204 self.uplink_pg_name = self.params['name']
205 self.uplink_pg_description = self.params['description']
206 self.uplink_pg_reset = self.params['advanced'].get('port_config_reset_at_disconnect')
207 self.uplink_pg_block_ports = self.params['advanced'].get('block_override')
208 self.uplink_pg_vendor_conf = self.params['advanced'].get('vendor_config_override')
209 self.uplink_pg_vlan = self.params['advanced'].get('vlan_override')
210 self.uplink_pg_netflow = self.params['advanced'].get('netflow_override')
211 self.uplink_pg_tf = self.params['advanced'].get('traffic_filter_override')
212 self.uplink_pg_vlan_trunk_range = self.params['vlan_trunk_range']
213 self.uplink_pg_netflow_enabled = self.params['netflow_enabled']
214 self.uplink_pg_block_all_ports = self.params['block_all_ports']
215 self.lacp_status = self.params['lacp'].get('status')
216 self.lacp_mode = self.params['lacp'].get('mode')
217 self.dvs = find_dvs_by_name(self.content, self.switch_name)
218 if self.dvs is None:
219 self.module.fail_json(msg="Failed to find DVS %s" % self.switch_name)
220 self.support_mode = self.dvs.config.lacpApiVersion
221
222 def ensure(self):
223 """Manage uplink portgroup"""
224 changed = changed_uplink_pg_policy = changed_vlan_trunk_range = changed_lacp = False
225 results = dict(changed=changed)
226 results['dvswitch'] = self.switch_name
227 changed_list = []
228 message = ''
229
230 uplink_pg_spec = vim.dvs.DistributedVirtualPortgroup.ConfigSpec()
231 # Use the same version in the new spec; The version will be increased by one by the API automatically
232 uplink_pg_spec.configVersion = self.dvs.config.uplinkPortgroup[0].config.configVersion
233 uplink_pg_config = self.dvs.config.uplinkPortgroup[0].config
234
235 # Check name
236 if self.uplink_pg_name:
237 results['name'] = self.uplink_pg_name
238 if uplink_pg_config.name != self.uplink_pg_name:
239 changed = True
240 changed_list.append("name")
241 results['name_previous'] = uplink_pg_config.name
242 uplink_pg_spec.name = self.uplink_pg_name
243 else:
244 results['name'] = uplink_pg_config.name
245
246 # Check description
247 results['description'] = self.uplink_pg_description
248 if uplink_pg_config.description != self.uplink_pg_description:
249 changed = True
250 changed_list.append("description")
251 results['description_previous'] = uplink_pg_config.description
252 uplink_pg_spec.description = self.uplink_pg_description
253
254 # Check port policies
255 results['adv_reset_at_disconnect'] = self.uplink_pg_reset
256 results['adv_block_ports'] = self.uplink_pg_block_ports
257 results['adv_vendor_conf'] = self.uplink_pg_vendor_conf
258 results['adv_vlan'] = self.uplink_pg_vlan
259 results['adv_netflow'] = self.uplink_pg_netflow
260 results['adv_traffic_filtering'] = self.uplink_pg_tf
261 uplink_pg_policy_spec = vim.dvs.VmwareDistributedVirtualSwitch.VMwarePortgroupPolicy()
262 uplink_pg_policy_spec.portConfigResetAtDisconnect = self.uplink_pg_reset
263 uplink_pg_policy_spec.blockOverrideAllowed = self.uplink_pg_block_ports
264 uplink_pg_policy_spec.vendorConfigOverrideAllowed = self.uplink_pg_vendor_conf
265 uplink_pg_policy_spec.vlanOverrideAllowed = self.uplink_pg_vlan
266 uplink_pg_policy_spec.ipfixOverrideAllowed = self.uplink_pg_netflow
267 uplink_pg_policy_spec.trafficFilterOverrideAllowed = self.uplink_pg_tf
268 # There's no information available if the following option are deprecated, but
269 # they aren't visible in the vSphere Client
270 uplink_pg_policy_spec.shapingOverrideAllowed = False
271 uplink_pg_policy_spec.livePortMovingAllowed = False
272 uplink_pg_policy_spec.uplinkTeamingOverrideAllowed = False
273 uplink_pg_policy_spec.macManagementOverrideAllowed = False
274 uplink_pg_policy_spec.networkResourcePoolOverrideAllowed = False
275 # Check policies
276 if uplink_pg_config.policy.portConfigResetAtDisconnect != self.uplink_pg_reset:
277 changed_uplink_pg_policy = True
278 results['adv_reset_at_disconnect_previous'] = uplink_pg_config.policy.portConfigResetAtDisconnect
279 if uplink_pg_config.policy.blockOverrideAllowed != self.uplink_pg_block_ports:
280 changed_uplink_pg_policy = True
281 results['adv_block_ports_previous'] = uplink_pg_config.policy.blockOverrideAllowed
282 if uplink_pg_config.policy.vendorConfigOverrideAllowed != self.uplink_pg_vendor_conf:
283 changed_uplink_pg_policy = True
284 results['adv_vendor_conf_previous'] = uplink_pg_config.policy.vendorConfigOverrideAllowed
285 if uplink_pg_config.policy.vlanOverrideAllowed != self.uplink_pg_vlan:
286 changed_uplink_pg_policy = True
287 results['adv_vlan_previous'] = uplink_pg_config.policy.vlanOverrideAllowed
288 if uplink_pg_config.policy.ipfixOverrideAllowed != self.uplink_pg_netflow:
289 changed_uplink_pg_policy = True
290 results['adv_netflow_previous'] = uplink_pg_config.policy.ipfixOverrideAllowed
291 if uplink_pg_config.policy.trafficFilterOverrideAllowed != self.uplink_pg_tf:
292 changed_uplink_pg_policy = True
293 results['adv_traffic_filtering_previous'] = uplink_pg_config.policy.trafficFilterOverrideAllowed
294 if changed_uplink_pg_policy:
295 changed = True
296 changed_list.append("advanced")
297 uplink_pg_spec.policy = uplink_pg_policy_spec
298
299 uplink_pg_spec.defaultPortConfig = vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
300
301 # Check VLAN trunk
302 results['vlan_trunk_range'] = self.uplink_pg_vlan_trunk_range
303 vlan_id_ranges = self.uplink_pg_vlan_trunk_range
304 trunk_vlan_spec = vim.dvs.VmwareDistributedVirtualSwitch.TrunkVlanSpec()
305 vlan_id_list = []
306 for vlan_id_range in vlan_id_ranges:
307 vlan_id_range_found = False
308 vlan_id_start, vlan_id_end = self.get_vlan_ids_from_range(vlan_id_range)
309 # Check if range is already configured
310 for current_vlan_id_range in uplink_pg_config.defaultPortConfig.vlan.vlanId:
311 if current_vlan_id_range.start == int(vlan_id_start) and current_vlan_id_range.end == int(vlan_id_end):
312 vlan_id_range_found = True
313 break
314 if vlan_id_range_found is False:
315 changed_vlan_trunk_range = True
316 vlan_id_list.append(
317 vim.NumericRange(start=int(vlan_id_start), end=int(vlan_id_end))
318 )
319 # Check if range needs to be removed
320 for current_vlan_id_range in uplink_pg_config.defaultPortConfig.vlan.vlanId:
321 vlan_id_range_found = False
322 for vlan_id_range in vlan_id_ranges:
323 vlan_id_start, vlan_id_end = self.get_vlan_ids_from_range(vlan_id_range)
324 if (current_vlan_id_range.start == int(vlan_id_start)
325 and current_vlan_id_range.end == int(vlan_id_end)):
326 vlan_id_range_found = True
327 break
328 if vlan_id_range_found is False:
329 changed_vlan_trunk_range = True
330 trunk_vlan_spec.vlanId = vlan_id_list
331 if changed_vlan_trunk_range:
332 changed = True
333 changed_list.append("vlan trunk range")
334 current_vlan_id_list = []
335 for current_vlan_id_range in uplink_pg_config.defaultPortConfig.vlan.vlanId:
336 if current_vlan_id_range.start == current_vlan_id_range.end:
337 current_vlan_id_range_string = current_vlan_id_range.start
338 else:
339 current_vlan_id_range_string = '-'.join(
340 [str(current_vlan_id_range.start), str(current_vlan_id_range.end)]
341 )
342 current_vlan_id_list.append(current_vlan_id_range_string)
343 results['vlan_trunk_range_previous'] = current_vlan_id_list
344 uplink_pg_spec.defaultPortConfig.vlan = trunk_vlan_spec
345
346 # Check LACP
347 lacp_support_mode = self.get_lacp_support_mode(self.support_mode)
348 if lacp_support_mode == 'basic':
349 results['lacp_status'] = self.lacp_status
350 lacp_spec = vim.dvs.VmwareDistributedVirtualSwitch.UplinkLacpPolicy()
351 lacp_enabled = False
352 if self.lacp_status == 'enabled':
353 lacp_enabled = True
354 if uplink_pg_config.defaultPortConfig.lacpPolicy.enable.value != lacp_enabled:
355 changed_lacp = True
356 changed_list.append("lacp status")
357 if uplink_pg_config.defaultPortConfig.lacpPolicy.enable.value:
358 results['lacp_status_previous'] = 'enabled'
359 else:
360 results['lacp_status_previous'] = 'disabled'
361 lacp_spec.enable = vim.BoolPolicy()
362 lacp_spec.enable.inherited = False
363 lacp_spec.enable.value = lacp_enabled
364 if lacp_enabled and uplink_pg_config.defaultPortConfig.lacpPolicy.mode.value != self.lacp_mode:
365 results['lacp_mode'] = self.lacp_mode
366 changed_lacp = True
367 changed_list.append("lacp mode")
368 results['lacp_mode_previous'] = uplink_pg_config.defaultPortConfig.lacpPolicy.mode.value
369 lacp_spec.mode = vim.StringPolicy()
370 lacp_spec.mode.inherited = False
371 lacp_spec.mode.value = self.lacp_mode
372 if changed_lacp:
373 changed = True
374 uplink_pg_spec.defaultPortConfig.lacpPolicy = lacp_spec
375
376 # Check NetFlow
377 results['netflow_enabled'] = self.uplink_pg_netflow_enabled
378 netflow_enabled_spec = vim.BoolPolicy()
379 netflow_enabled_spec.inherited = False
380 netflow_enabled_spec.value = self.uplink_pg_netflow_enabled
381 if uplink_pg_config.defaultPortConfig.ipfixEnabled.value != self.uplink_pg_netflow_enabled:
382 changed = True
383 results['netflow_enabled_previous'] = uplink_pg_config.defaultPortConfig.ipfixEnabled.value
384 changed_list.append("netflow")
385 uplink_pg_spec.defaultPortConfig.ipfixEnabled = netflow_enabled_spec
386
387 # TODO: Check Traffic filtering and marking
388
389 # Check Block all ports
390 results['block_all_ports'] = self.uplink_pg_block_all_ports
391 block_all_ports_spec = vim.BoolPolicy()
392 block_all_ports_spec.inherited = False
393 block_all_ports_spec.value = self.uplink_pg_block_all_ports
394 if uplink_pg_config.defaultPortConfig.blocked.value != self.uplink_pg_block_all_ports:
395 changed = True
396 changed_list.append("block all ports")
397 results['block_all_ports_previous'] = uplink_pg_config.defaultPortConfig.blocked.value
398 uplink_pg_spec.defaultPortConfig.blocked = block_all_ports_spec
399
400 if changed:
401 if self.module.check_mode:
402 changed_suffix = ' would be changed'
403 else:
404 changed_suffix = ' changed'
405 if len(changed_list) > 2:
406 message = ', '.join(changed_list[:-1]) + ', and ' + str(changed_list[-1])
407 elif len(changed_list) == 2:
408 message = ' and '.join(changed_list)
409 elif len(changed_list) == 1:
410 message = changed_list[0]
411 message += changed_suffix
412 if not self.module.check_mode:
413 try:
414 task = self.dvs.config.uplinkPortgroup[0].ReconfigureDVPortgroup_Task(uplink_pg_spec)
415 wait_for_task(task)
416 except TaskError as invalid_argument:
417 self.module.fail_json(msg="Failed to update uplink portgroup : %s" % to_native(invalid_argument))
418 else:
419 message = "Uplink portgroup already configured properly"
420 results['changed'] = changed
421 results['result'] = message
422
423 self.module.exit_json(**results)
424
425 @staticmethod
426 def get_vlan_ids_from_range(vlan_id_range):
427 """Get start and end VLAN ID from VLAN ID range"""
428 try:
429 vlan_id_start, vlan_id_end = vlan_id_range.split('-')
430 except (AttributeError, TypeError):
431 vlan_id_start = vlan_id_end = vlan_id_range
432 except ValueError:
433 vlan_id_start = vlan_id_end = vlan_id_range.strip()
434 return vlan_id_start, vlan_id_end
435
436 @staticmethod
437 def get_lacp_support_mode(mode):
438 """Get LACP support mode"""
439 return_mode = None
440 if mode == 'basic':
441 return_mode = 'singleLag'
442 elif mode == 'enhanced':
443 return_mode = 'multipleLag'
444 elif mode == 'singleLag':
445 return_mode = 'basic'
446 elif mode == 'multipleLag':
447 return_mode = 'enhanced'
448 return return_mode
449
450
451 def main():
452 """Main"""
453 argument_spec = base_argument_spec()
454 argument_spec.update(
455 dict(
456 switch=dict(required=True, aliases=['dvswitch']),
457 name=dict(type='str'),
458 description=dict(type='str'),
459 advanced=dict(
460 type='dict',
461 options=dict(
462 port_config_reset_at_disconnect=dict(type='bool', default=True),
463 block_override=dict(type='bool', default=True),
464 vendor_config_override=dict(type='bool', default=False),
465 vlan_override=dict(type='bool', default=False),
466 netflow_override=dict(type='bool', default=False),
467 traffic_filter_override=dict(type='bool', default=False),
468 ),
469 default=dict(
470 port_config_reset_at_disconnect=True,
471 block_override=True,
472 vendor_config_override=False,
473 vlan_override=False,
474 netflow_override=False,
475 traffic_filter_override=False,
476 ),
477 aliases=['port_policy'],
478 ),
479 lacp=dict(
480 type='dict',
481 options=dict(
482 status=dict(type='str', choices=['enabled', 'disabled'], default='disabled'),
483 mode=dict(type='str', choices=['active', 'passive'], default='passive'),
484 ),
485 default=dict(
486 status='disabled',
487 mode='passive',
488 ),
489 ),
490 vlan_trunk_range=dict(type='list', default=['0-4094'], elements='str'),
491 netflow_enabled=dict(type='bool', default=False),
492 block_all_ports=dict(type='bool', default=False),
493 )
494 )
495
496 module = AnsibleModule(
497 argument_spec=argument_spec,
498 supports_check_mode=True,
499 )
500
501 vmware_dvswitch_uplink_pg = VMwareDvSwitchUplinkPortgroup(module)
502 vmware_dvswitch_uplink_pg.ensure()
503
504
505 if __name__ == '__main__':
506 main()