Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2015, Joseph Callen <jcallen () csc.com>
5 # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
6 # Copyright: (c) 2018, Christian Kotte <[email protected]>
7 # Copyright: (c) 2018, Ansible Project
8 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
9 # SPDX-License-Identifier: GPL-3.0-or-later
10
11 from __future__ import absolute_import, division, print_function
12 __metaclass__ = type
13
14
15 DOCUMENTATION = r'''
16 ---
17 module: vmware_dvswitch
18 short_description: Create or remove a Distributed Switch
19 description:
20 - This module can be used to create, remove a Distributed Switch.
21 author:
22 - Joseph Callen (@jcpowermac)
23 - Abhijeet Kasurde (@Akasurde)
24 - Christian Kotte (@ckotte)
25 options:
26 datacenter_name:
27 description:
28 - The name of the datacenter that will contain the Distributed Switch.
29 - Required if O(folder) is not provided.
30 - Mutually exclusive with O(folder) parameter.
31 required: false
32 aliases: ['datacenter']
33 type: str
34 switch_name:
35 description:
36 - The name of the distribute vSwitch to create or remove.
37 required: true
38 aliases: ['switch', 'dvswitch']
39 type: str
40 switch_version:
41 description:
42 - The version of the Distributed Switch to create.
43 - The version must match the version of the ESXi hosts you want to connect.
44 - The version of the vCenter server is used if not specified.
45 - Required if O(state=present).
46 aliases: ['version']
47 type: str
48 mtu:
49 description:
50 - The switch maximum transmission unit.
51 - Required if O(state=present).
52 - Accepts value between 1280 to 9000 (both inclusive).
53 type: int
54 default: 1500
55 multicast_filtering_mode:
56 description:
57 - The multicast filtering mode.
58 - 'V(basic) mode: multicast traffic for virtual machines is forwarded according to the destination MAC address of the multicast group.'
59 - 'V(snooping) mode: the Distributed Switch provides IGMP and MLD snooping according to RFC 4541.'
60 type: str
61 choices: ['basic', 'snooping']
62 default: 'basic'
63 uplink_quantity:
64 description:
65 - Quantity of uplink per ESXi host added to the Distributed Switch.
66 - The uplink quantity can be increased or decreased, but a decrease will only be successfull if the uplink isn't used by a portgroup.
67 - Required if O(state=present).
68 type: int
69 uplink_prefix:
70 description:
71 - The prefix used for the naming of the uplinks.
72 - Only valid if the Distributed Switch will be created. Not used if the Distributed Switch is already present.
73 - Uplinks are created as Uplink 1, Uplink 2, etc. pp. by default.
74 default: 'Uplink '
75 type: str
76 discovery_proto:
77 description:
78 - Link discovery protocol between Cisco and Link Layer discovery.
79 - Required if O(state=present).
80 - 'V(cdp): Use Cisco Discovery Protocol (CDP).'
81 - 'V(lldp): Use Link Layer Discovery Protocol (LLDP).'
82 - 'V(disabled): Do not use a discovery protocol.'
83 choices: ['cdp', 'lldp', 'disabled']
84 default: 'cdp'
85 aliases: [ 'discovery_protocol' ]
86 type: str
87 discovery_operation:
88 description:
89 - Select the discovery operation.
90 - Required if O(state=present).
91 choices: ['both', 'advertise', 'listen']
92 default: 'listen'
93 type: str
94 contact:
95 description:
96 - Dictionary which configures administrator contact name and description for the Distributed Switch.
97 suboptions:
98 name:
99 type: str
100 description: Administrator name.
101 description:
102 type: str
103 description: Description or other details.
104 type: dict
105 description:
106 description:
107 - Description of the Distributed Switch.
108 type: str
109 health_check:
110 description:
111 - Dictionary which configures Health Check for the Distributed Switch.
112 suboptions:
113 vlan_mtu:
114 type: bool
115 description: VLAN and MTU health check.
116 default: false
117 teaming_failover:
118 type: bool
119 description: Teaming and failover health check.
120 default: false
121 vlan_mtu_interval:
122 type: int
123 description:
124 - VLAN and MTU health check interval (minutes).
125 - The default value is 1 in the vSphere Client if the VLAN and MTU health check is enabled.
126 default: 0
127 teaming_failover_interval:
128 type: int
129 description:
130 - Teaming and failover health check interval (minutes).
131 - The default value is 1 in the vSphere Client if the Teaming and failover health check is enabled.
132 default: 0
133 type: dict
134 default: {
135 vlan_mtu: false,
136 teaming_failover: false,
137 vlan_mtu_interval: 0,
138 teaming_failover_interval: 0,
139 }
140 network_policy:
141 description:
142 - Dictionary which configures the different default security values for portgroups.
143 - If set, these options are inherited by the portgroups of the DVS.
144 suboptions:
145 promiscuous:
146 type: bool
147 description: Indicates whether promiscuous mode is allowed.
148 default: false
149 forged_transmits:
150 type: bool
151 description: Indicates whether forged transmits are allowed.
152 default: false
153 mac_changes:
154 type: bool
155 description: Indicates whether mac changes are allowed.
156 default: false
157 required: false
158 type: dict
159 state:
160 description:
161 - If set to V(present) and the Distributed Switch does not exist, the Distributed Switch will be created.
162 - If set to V(absent) and the Distributed Switch exists, the Distributed Switch will be deleted.
163 default: 'present'
164 choices: ['present', 'absent']
165 type: str
166 folder:
167 description:
168 - Destination folder, absolute path to place dvswitch in.
169 - The folder should include the datacenter.
170 - Required if O(datacenter) is not provided.
171 - Mutually exclusive with O(datacenter) parameter.
172 - 'Examples:'
173 - ' folder: /datacenter1/network'
174 - ' folder: datacenter1/network'
175 - ' folder: /datacenter1/network/folder1'
176 - ' folder: datacenter1/network/folder1'
177 - ' folder: /folder1/datacenter1/network'
178 - ' folder: folder1/datacenter1/network'
179 - ' folder: /folder1/datacenter1/network/folder2'
180 required: false
181 type: str
182 net_flow:
183 description:
184 - Dictionary which configures the Net Flow for the Distributed Switch.
185 suboptions:
186 collector_ip:
187 type: str
188 description: The IP Address (IPv4 or IPv6) of the NetFlow collector.
189 collector_port:
190 type: int
191 description: The Port of the NetFlow collector.
192 default: 0
193 observation_domain_id:
194 type: int
195 description: Identifies the information related to the switch.
196 default: 0
197 switch_ip:
198 type: str
199 description:
200 - Assign an IP address to see the distributed switch as a single network device in the NetFlow collector.
201 - This is instead of as multiple devices corresponding to each host.
202 - In an IPv6 environment, the ESXi hosts ignore the switch IP address.
203 version_added: '4.3.0'
204 active_flow_timeout:
205 type: int
206 description: The time, in seconds, to wait before sending information after the flow is initiated.
207 default: 60
208 idle_flow_timeout:
209 type: int
210 description: The time, in seconds, to wait before sending information after the flow is initiated.
211 default: 15
212 sampling_rate:
213 type: int
214 description:
215 - The portion of data that the switch collects.
216 - The sampling rate represents the number of packets that NetFlow drops after every collected packet.
217 - If the rate is 0, NetFlow samples every packet, that is, collect one packet and drop none.
218 - If the rate is 1, NetFlow samples a packet and drops the next one, and so on.
219 default: 4096
220 internal_flows_only:
221 type: bool
222 description: If True, data on network activity between vms on the same host will be collected only.
223 default: false
224 type: dict
225 default: {
226 'collector_port': 0,
227 'observation_domain_id': 0,
228 'active_flow_timeout': 60,
229 'idle_flow_timeout': 15,
230 'sampling_rate': 4096,
231 'internal_flows_only': false
232 }
233 extends_documentation_fragment:
234 - vmware.vmware.base_options
235
236 '''
237
238 EXAMPLES = r'''
239 - name: Create dvSwitch
240 community.vmware.vmware_dvswitch:
241 hostname: '{{ vcenter_hostname }}'
242 username: '{{ vcenter_username }}'
243 password: '{{ vcenter_password }}'
244 datacenter: '{{ datacenter }}'
245 switch: dvSwitch
246 version: 6.0.0
247 mtu: 9000
248 uplink_quantity: 2
249 discovery_protocol: lldp
250 discovery_operation: both
251 state: present
252 delegate_to: localhost
253
254 - name: Create dvSwitch with all options
255 community.vmware.vmware_dvswitch:
256 hostname: '{{ vcenter_hostname }}'
257 username: '{{ vcenter_username }}'
258 password: '{{ vcenter_password }}'
259 datacenter: '{{ datacenter }}'
260 switch: dvSwitch
261 version: 6.5.0
262 mtu: 9000
263 uplink_quantity: 2
264 uplink_prefix: 'Uplink_'
265 discovery_protocol: cdp
266 discovery_operation: both
267 multicast_filtering_mode: snooping
268 health_check:
269 vlan_mtu: true
270 vlan_mtu_interval: 1
271 teaming_failover: true
272 teaming_failover_interval: 1
273 net_flow:
274 collector_ip: 192.168.10.50
275 collector_port: 50034
276 observation_domain_id: 0
277 switch_ip: 192.168.10.40
278 active_flow_timeout: 60
279 idle_flow_timeout: 15
280 sampling_rate: 4096
281 internal_flows_only: false
282 state: present
283 delegate_to: localhost
284
285 - name: Delete dvSwitch
286 community.vmware.vmware_dvswitch:
287 hostname: '{{ vcenter_hostname }}'
288 username: '{{ vcenter_username }}'
289 password: '{{ vcenter_password }}'
290 datacenter: '{{ datacenter }}'
291 switch: dvSwitch
292 state: absent
293 delegate_to: localhost
294 '''
295
296 RETURN = r'''
297 result:
298 description: information about performed operation
299 returned: always
300 type: str
301 sample: {
302 "changed": false,
303 "contact": null,
304 "contact_details": null,
305 "description": null,
306 "discovery_operation": "both",
307 "discovery_protocol": "cdp",
308 "dvswitch": "test",
309 "health_check_teaming": false,
310 "health_check_teaming_interval": 0,
311 "health_check_vlan": false,
312 "health_check_vlan_interval": 0,
313 "net_flow_collector_ip": "192.168.10.50",
314 "net_flow_collector_port": 50034,
315 "net_flow_observation_domain_id": 0,
316 "net_flow_switch_ip": "192.168.10.40",
317 "net_flow_active_flow_timeout": 60,
318 "net_flow_idle_flow_timeout": 15,
319 "net_flow_sampling_rate": 4096,
320 "net_flow_internal_flows_only": false,
321 "mtu": 9000,
322 "multicast_filtering_mode": "basic",
323 "result": "DVS already configured properly",
324 "uplink_quantity": 2,
325 "uplinks": [
326 "Uplink_1",
327 "Uplink_2"
328 ],
329 "version": "6.6.0"
330 }
331 '''
332
333 try:
334 from pyVmomi import vim, vmodl
335 except ImportError:
336 pass
337
338 from ansible.module_utils.basic import AnsibleModule
339 from ansible.module_utils.common.text.converters import to_native
340 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
341 PyVmomi, TaskError, find_dvs_by_name, wait_for_task
342 )
343 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
344
345
346 class VMwareDvSwitch(PyVmomi):
347 """Class to manage a Distributed Virtual Switch"""
348
349 def __init__(self, module):
350 super(VMwareDvSwitch, self).__init__(module)
351 self.dvs = None
352
353 self.switch_name = self.module.params['switch_name']
354 self.switch_version = self.module.params['switch_version']
355
356 if self.switch_version is not None:
357 available_dvs_versions = self.available_dvs_versions()
358 if self.switch_version not in available_dvs_versions:
359 self.module.fail_json(msg="Unsupported version '%s'. Supported versions are: %s." % (self.switch_version, ', '.join(available_dvs_versions)))
360
361 folder = self.params['folder']
362 if folder:
363 self.folder_obj = self.content.searchIndex.FindByInventoryPath(folder)
364 if not self.folder_obj:
365 self.module.fail_json(msg="Failed to find the folder specified by %(folder)s" % self.params)
366 else:
367 datacenter_name = self.params.get('datacenter_name')
368 datacenter_obj = self.find_datacenter_by_name(datacenter_name)
369 if not datacenter_obj:
370 self.module.fail_json(msg="Failed to find datacenter '%s' required"
371 " for managing distributed vSwitch." % datacenter_name)
372 self.folder_obj = datacenter_obj.networkFolder
373
374 self.mtu = self.module.params['mtu']
375 # MTU sanity check
376 if not 1280 <= self.mtu <= 9000:
377 self.module.fail_json(
378 msg="MTU value should be between 1280 and 9000 (both inclusive), provided %d." % self.mtu
379 )
380 self.multicast_filtering_mode = self.module.params['multicast_filtering_mode']
381 self.uplink_quantity = self.module.params['uplink_quantity']
382 self.uplink_prefix = self.module.params['uplink_prefix']
383 self.discovery_protocol = self.module.params['discovery_proto']
384 self.discovery_operation = self.module.params['discovery_operation']
385 # TODO: add port mirroring
386 self.health_check_vlan = self.params['health_check'].get('vlan_mtu')
387 self.health_check_vlan_interval = self.params['health_check'].get('vlan_mtu_interval')
388 self.health_check_teaming = self.params['health_check'].get('teaming_failover')
389 self.health_check_teaming_interval = self.params['health_check'].get('teaming_failover_interval')
390 if self.params['contact']:
391 self.contact_name = self.params['contact'].get('name')
392 self.contact_details = self.params['contact'].get('description')
393 else:
394 self.contact_name = None
395 self.contact_details = None
396 self.description = self.module.params['description']
397
398 self.network_policy = self.module.params['network_policy']
399 if self.network_policy is None:
400 self.network_policy = {}
401
402 self.netFlow_collector_ip = self.module.params['net_flow'].get('collector_ip') or None
403 self.netFlow_collector_port = self.module.params['net_flow'].get('collector_port')
404 self.netFlow_observation_domain_id = self.module.params['net_flow'].get('observation_domain_id')
405 self.netFlow_switch_ip = self.module.params['net_flow'].get('switch_ip')
406 self.netFlow_active_flow_timeout = self.module.params['net_flow'].get('active_flow_timeout')
407 self.netFlow_idle_flow_timeout = self.module.params['net_flow'].get('idle_flow_timeout')
408 self.netFlow_sampling_rate = self.module.params['net_flow'].get('sampling_rate')
409 self.netFlow_internal_flows_only = self.module.params['net_flow'].get('internal_flows_only')
410
411 self.state = self.module.params['state']
412
413 def available_dvs_versions(self):
414 """Get the DVS version supported by the vCenter"""
415 dvs_mng = self.content.dvSwitchManager
416 available_dvs_specs = dvs_mng.QueryAvailableDvsSpec(recommended=True)
417
418 available_dvs_versions = []
419 for available_dvs_spec in available_dvs_specs:
420 available_dvs_versions.append(available_dvs_spec.version)
421
422 return available_dvs_versions
423
424 def process_state(self):
425 """Process the current state of the DVS"""
426 dvs_states = {
427 'absent': {
428 'present': self.destroy_dvswitch,
429 'absent': self.exit_unchanged,
430 },
431 'present': {
432 'present': self.update_dvswitch,
433 'absent': self.create_dvswitch,
434 }
435 }
436
437 try:
438 dvs_states[self.state][self.check_dvs()]()
439 except vmodl.RuntimeFault as runtime_fault:
440 self.module.fail_json(msg=to_native(runtime_fault.msg))
441 except vmodl.MethodFault as method_fault:
442 self.module.fail_json(msg=to_native(method_fault.msg))
443 except Exception as e:
444 self.module.fail_json(msg=to_native(e))
445
446 def check_dvs(self):
447 """Check if DVS is present"""
448 self.dvs = find_dvs_by_name(self.content, self.switch_name, folder=self.folder_obj)
449 if self.dvs is None:
450 return 'absent'
451 return 'present'
452
453 def create_dvswitch(self):
454 """Create a DVS"""
455 changed = True
456 results = dict(changed=changed)
457
458 spec = vim.DistributedVirtualSwitch.CreateSpec()
459 spec.configSpec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
460 # Name
461 results['dvswitch'] = self.switch_name
462 spec.configSpec.name = self.switch_name
463 # MTU
464 results['mtu'] = self.mtu
465 spec.configSpec.maxMtu = self.mtu
466 # Discovery Protocol type and operation
467 results['discovery_protocol'] = self.discovery_protocol
468 results['discovery_operation'] = self.discovery_operation
469 spec.configSpec.linkDiscoveryProtocolConfig = self.create_ldp_spec()
470 # Administrator contact
471 results['contact'] = self.contact_name
472 results['contact_details'] = self.contact_details
473 if self.contact_name or self.contact_details:
474 spec.configSpec.contact = self.create_contact_spec()
475 # Description
476 results['description'] = self.description
477 if self.description:
478 spec.description = self.description
479 # Uplinks
480 results['uplink_quantity'] = self.uplink_quantity
481 spec.configSpec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
482 for count in range(1, self.uplink_quantity + 1):
483 spec.configSpec.uplinkPortPolicy.uplinkPortName.append("%s%d" % (self.uplink_prefix, count))
484 results['uplinks'] = spec.configSpec.uplinkPortPolicy.uplinkPortName
485 # Version
486 results['version'] = self.switch_version
487 if self.switch_version:
488 spec.productInfo = self.create_product_spec(self.switch_version)
489
490 if self.module.check_mode:
491 result = "DVS would be created"
492 else:
493 # Create DVS
494 network_folder = self.folder_obj
495 task = network_folder.CreateDVS_Task(spec)
496 try:
497 wait_for_task(task)
498 except TaskError as invalid_argument:
499 self.module.fail_json(
500 msg="Failed to create DVS : %s" % to_native(invalid_argument)
501 )
502 # Find new DVS
503 self.dvs = find_dvs_by_name(self.content, self.switch_name)
504 changed_multicast = changed_network_policy = False
505 spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
506 # Use the same version in the new spec; The version will be increased by one by the API automatically
507 spec.configVersion = self.dvs.config.configVersion
508 # Set multicast filtering mode
509 results['multicast_filtering_mode'] = self.multicast_filtering_mode
510 multicast_filtering_mode = self.get_api_mc_filtering_mode(self.multicast_filtering_mode)
511 if self.dvs.config.multicastFilteringMode != multicast_filtering_mode:
512 changed_multicast = True
513 spec.multicastFilteringMode = multicast_filtering_mode
514 spec.multicastFilteringMode = self.get_api_mc_filtering_mode(self.multicast_filtering_mode)
515 # Set default network policy
516 network_policy = self.network_policy
517 if 'promiscuous' in network_policy or 'forged_transmits' in network_policy or 'mac_changes' in network_policy:
518 results['network_policy'] = {}
519 if 'promiscuous' in network_policy:
520 results['network_policy']['promiscuous'] = network_policy['promiscuous']
521 if 'forged_transmits' in network_policy:
522 results['network_policy']['forged_transmits'] = network_policy['forged_transmits']
523 if 'mac_changes' in network_policy:
524 results['network_policy']['mac_changes'] = network_policy['mac_changes']
525
526 result = self.check_network_policy_config()
527 changed_network_policy = result[1]
528 if changed_network_policy:
529 if spec.defaultPortConfig is None:
530 spec.defaultPortConfig = vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
531 spec.defaultPortConfig.macManagementPolicy = result[0]
532
533 # Set NetFlow config
534 if self.netFlow_collector_ip is not None:
535 results['net_flow_collector_ip'] = self.netFlow_collector_ip
536 results['net_flow_collector_port'] = self.netFlow_collector_port
537 results['net_flow_observation_domain_id'] = self.netFlow_observation_domain_id
538 results['net_flow_active_flow_timeout'] = self.netFlow_active_flow_timeout
539 results['net_flow_idle_flow_timeout'] = self.netFlow_idle_flow_timeout
540 results['net_flow_sampling_rate'] = self.netFlow_sampling_rate
541 results['net_flow_internal_flows_only'] = self.netFlow_internal_flows_only
542 results['net_flow_switch_ip'] = self.netFlow_switch_ip
543 result = self.check_netFlow_config()
544
545 changed_netFlow = result[2]
546 if changed_netFlow:
547 spec.ipfixConfig = result[0]
548 spec.switchIpAddress = result[1]
549
550 if changed_multicast or changed_network_policy or changed_netFlow:
551 self.update_dvs_config(self.dvs, spec)
552
553 # Set Health Check config
554 results['health_check_vlan'] = self.health_check_vlan
555 results['health_check_teaming'] = self.health_check_teaming
556 results['uuid'] = self.dvs.uuid
557 result = self.check_health_check_config(self.dvs.config.healthCheckConfig)
558 changed_health_check = result[1]
559 if changed_health_check:
560 self.update_health_check_config(self.dvs, result[0])
561
562 result = "DVS created"
563
564 self.module.exit_json(changed=changed, result=to_native(result))
565
566 def create_ldp_spec(self):
567 """Create Link Discovery Protocol config spec"""
568 ldp_config_spec = vim.host.LinkDiscoveryProtocolConfig()
569 if self.discovery_protocol == 'disabled':
570 ldp_config_spec.protocol = 'cdp'
571 ldp_config_spec.operation = 'none'
572 else:
573 ldp_config_spec.protocol = self.discovery_protocol
574 ldp_config_spec.operation = self.discovery_operation
575 return ldp_config_spec
576
577 def create_product_spec(self, switch_version):
578 """Create product info spec"""
579 product_info_spec = vim.dvs.ProductSpec()
580 product_info_spec.version = switch_version
581 return product_info_spec
582
583 @staticmethod
584 def get_api_mc_filtering_mode(mode):
585 """Get Multicast filtering mode"""
586 if mode == 'basic':
587 return 'legacyFiltering'
588 return 'snooping'
589
590 def create_contact_spec(self):
591 """Create contact info spec"""
592 contact_info_spec = vim.DistributedVirtualSwitch.ContactInfo()
593 contact_info_spec.name = self.contact_name
594 contact_info_spec.contact = self.contact_details
595 return contact_info_spec
596
597 def update_dvs_config(self, switch_object, spec):
598 """Update DVS config"""
599 try:
600 task = switch_object.ReconfigureDvs_Task(spec)
601 wait_for_task(task)
602 except TaskError as invalid_argument:
603 self.module.fail_json(
604 msg="Failed to update DVS : %s" % to_native(invalid_argument)
605 )
606
607 def check_network_policy_config(self):
608 changed_promiscuous = changed_forged_transmits = changed_mac_changes = False
609 promiscuous_previous = forged_transmits_previous = mac_changes_previous = None
610 current_config = self.dvs.config.defaultPortConfig
611
612 policy = vim.dvs.VmwareDistributedVirtualSwitch.MacManagementPolicy()
613
614 if 'promiscuous' in self.network_policy and current_config.macManagementPolicy.allowPromiscuous != self.network_policy['promiscuous']:
615 changed_promiscuous = True
616 promiscuous_previous = current_config.macManagementPolicy.allowPromiscuous
617 policy.allowPromiscuous = self.network_policy['promiscuous']
618
619 if 'forged_transmits' in self.network_policy and current_config.macManagementPolicy.forgedTransmits != self.network_policy['forged_transmits']:
620 changed_forged_transmits = True
621 forged_transmits_previous = current_config.macManagementPolicy.forgedTransmits
622 policy.forgedTransmits = self.network_policy['forged_transmits']
623
624 if 'mac_changes' in self.network_policy and current_config.macManagementPolicy.macChanges != self.network_policy['mac_changes']:
625 changed_mac_changes = True
626 mac_changes_previous = current_config.macManagementPolicy.macChanges
627 policy.macChanges = self.network_policy['mac_changes']
628
629 changed = changed_promiscuous or changed_forged_transmits or changed_mac_changes
630 return (policy, changed, changed_promiscuous, promiscuous_previous, changed_forged_transmits,
631 forged_transmits_previous, changed_mac_changes, mac_changes_previous)
632
633 def check_health_check_config(self, health_check_config):
634 """Check Health Check config"""
635 changed = changed_vlan = changed_vlan_interval = changed_teaming = changed_teaming_interval = False
636 vlan_previous = teaming_previous = None
637 vlan_interval_previous = teaming_interval_previous = 0
638 for config in health_check_config:
639 if isinstance(config, vim.dvs.VmwareDistributedVirtualSwitch.VlanMtuHealthCheckConfig):
640 if config.enable != self.health_check_vlan:
641 changed = changed_vlan = True
642 vlan_previous = config.enable
643 config.enable = self.health_check_vlan
644 if config.enable and config.interval != self.health_check_vlan_interval:
645 changed = changed_vlan_interval = True
646 vlan_interval_previous = config.interval
647 config.interval = self.health_check_vlan_interval
648 if isinstance(config, vim.dvs.VmwareDistributedVirtualSwitch.TeamingHealthCheckConfig):
649 if config.enable != self.health_check_teaming:
650 changed = changed_teaming = True
651 teaming_previous = config.enable
652 config.enable = self.health_check_teaming
653 if config.enable and config.interval != self.health_check_teaming_interval:
654 changed = changed_teaming_interval = True
655 teaming_interval_previous = config.interval
656 config.interval = self.health_check_teaming_interval
657 return (health_check_config, changed, changed_vlan, vlan_previous, changed_vlan_interval, vlan_interval_previous,
658 changed_teaming, teaming_previous, changed_teaming_interval, teaming_interval_previous)
659
660 def update_health_check_config(self, switch_object, health_check_config):
661 """Update Health Check config"""
662 try:
663 task = switch_object.UpdateDVSHealthCheckConfig_Task(healthCheckConfig=health_check_config)
664 except vim.fault.DvsFault as dvs_fault:
665 self.module.fail_json(msg="Update failed due to DVS fault : %s" % to_native(dvs_fault))
666 except vmodl.fault.NotSupported as not_supported:
667 self.module.fail_json(msg="Health check not supported on the switch : %s" % to_native(not_supported))
668 except TaskError as invalid_argument:
669 self.module.fail_json(msg="Failed to configure health check : %s" % to_native(invalid_argument))
670 try:
671 wait_for_task(task)
672 except TaskError as invalid_argument:
673 self.module.fail_json(msg="Failed to update health check config : %s" % to_native(invalid_argument))
674
675 def check_netFlow_config(self):
676 """Check NetFlow config"""
677 changed = changed_collectorIpAddress = changed_collectorPort = changed_observationDomainId = \
678 changed_activeFlowTimeout = changed_idleFlowTimeout = changed_samplingRate = changed_internalFlowsOnly = \
679 changed_switchIpAddress = False
680 collectorIpAddress_previous = collectorPort_previous = observationDomainId_previous = activeFlowTimeout_previous = \
681 idleFlowTimeout_previous = samplingRate_previous = internalFlowsOnly_previous = switchIpAddress_previous = None
682
683 current_config = self.dvs.config.ipfixConfig
684 if current_config is None:
685 new_config = vim.dvs.VmwareDistributedVirtualSwitch.IpfixConfig()
686 else:
687 new_config = current_config
688 current_switchIpAddress = self.dvs.config.switchIpAddress
689 if current_switchIpAddress is None:
690 new_config_spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
691 new_switchIpAddress = new_config_spec.switchIpAddress
692 else:
693 new_switchIpAddress = current_switchIpAddress
694
695 if self.netFlow_collector_ip is not None:
696 if current_config.collectorIpAddress != self.netFlow_collector_ip:
697 changed = changed_collectorIpAddress = True
698 collectorIpAddress_previous = current_config.collectorIpAddress
699 new_config.collectorIpAddress = self.netFlow_collector_ip
700 if current_config.collectorPort != self.netFlow_collector_port:
701 changed = changed_collectorPort = True
702 collectorPort_previous = current_config.collectorPort
703 new_config.collectorPort = self.netFlow_collector_port
704 if current_config.observationDomainId != self.netFlow_observation_domain_id:
705 changed = changed_observationDomainId = True
706 observationDomainId_previous = current_config.observationDomainId
707 new_config.observationDomainId = self.netFlow_observation_domain_id
708 if current_config.activeFlowTimeout != self.netFlow_active_flow_timeout:
709 changed = changed_activeFlowTimeout = True
710 activeFlowTimeout_previous = current_config.activeFlowTimeout
711 new_config.activeFlowTimeout = self.netFlow_active_flow_timeout
712 if current_config.idleFlowTimeout != self.netFlow_idle_flow_timeout:
713 changed = changed_idleFlowTimeout = True
714 idleFlowTimeout_previous = current_config.idleFlowTimeout
715 new_config.idleFlowTimeout = self.netFlow_idle_flow_timeout
716 if current_config.samplingRate != self.netFlow_sampling_rate:
717 changed = changed_samplingRate = True
718 samplingRate_previous = current_config.samplingRate
719 new_config.samplingRate = self.netFlow_sampling_rate
720 if current_config.internalFlowsOnly != self.netFlow_internal_flows_only:
721 changed = changed_internalFlowsOnly = True
722 internalFlowsOnly_previous = current_config.internalFlowsOnly
723 new_config.internalFlowsOnly = self.netFlow_internal_flows_only
724 if self.netFlow_switch_ip is not None and current_switchIpAddress != self.netFlow_switch_ip:
725 changed = changed_switchIpAddress = True
726 switchIpAddress_previous = current_switchIpAddress
727 new_switchIpAddress = self.netFlow_switch_ip
728
729 return (new_config, new_switchIpAddress, changed, changed_collectorIpAddress, collectorIpAddress_previous,
730 changed_collectorPort, collectorPort_previous, changed_observationDomainId, observationDomainId_previous,
731 changed_activeFlowTimeout, activeFlowTimeout_previous, changed_idleFlowTimeout, idleFlowTimeout_previous,
732 changed_samplingRate, samplingRate_previous, changed_internalFlowsOnly, internalFlowsOnly_previous,
733 changed_switchIpAddress, switchIpAddress_previous)
734
735 def exit_unchanged(self):
736 """Exit with status message"""
737 changed = False
738 results = dict(changed=changed)
739 results['dvswitch'] = self.switch_name
740 results['result'] = "DVS not present"
741 self.module.exit_json(**results)
742
743 def destroy_dvswitch(self):
744 """Delete a DVS"""
745 changed = True
746 results = dict(changed=changed)
747 results['dvswitch'] = self.switch_name
748
749 if self.module.check_mode:
750 results['result'] = "DVS would be deleted"
751 else:
752 try:
753 task = self.dvs.Destroy_Task()
754 except vim.fault.VimFault as vim_fault:
755 self.module.fail_json(msg="Failed to deleted DVS : %s" % to_native(vim_fault))
756 wait_for_task(task)
757 results['result'] = "DVS deleted"
758 self.module.exit_json(**results)
759
760 def update_dvswitch(self):
761 """Check and update DVS settings"""
762 changed = changed_settings = changed_ldp = changed_version = changed_health_check = changed_network_policy = changed_netFlow = False
763 results = dict(changed=changed)
764 results['dvswitch'] = self.switch_name
765 changed_list = []
766 message = ''
767
768 config_spec = vim.dvs.VmwareDistributedVirtualSwitch.ConfigSpec()
769 # Use the same version in the new spec; The version will be increased by one by the API automatically
770 config_spec.configVersion = self.dvs.config.configVersion
771
772 # Check MTU
773 results['mtu'] = self.mtu
774 if self.dvs.config.maxMtu != self.mtu:
775 changed = changed_settings = True
776 changed_list.append("mtu")
777 results['mtu_previous'] = config_spec.maxMtu
778 config_spec.maxMtu = self.mtu
779
780 # Check Discovery Protocol type and operation
781 ldp_protocol = self.dvs.config.linkDiscoveryProtocolConfig.protocol
782 ldp_operation = self.dvs.config.linkDiscoveryProtocolConfig.operation
783 if self.discovery_protocol == 'disabled':
784 results['discovery_protocol'] = self.discovery_protocol
785 results['discovery_operation'] = 'n/a'
786 if ldp_protocol != 'cdp' or ldp_operation != 'none':
787 changed_ldp = True
788 results['discovery_protocol_previous'] = ldp_protocol
789 results['discovery_operation_previous'] = ldp_operation
790 else:
791 results['discovery_protocol'] = self.discovery_protocol
792 results['discovery_operation'] = self.discovery_operation
793 if ldp_protocol != self.discovery_protocol or ldp_operation != self.discovery_operation:
794 changed_ldp = True
795 if ldp_protocol != self.discovery_protocol:
796 results['discovery_protocol_previous'] = ldp_protocol
797 if ldp_operation != self.discovery_operation:
798 results['discovery_operation_previous'] = ldp_operation
799 if changed_ldp:
800 changed = changed_settings = True
801 changed_list.append("discovery protocol")
802 config_spec.linkDiscoveryProtocolConfig = self.create_ldp_spec()
803
804 # Check Multicast filtering mode
805 results['multicast_filtering_mode'] = self.multicast_filtering_mode
806 multicast_filtering_mode = self.get_api_mc_filtering_mode(self.multicast_filtering_mode)
807 if self.dvs.config.multicastFilteringMode != multicast_filtering_mode:
808 changed = changed_settings = True
809 changed_list.append("multicast filtering")
810 results['multicast_filtering_mode_previous'] = self.dvs.config.multicastFilteringMode
811 config_spec.multicastFilteringMode = multicast_filtering_mode
812
813 # Check administrator contact
814 results['contact'] = self.contact_name
815 results['contact_details'] = self.contact_details
816 if self.dvs.config.contact.name != self.contact_name or self.dvs.config.contact.contact != self.contact_details:
817 changed = changed_settings = True
818 changed_list.append("contact")
819 results['contact_previous'] = self.dvs.config.contact.name
820 results['contact_details_previous'] = self.dvs.config.contact.contact
821 config_spec.contact = self.create_contact_spec()
822
823 # Check description
824 results['description'] = self.description
825 if self.dvs.config.description != self.description:
826 changed = changed_settings = True
827 changed_list.append("description")
828 results['description_previous'] = self.dvs.config.description
829 if self.description is None:
830 # need to use empty string; will be set to None by API
831 config_spec.description = ''
832 else:
833 config_spec.description = self.description
834
835 # Check uplinks
836 results['uplink_quantity'] = self.uplink_quantity
837 if len(self.dvs.config.uplinkPortPolicy.uplinkPortName) != self.uplink_quantity:
838 changed = changed_settings = True
839 changed_list.append("uplink quantity")
840 results['uplink_quantity_previous'] = len(self.dvs.config.uplinkPortPolicy.uplinkPortName)
841 config_spec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
842 # just replace the uplink array if uplinks need to be added
843 if len(self.dvs.config.uplinkPortPolicy.uplinkPortName) < self.uplink_quantity:
844 for count in range(1, self.uplink_quantity + 1):
845 config_spec.uplinkPortPolicy.uplinkPortName.append("%s%d" % (self.uplink_prefix, count))
846 # just replace the uplink array if uplinks need to be removed
847 if len(self.dvs.config.uplinkPortPolicy.uplinkPortName) > self.uplink_quantity:
848 for count in range(1, self.uplink_quantity + 1):
849 config_spec.uplinkPortPolicy.uplinkPortName.append("%s%d" % (self.uplink_prefix, count))
850 results['uplinks'] = config_spec.uplinkPortPolicy.uplinkPortName
851 results['uplinks_previous'] = self.dvs.config.uplinkPortPolicy.uplinkPortName
852 else:
853 # No uplink name check; uplink names can't be changed easily if they are used by a portgroup
854 results['uplinks'] = self.dvs.config.uplinkPortPolicy.uplinkPortName
855
856 # Check Health Check
857 results['health_check_vlan'] = self.health_check_vlan
858 results['health_check_teaming'] = self.health_check_teaming
859 results['health_check_vlan_interval'] = self.health_check_vlan_interval
860 results['health_check_teaming_interval'] = self.health_check_teaming_interval
861 (health_check_config, changed_health_check, changed_vlan, vlan_previous,
862 changed_vlan_interval, vlan_interval_previous, changed_teaming, teaming_previous,
863 changed_teaming_interval, teaming_interval_previous) = \
864 self.check_health_check_config(self.dvs.config.healthCheckConfig)
865 if changed_health_check:
866 changed = True
867 changed_list.append("health check")
868 if changed_vlan:
869 results['health_check_vlan_previous'] = vlan_previous
870 if changed_vlan_interval:
871 results['health_check_vlan_interval_previous'] = vlan_interval_previous
872 if changed_teaming:
873 results['health_check_teaming_previous'] = teaming_previous
874 if changed_teaming_interval:
875 results['health_check_teaming_interval_previous'] = teaming_interval_previous
876
877 # Check Network Policy
878 if 'promiscuous' in self.network_policy or 'forged_transmits' in self.network_policy or 'mac_changes' in self.network_policy:
879 results['network_policy'] = {}
880 if 'promiscuous' in self.network_policy:
881 results['network_policy']['promiscuous'] = self.network_policy['promiscuous']
882 if 'forged_transmits' in self.network_policy:
883 results['network_policy']['forged_transmits'] = self.network_policy['forged_transmits']
884 if 'mac_changes' in self.network_policy:
885 results['network_policy']['mac_changes'] = self.network_policy['mac_changes']
886
887 (policy, changed_network_policy, changed_promiscuous, promiscuous_previous, changed_forged_transmits,
888 forged_transmits_previous, changed_mac_changes, mac_changes_previous) = \
889 self.check_network_policy_config()
890
891 if changed_network_policy:
892 changed = changed_settings = True
893 changed_list.append("network policy")
894 results['network_policy_previous'] = {}
895 if changed_promiscuous:
896 results['network_policy_previous']['promiscuous'] = promiscuous_previous
897
898 if changed_forged_transmits:
899 results['network_policy_previous']['forged_transmits'] = forged_transmits_previous
900
901 if changed_mac_changes:
902 results['network_policy_previous']['mac_changes'] = mac_changes_previous
903
904 if config_spec.defaultPortConfig is None:
905 config_spec.defaultPortConfig = vim.dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy()
906
907 config_spec.defaultPortConfig.macManagementPolicy = policy
908
909 # Check switch version
910 spec_product = None
911 if self.switch_version:
912 results['version'] = self.switch_version
913 if self.dvs.config.productInfo.version != self.switch_version:
914 changed_version = True
915 spec_product = self.create_product_spec(self.switch_version)
916 else:
917 results['version'] = self.dvs.config.productInfo.version
918 changed_version = False
919 if changed_version:
920 changed = True
921 changed_list.append("switch version")
922 results['version_previous'] = self.dvs.config.productInfo.version
923
924 # Check NetFlow Config
925 if self.netFlow_collector_ip is not None:
926 results['net_flow_collector_ip'] = self.netFlow_collector_ip
927 results['net_flow_collector_port'] = self.netFlow_collector_port
928 results['net_flow_observation_domain_id'] = self.netFlow_observation_domain_id
929 results['net_flow_active_flow_timeout'] = self.netFlow_active_flow_timeout
930 results['net_flow_idle_flow_timeout'] = self.netFlow_idle_flow_timeout
931 results['net_flow_sampling_rate'] = self.netFlow_sampling_rate
932 results['net_flow_internal_flows_only'] = self.netFlow_internal_flows_only
933 results['net_flow_switch_ip'] = self.netFlow_switch_ip
934
935 (ipfixConfig, switchIpAddress_netFlow, changed_netFlow, changed_collectorIpAddress, collectorIpAddress_previous,
936 changed_collectorPort, collectorPort_previous, changed_observationDomainId, observationDomainId_previous, changed_activeFlowTimeout,
937 activeFlowTimeout_previous, changed_idleFlowTimeout, idleFlowTimeout_previous, changed_samplingRate, samplingRate_previous,
938 changed_internalFlowsOnly, internalFlowsOnly_previous, changed_switchIpAddress, switchIpAddress_previous) = self.check_netFlow_config()
939 if changed_netFlow:
940 changed = changed_settings = True
941 changed_list.append("netFlow")
942 if changed_collectorIpAddress:
943 results['net_flow_collector_ip_previous'] = collectorIpAddress_previous
944 if changed_collectorPort:
945 results['net_flow_collector_port_previous'] = collectorPort_previous
946 if changed_observationDomainId:
947 results['net_flow_observation_domain_id_previous'] = observationDomainId_previous
948 if changed_activeFlowTimeout:
949 results['net_flow_active_flow_timeout_previous'] = activeFlowTimeout_previous
950 if changed_idleFlowTimeout:
951 results['net_flow_idle_flow_timeout_previous'] = idleFlowTimeout_previous
952 if changed_samplingRate:
953 results['net_flow_sampling_rate_previous'] = samplingRate_previous
954 if changed_internalFlowsOnly:
955 results['net_flow_internal_flows_only_previous'] = internalFlowsOnly_previous
956 if changed_switchIpAddress:
957 results['net_flow_switch_ip_previous'] = switchIpAddress_previous
958
959 config_spec.ipfixConfig = ipfixConfig
960 config_spec.switchIpAddress = switchIpAddress_netFlow
961
962 if changed:
963 if self.module.check_mode:
964 changed_suffix = ' would be changed'
965 else:
966 changed_suffix = ' changed'
967 if len(changed_list) > 2:
968 message = ', '.join(changed_list[:-1]) + ', and ' + str(changed_list[-1])
969 elif len(changed_list) == 2:
970 message = ' and '.join(changed_list)
971 elif len(changed_list) == 1:
972 message = changed_list[0]
973 message += changed_suffix
974 if not self.module.check_mode:
975 if changed_settings:
976 self.update_dvs_config(self.dvs, config_spec)
977 if changed_health_check:
978 self.update_health_check_config(self.dvs, health_check_config)
979 if changed_version:
980 task = self.dvs.PerformDvsProductSpecOperation_Task("upgrade", spec_product)
981 try:
982 wait_for_task(task)
983 except TaskError as invalid_argument:
984 self.module.fail_json(msg="Failed to update DVS version : %s" % to_native(invalid_argument))
985 else:
986 message = "DVS already configured properly"
987 results['uuid'] = self.dvs.uuid
988 results['changed'] = changed
989 results['result'] = message
990
991 self.module.exit_json(**results)
992
993
994 def main():
995 """Main"""
996 argument_spec = base_argument_spec()
997 argument_spec.update(
998 dict(
999 datacenter_name=dict(aliases=['datacenter']),
1000 folder=dict(),
1001 switch_name=dict(required=True, aliases=['switch', 'dvswitch']),
1002 mtu=dict(type='int', default=1500),
1003 multicast_filtering_mode=dict(type='str', default='basic', choices=['basic', 'snooping']),
1004 switch_version=dict(
1005 type='str',
1006 aliases=['version'],
1007 default=None
1008 ),
1009 uplink_quantity=dict(type='int'),
1010 uplink_prefix=dict(type='str', default='Uplink '),
1011 discovery_proto=dict(
1012 type='str', choices=['cdp', 'lldp', 'disabled'], default='cdp', aliases=['discovery_protocol']
1013 ),
1014 discovery_operation=dict(type='str', choices=['both', 'advertise', 'listen'], default='listen'),
1015 health_check=dict(
1016 type='dict',
1017 options=dict(
1018 vlan_mtu=dict(type='bool', default=False),
1019 teaming_failover=dict(type='bool', default=False),
1020 vlan_mtu_interval=dict(type='int', default=0),
1021 teaming_failover_interval=dict(type='int', default=0),
1022 ),
1023 default=dict(
1024 vlan_mtu=False,
1025 teaming_failover=False,
1026 vlan_mtu_interval=0,
1027 teaming_failover_interval=0,
1028 ),
1029 ),
1030 contact=dict(
1031 type='dict',
1032 options=dict(
1033 name=dict(type='str'),
1034 description=dict(type='str'),
1035 ),
1036 ),
1037 description=dict(type='str'),
1038 state=dict(default='present', choices=['present', 'absent']),
1039 network_policy=dict(
1040 type='dict',
1041 options=dict(
1042 promiscuous=dict(type='bool', default=False),
1043 forged_transmits=dict(type='bool', default=False),
1044 mac_changes=dict(type='bool', default=False)
1045 ),
1046 ),
1047 net_flow=dict(
1048 type='dict',
1049 options=dict(
1050 collector_ip=dict(type='str'),
1051 collector_port=dict(type='int', default=0),
1052 observation_domain_id=dict(type='int', default=0),
1053 switch_ip=dict(type='str'),
1054 active_flow_timeout=dict(type='int', default=60),
1055 idle_flow_timeout=dict(type='int', default=15),
1056 sampling_rate=dict(type='int', default=4096),
1057 internal_flows_only=dict(type='bool', default=False),
1058 ),
1059 default=dict(
1060 collector_port=0,
1061 observation_domain_id=0,
1062 active_flow_timeout=60,
1063 idle_flow_timeout=15,
1064 sampling_rate=4096,
1065 internal_flows_only=False,
1066 ),
1067 ),
1068 )
1069 )
1070
1071 module = AnsibleModule(
1072 argument_spec=argument_spec,
1073 required_if=[
1074 ('state', 'present',
1075 ['uplink_quantity']),
1076 ],
1077 required_one_of=[
1078 ['folder', 'datacenter_name'],
1079 ],
1080 mutually_exclusive=[
1081 ['folder', 'datacenter_name'],
1082 ],
1083 supports_check_mode=True,
1084 )
1085
1086 vmware_dvswitch = VMwareDvSwitch(module)
1087 vmware_dvswitch.process_state()
1088
1089
1090 if __name__ == '__main__':
1091 main()