Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_dvswitch_pvlans.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_pvlans
15 short_description: Manage Private VLAN configuration of a Distributed Switch
16 description:
17 - This module can be used to configure Private VLANs (PVLANs) on 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 primary_pvlans:
28 description:
29 - A list of VLAN IDs that should be configured as Primary PVLANs.
30 - If not specified, all PVLANs will be deleted if present.
31 - Each member of the list requires primary_pvlan_id (int) set.
32 - The secondary promiscuous PVLAN will be created automatically.
33 - If O(secondary_pvlans) isn't specified, the primary PVLANs and each secondary promiscuous PVLAN will be created.
34 - Please see examples for more information.
35 type: list
36 default: []
37 elements: dict
38 suboptions:
39 primary_pvlan_id:
40 description:
41 - The primary VLAN ID.
42 - The VLAN IDs of 0 and 4095 are reserved and cannot be used in this option.
43 type: int
44 secondary_pvlans:
45 description:
46 - A list of VLAN IDs that should be configured as Secondary PVLANs.
47 - 'O(primary_pvlans) need to be specified to create any Secondary PVLAN.'
48 - If O(primary_pvlans) isn't specified, all PVLANs will be deleted if present.
49 - Each member of the list requires primary_pvlan_id (int), secondary_pvlan_id (int), and pvlan_type (str) to be set.
50 - The type of the secondary PVLAN can be isolated or community. The secondary promiscuous PVLAN will be created automatically.
51 - Please see examples for more information.
52 type: list
53 default: []
54 elements: dict
55 suboptions:
56 primary_pvlan_id:
57 description:
58 - The primary VLAN ID.
59 - The VLAN IDs of 0 and 4095 are reserved and cannot be used in this option.
60 type: int
61 secondary_pvlan_id:
62 description:
63 - The type of PVLAN.
64 type: int
65 pvlan_type:
66 description:
67 - The secondary VLAN ID.
68 - The VLAN IDs of 0 and 4095 are reserved and cannot be used in this option.
69 choices:
70 - community
71 - isolated
72 type: str
73 extends_documentation_fragment:
74 - vmware.vmware.base_options
75 '''
76
77 EXAMPLES = r'''
78 - name: Create PVLANs on a Distributed Switch
79 community.vmware.vmware_dvswitch_pvlans:
80 hostname: '{{ inventory_hostname }}'
81 username: '{{ vcenter_username }}'
82 password: '{{ vcenter_password }}'
83 switch: dvSwitch
84 primary_pvlans:
85 - primary_pvlan_id: 1
86 - primary_pvlan_id: 4
87 secondary_pvlans:
88 - primary_pvlan_id: 1
89 secondary_pvlan_id: 2
90 pvlan_type: isolated
91 - primary_pvlan_id: 1
92 secondary_pvlan_id: 3
93 pvlan_type: community
94 - primary_pvlan_id: 4
95 secondary_pvlan_id: 5
96 pvlan_type: community
97 delegate_to: localhost
98
99 - name: Create primary PVLAN and secondary promiscuous PVLAN on a Distributed Switch
100 community.vmware.vmware_dvswitch_pvlans:
101 hostname: '{{ inventory_hostname }}'
102 username: '{{ vcenter_username }}'
103 password: '{{ vcenter_password }}'
104 switch: dvSwitch
105 primary_pvlans:
106 - primary_pvlan_id: 1
107 delegate_to: localhost
108
109 - name: Remove all PVLANs from a Distributed Switch
110 community.vmware.vmware_dvswitch_pvlans:
111 hostname: '{{ inventory_hostname }}'
112 username: '{{ vcenter_username }}'
113 password: '{{ vcenter_password }}'
114 switch: dvSwitch
115 primary_pvlans: []
116 secondary_pvlans: []
117 delegate_to: localhost
118 '''
119
120 RETURN = r'''
121 result:
122 description: information about performed operation
123 returned: always
124 type: str
125 sample: {
126 "changed": true,
127 "dvswitch": "dvSwitch",
128 "private_vlans": [
129 {
130 "primary_pvlan_id": 1,
131 "pvlan_type": "promiscuous",
132 "secondary_pvlan_id": 1
133 },
134 {
135 "primary_pvlan_id": 1,
136 "pvlan_type": "isolated",
137 "secondary_pvlan_id": 2
138 },
139 {
140 "primary_pvlan_id": 1,
141 "pvlan_type": "community",
142 "secondary_pvlan_id": 3
143 }
144 ],
145 "private_vlans_previous": [],
146 "result": "All private VLANs added"
147 }
148 '''
149
150 try:
151 from pyVmomi import vim
152 except ImportError:
153 pass
154
155 from ansible.module_utils.basic import AnsibleModule
156 from ansible.module_utils.common.text.converters import to_native
157 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
158 PyVmomi, TaskError, find_dvs_by_name, wait_for_task
159 )
160 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
161
162
163 class VMwareDvSwitchPvlans(PyVmomi):
164 """Class to manage Private VLANs on a Distributed Virtual Switch"""
165
166 def __init__(self, module):
167 super(VMwareDvSwitchPvlans, self).__init__(module)
168 self.switch_name = self.module.params['switch']
169 if self.module.params['primary_pvlans']:
170 self.primary_pvlans = self.module.params['primary_pvlans']
171 if self.module.params['secondary_pvlans']:
172 self.secondary_pvlans = self.module.params['secondary_pvlans']
173 else:
174 self.secondary_pvlans = None
175 self.do_pvlan_sanity_checks()
176 else:
177 self.primary_pvlans = None
178 self.secondary_pvlans = None
179 self.dvs = find_dvs_by_name(self.content, self.switch_name)
180 if self.dvs is None:
181 self.module.fail_json(msg="Failed to find DVS %s" % self.switch_name)
182
183 def do_pvlan_sanity_checks(self):
184 """Do sanity checks for primary and secondary PVLANs"""
185 # Check if primary PVLANs are unique
186 for primary_vlan in self.primary_pvlans:
187 count = 0
188 primary_pvlan_id = self.get_primary_pvlan_option(primary_vlan)
189 for primary_vlan_2 in self.primary_pvlans:
190 primary_pvlan_id_2 = self.get_primary_pvlan_option(primary_vlan_2)
191 if primary_pvlan_id == primary_pvlan_id_2:
192 count += 1
193 if count > 1:
194 self.module.fail_json(
195 msg="The primary PVLAN ID '%s' must be unique!" % primary_pvlan_id
196 )
197 if self.secondary_pvlans:
198 # Check if secondary PVLANs are unique
199 for secondary_pvlan in self.secondary_pvlans:
200 count = 0
201 result = self.get_secondary_pvlan_options(secondary_pvlan)
202 for secondary_pvlan_2 in self.secondary_pvlans:
203 result_2 = self.get_secondary_pvlan_options(secondary_pvlan_2)
204 if result[0] == result_2[0]:
205 count += 1
206 if count > 1:
207 self.module.fail_json(
208 msg="The secondary PVLAN ID '%s' must be unique!" % result[0]
209 )
210 # Check if secondary PVLANs are already used as primary PVLANs
211 for primary_vlan in self.primary_pvlans:
212 primary_pvlan_id = self.get_primary_pvlan_option(primary_vlan)
213 for secondary_pvlan in self.secondary_pvlans:
214 result = self.get_secondary_pvlan_options(secondary_pvlan)
215 if primary_pvlan_id == result[0]:
216 self.module.fail_json(
217 msg="The secondary PVLAN ID '%s' is already used as a primary PVLAN!" %
218 result[0]
219 )
220 # Check if a primary PVLAN is present for every secondary PVLANs
221 for secondary_pvlan in self.secondary_pvlans:
222 primary_pvlan_found = False
223 result = self.get_secondary_pvlan_options(secondary_pvlan)
224 for primary_vlan in self.primary_pvlans:
225 primary_pvlan_id = self.get_primary_pvlan_option(primary_vlan)
226 if result[1] == primary_pvlan_id:
227 primary_pvlan_found = True
228 break
229 if not primary_pvlan_found:
230 self.module.fail_json(
231 msg="The primary PVLAN ID '%s' isn't defined for the secondary PVLAN ID '%s'!" %
232 (result[1], result[0])
233 )
234
235 def ensure(self):
236 """Manage Private VLANs"""
237 changed = False
238 results = dict(changed=changed)
239 results['dvswitch'] = self.switch_name
240 changed_list_add = []
241 changed_list_remove = []
242
243 config_spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
244 # Use the same version in the new spec; The version will be increased by one by the API automatically
245 config_spec.configVersion = self.dvs.config.configVersion
246
247 # Check Private VLANs
248 results['private_vlans'] = None
249 if self.primary_pvlans:
250 desired_pvlan_list = []
251 for primary_vlan in self.primary_pvlans:
252 primary_pvlan_id = self.get_primary_pvlan_option(primary_vlan)
253 temp_pvlan = dict()
254 temp_pvlan['primary_pvlan_id'] = primary_pvlan_id
255 temp_pvlan['secondary_pvlan_id'] = primary_pvlan_id
256 temp_pvlan['pvlan_type'] = 'promiscuous'
257 desired_pvlan_list.append(temp_pvlan)
258 if self.secondary_pvlans:
259 for secondary_pvlan in self.secondary_pvlans:
260 (secondary_pvlan_id,
261 secondary_vlan_primary_vlan_id,
262 pvlan_type) = self.get_secondary_pvlan_options(secondary_pvlan)
263 temp_pvlan = dict()
264 temp_pvlan['primary_pvlan_id'] = secondary_vlan_primary_vlan_id
265 temp_pvlan['secondary_pvlan_id'] = secondary_pvlan_id
266 temp_pvlan['pvlan_type'] = pvlan_type
267 desired_pvlan_list.append(temp_pvlan)
268 results['private_vlans'] = desired_pvlan_list
269 if self.dvs.config.pvlanConfig:
270 pvlan_spec_list = []
271 # Check if desired PVLANs are configured
272 for primary_vlan in self.primary_pvlans:
273 primary_pvlan_id = self.get_primary_pvlan_option(primary_vlan)
274 promiscuous_found = other_found = False
275 for pvlan_object in self.dvs.config.pvlanConfig:
276 if pvlan_object.primaryVlanId == primary_pvlan_id and pvlan_object.pvlanType == 'promiscuous':
277 promiscuous_found = True
278 break
279 if not promiscuous_found:
280 changed = True
281 changed_list_add.append('promiscuous (%s, %s)' % (primary_pvlan_id, primary_pvlan_id))
282 pvlan_spec_list.append(
283 self.create_pvlan_config_spec(
284 operation='add',
285 primary_pvlan_id=primary_pvlan_id,
286 secondary_pvlan_id=primary_pvlan_id,
287 pvlan_type='promiscuous'
288 )
289 )
290 if self.secondary_pvlans:
291 for secondary_pvlan in self.secondary_pvlans:
292 (secondary_pvlan_id,
293 secondary_vlan_primary_vlan_id,
294 pvlan_type) = self.get_secondary_pvlan_options(secondary_pvlan)
295 if primary_pvlan_id == secondary_vlan_primary_vlan_id:
296 for pvlan_object_2 in self.dvs.config.pvlanConfig:
297 if (pvlan_object_2.primaryVlanId == secondary_vlan_primary_vlan_id
298 and pvlan_object_2.secondaryVlanId == secondary_pvlan_id
299 and pvlan_object_2.pvlanType == pvlan_type):
300 other_found = True
301 break
302 if not other_found:
303 changed = True
304 changed_list_add.append(
305 '%s (%s, %s)' % (pvlan_type, primary_pvlan_id, secondary_pvlan_id)
306 )
307 pvlan_spec_list.append(
308 self.create_pvlan_config_spec(
309 operation='add',
310 primary_pvlan_id=primary_pvlan_id,
311 secondary_pvlan_id=secondary_pvlan_id,
312 pvlan_type=pvlan_type
313 )
314 )
315 # Check if a PVLAN needs to be removed
316 for pvlan_object in self.dvs.config.pvlanConfig:
317 promiscuous_found = other_found = False
318 if (pvlan_object.primaryVlanId == pvlan_object.secondaryVlanId
319 and pvlan_object.pvlanType == 'promiscuous'):
320 for primary_vlan in self.primary_pvlans:
321 primary_pvlan_id = self.get_primary_pvlan_option(primary_vlan)
322 if pvlan_object.primaryVlanId == primary_pvlan_id and pvlan_object.pvlanType == 'promiscuous':
323 promiscuous_found = True
324 break
325 if not promiscuous_found:
326 changed = True
327 changed_list_remove.append(
328 'promiscuous (%s, %s)' % (pvlan_object.primaryVlanId, pvlan_object.secondaryVlanId)
329 )
330 pvlan_spec_list.append(
331 self.create_pvlan_config_spec(
332 operation='remove',
333 primary_pvlan_id=pvlan_object.primaryVlanId,
334 secondary_pvlan_id=pvlan_object.secondaryVlanId,
335 pvlan_type='promiscuous'
336 )
337 )
338 elif self.secondary_pvlans:
339 for secondary_pvlan in self.secondary_pvlans:
340 (secondary_pvlan_id,
341 secondary_vlan_primary_vlan_id,
342 pvlan_type) = self.get_secondary_pvlan_options(secondary_pvlan)
343 if (pvlan_object.primaryVlanId == secondary_vlan_primary_vlan_id
344 and pvlan_object.secondaryVlanId == secondary_pvlan_id
345 and pvlan_object.pvlanType == pvlan_type):
346 other_found = True
347 break
348 if not other_found:
349 changed = True
350 changed_list_remove.append(
351 '%s (%s, %s)' % (
352 pvlan_object.pvlanType, pvlan_object.primaryVlanId, pvlan_object.secondaryVlanId
353 )
354 )
355 pvlan_spec_list.append(
356 self.create_pvlan_config_spec(
357 operation='remove',
358 primary_pvlan_id=pvlan_object.primaryVlanId,
359 secondary_pvlan_id=pvlan_object.secondaryVlanId,
360 pvlan_type=pvlan_object.pvlanType
361 )
362 )
363 else:
364 changed = True
365 changed_list_remove.append(
366 '%s (%s, %s)' % (
367 pvlan_object.pvlanType, pvlan_object.primaryVlanId, pvlan_object.secondaryVlanId
368 )
369 )
370 pvlan_spec_list.append(
371 self.create_pvlan_config_spec(
372 operation='remove',
373 primary_pvlan_id=pvlan_object.primaryVlanId,
374 secondary_pvlan_id=pvlan_object.secondaryVlanId,
375 pvlan_type=pvlan_object.pvlanType
376 )
377 )
378 else:
379 changed = True
380 changed_list_add.append('All private VLANs')
381 pvlan_spec_list = []
382 for primary_vlan in self.primary_pvlans:
383 # the first secondary VLAN's type is always promiscuous
384 primary_pvlan_id = self.get_primary_pvlan_option(primary_vlan)
385 pvlan_spec_list.append(
386 self.create_pvlan_config_spec(
387 operation='add',
388 primary_pvlan_id=primary_pvlan_id,
389 secondary_pvlan_id=primary_pvlan_id,
390 pvlan_type='promiscuous'
391 )
392 )
393 if self.secondary_pvlans:
394 for secondary_pvlan in self.secondary_pvlans:
395 (secondary_pvlan_id,
396 secondary_vlan_primary_vlan_id,
397 pvlan_type) = self.get_secondary_pvlan_options(secondary_pvlan)
398 if primary_pvlan_id == secondary_vlan_primary_vlan_id:
399 pvlan_spec_list.append(
400 self.create_pvlan_config_spec(
401 operation='add',
402 primary_pvlan_id=primary_pvlan_id,
403 secondary_pvlan_id=secondary_pvlan_id,
404 pvlan_type=pvlan_type
405 )
406 )
407 else:
408 # Remove PVLAN configuration if present
409 if self.dvs.config.pvlanConfig:
410 changed = True
411 changed_list_remove.append('All private VLANs')
412 pvlan_spec_list = []
413 for pvlan_object in self.dvs.config.pvlanConfig:
414 pvlan_spec_list.append(
415 self.create_pvlan_config_spec(
416 operation='remove',
417 primary_pvlan_id=pvlan_object.primaryVlanId,
418 secondary_pvlan_id=pvlan_object.secondaryVlanId,
419 pvlan_type=pvlan_object.pvlanType
420 )
421 )
422
423 if changed:
424 message_add = message_remove = None
425 if changed_list_add:
426 message_add = self.build_change_message('add', changed_list_add)
427 if changed_list_remove:
428 message_remove = self.build_change_message('remove', changed_list_remove)
429 if message_add and message_remove:
430 message = message_add + '. ' + message_remove + '.'
431 elif message_add:
432 message = message_add
433 elif message_remove:
434 message = message_remove
435 current_pvlan_list = []
436 for pvlan_object in self.dvs.config.pvlanConfig:
437 temp_pvlan = dict()
438 temp_pvlan['primary_pvlan_id'] = pvlan_object.primaryVlanId
439 temp_pvlan['secondary_pvlan_id'] = pvlan_object.secondaryVlanId
440 temp_pvlan['pvlan_type'] = pvlan_object.pvlanType
441 current_pvlan_list.append(temp_pvlan)
442 results['private_vlans_previous'] = current_pvlan_list
443 config_spec.pvlanConfigSpec = pvlan_spec_list
444 if not self.module.check_mode:
445 try:
446 task = self.dvs.ReconfigureDvs_Task(config_spec)
447 wait_for_task(task)
448 except TaskError as invalid_argument:
449 self.module.fail_json(
450 msg="Failed to update DVS : %s" % to_native(invalid_argument)
451 )
452 else:
453 message = "PVLANs already configured properly"
454 results['changed'] = changed
455 results['result'] = message
456
457 self.module.exit_json(**results)
458
459 def get_primary_pvlan_option(self, primary_vlan):
460 """Get Primary PVLAN option"""
461 primary_pvlan_id = primary_vlan.get('primary_pvlan_id', None)
462 if primary_pvlan_id is None:
463 self.module.fail_json(
464 msg="Please specify primary_pvlan_id in primary_pvlans options as it's a required parameter"
465 )
466 if primary_pvlan_id in (0, 4095):
467 self.module.fail_json(msg="The VLAN IDs of 0 and 4095 are reserved and cannot be used as a primary PVLAN.")
468 return primary_pvlan_id
469
470 def get_secondary_pvlan_options(self, secondary_pvlan):
471 """Get Secondary PVLAN option"""
472 secondary_pvlan_id = secondary_pvlan.get('secondary_pvlan_id', None)
473 if secondary_pvlan_id is None:
474 self.module.fail_json(
475 msg="Please specify secondary_pvlan_id in secondary_pvlans options as it's a required parameter"
476 )
477 primary_pvlan_id = secondary_pvlan.get('primary_pvlan_id', None)
478 if primary_pvlan_id is None:
479 self.module.fail_json(
480 msg="Please specify primary_pvlan_id in secondary_pvlans options as it's a required parameter"
481 )
482 if secondary_pvlan_id in (0, 4095) or primary_pvlan_id in (0, 4095):
483 self.module.fail_json(
484 msg="The VLAN IDs of 0 and 4095 are reserved and cannot be used as a primary or secondary PVLAN."
485 )
486 pvlan_type = secondary_pvlan.get('pvlan_type', None)
487 supported_pvlan_types = ['isolated', 'community']
488 if pvlan_type is None:
489 self.module.fail_json(msg="Please specify pvlan_type in secondary_pvlans options as it's a required parameter")
490 elif pvlan_type not in supported_pvlan_types:
491 self.module.fail_json(msg="The specified PVLAN type '%s' isn't supported!" % pvlan_type)
492 return secondary_pvlan_id, primary_pvlan_id, pvlan_type
493
494 @staticmethod
495 def create_pvlan_config_spec(operation, primary_pvlan_id, secondary_pvlan_id, pvlan_type):
496 """
497 Create PVLAN config spec
498 operation: add, edit, or remove
499 Returns: PVLAN config spec
500 """
501 pvlan_spec = vim.dvs.VmwareDistributedVirtualSwitch.PvlanConfigSpec()
502 pvlan_spec.operation = operation
503 pvlan_spec.pvlanEntry = vim.dvs.VmwareDistributedVirtualSwitch.PvlanMapEntry()
504 pvlan_spec.pvlanEntry.primaryVlanId = primary_pvlan_id
505 pvlan_spec.pvlanEntry.secondaryVlanId = secondary_pvlan_id
506 pvlan_spec.pvlanEntry.pvlanType = pvlan_type
507 return pvlan_spec
508
509 def build_change_message(self, operation, changed_list):
510 """Build the changed message"""
511 message = None
512 if operation == 'add':
513 changed_operation = 'added'
514 elif operation == 'remove':
515 changed_operation = 'removed'
516 if self.module.check_mode:
517 changed_suffix = ' would be %s' % changed_operation
518 else:
519 changed_suffix = ' %s' % changed_operation
520 if len(changed_list) > 2:
521 message = ', '.join(changed_list[:-1]) + ', and ' + str(changed_list[-1])
522 elif len(changed_list) == 2:
523 message = ' and '.join(changed_list)
524 elif len(changed_list) == 1:
525 message = changed_list[0]
526 message += changed_suffix
527 return message
528
529
530 def main():
531 """Main"""
532 argument_spec = base_argument_spec()
533 argument_spec.update(
534 dict(
535 switch=dict(required=True, aliases=['dvswitch']),
536 primary_pvlans=dict(type='list', default=list(), elements='dict',
537 options=dict(
538 primary_pvlan_id=dict(type='int')
539 )),
540 secondary_pvlans=dict(type='list', default=list(), elements='dict',
541 options=dict(
542 primary_pvlan_id=dict(type='int'),
543 secondary_pvlan_id=dict(type='int'),
544 pvlan_type=dict(type='str', choices=['community', 'isolated'])
545 )),
546 )
547 )
548
549 module = AnsibleModule(
550 argument_spec=argument_spec,
551 supports_check_mode=True,
552 )
553
554 vmware_dvswitch_pvlans = VMwareDvSwitchPvlans(module)
555 vmware_dvswitch_pvlans.ensure()
556
557
558 if __name__ == '__main__':
559 main()