Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2020, Ansible Project
4 # Copyright: (c) 2019, Diane Wang <[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_guest_network
15 short_description: Manage network adapters of specified virtual machine in given vCenter infrastructure
16 description:
17 - This module is used to add, reconfigure, remove network adapter of given virtual machine.
18 author:
19 - Diane Wang (@Tomorrow9) <[email protected]>
20 notes:
21 - For backwards compatibility network_data is returned when using the gather_network_info parameter
22 options:
23 name:
24 description:
25 - Name of virtual machine
26 - Required if O(uuid) or O(moid) is not supplied.
27 type: str
28 uuid:
29 description:
30 - vm uuid
31 - Required if O(name) or O(moid) is not supplied.
32 type: str
33 use_instance_uuid:
34 description:
35 - Whether to use the VMware instance UUID rather than the BIOS UUID.
36 default: false
37 type: bool
38 moid:
39 description:
40 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
41 - Required if O(uuid) or O(name) is not supplied.
42 type: str
43 folder:
44 description:
45 - Folder location of given VM, this is only required when there's multiple VM's with the same name.
46 type: str
47 datacenter:
48 default: ha-datacenter
49 description:
50 - Datacenter the VM belongs to.
51 type: str
52 cluster:
53 description:
54 - Name of cluster where VM belongs to.
55 type: str
56 esxi_hostname:
57 description:
58 - The hostname of the ESXi host where the VM belongs to.
59 type: str
60 mac_address:
61 description:
62 - MAC address of the NIC that should be altered, if a MAC address is not supplied a new nic will be created.
63 - Required when O(state=absent).
64 type: str
65 label:
66 description:
67 - 'Label of the NIC that should be altered. O(mac_address) or O(label) should be set to get the corresponding
68 device to reconfigure.'
69 - Alter the name of the network adapter.
70 type: str
71 vlan_id:
72 description:
73 - VLAN id associated with the network.
74 type: int
75 network_name:
76 description:
77 - Name of network in vSphere.
78 - Work faster then o(vlan_id) for big infrastructure with many networks.
79 type: str
80 device_type:
81 default: vmxnet3
82 description:
83 - Type of virtual network device.
84 - 'Valid choices are - V(e1000), V(e1000e), V(pcnet32), V(vmxnet2), V(vmxnet3) (default), V(sriov), V(pvrdma).'
85 type: str
86 pvrdma_device_protocol:
87 version_added: '3.3.0'
88 description:
89 - The PVRDMA device protocol used. Valid choices are - V(rocev1), V(rocev2).
90 - This parameter is only used on the VM with hardware version >=14 and <= 19.
91 type: str
92 switch:
93 description:
94 - Name of the (dv)switch for destination network, this is only required for dvswitches.
95 type: str
96 guest_control:
97 default: true
98 description:
99 - Enables guest control over whether the connectable device is connected.
100 type: bool
101 state:
102 default: present
103 choices: ['present', 'absent']
104 description:
105 - NIC state.
106 - When V(present), a nic will be added if a mac address or label does not previously exists or is unset.
107 - When V(absent), the O(mac_address) parameter has to be set.
108 type: str
109 start_connected:
110 default: true
111 description:
112 - If NIC should be connected to network on startup.
113 type: bool
114 wake_onlan:
115 default: false
116 description:
117 - Enable wake on LAN.
118 type: bool
119 connected:
120 default: true
121 description:
122 - If NIC should be connected to the network.
123 type: bool
124 directpath_io:
125 default: false
126 description:
127 - Enable Universal Pass-through (UPT).
128 - Only compatible with the O(device_type=vmxnet3).
129 type: bool
130 physical_function_backing:
131 type: str
132 description:
133 - If set, specifies the PCI ID of the physical function to use as backing for a SR-IOV network adapter.
134 - This option is only compatible for SR-IOV network adapters.
135 virtual_function_backing:
136 type: str
137 description:
138 - If set, specifies the PCI ID of the physical function to use as backing for a SR-IOV network adapter.
139 - This option is only compatible for SR-IOV network adapters.
140 allow_guest_os_mtu_change:
141 default: true
142 type: bool
143 description:
144 - Allows the guest OS to change the MTU on a SR-IOV network adapter.
145 - This option is only compatible for SR-IOV network adapters.
146 force:
147 default: false
148 description:
149 - Force adapter creation even if an existing adapter is attached to the same network.
150 type: bool
151 gather_network_info:
152 aliases:
153 - gather_network_facts
154 default: false
155 description:
156 - Return information about current guest network adapters.
157 type: bool
158 extends_documentation_fragment:
159 - vmware.vmware.base_options
160 '''
161
162 EXAMPLES = r'''
163 - name: change network for 00:50:56:11:22:33 on vm01.domain.fake
164 community.vmware.vmware_guest_network:
165 hostname: "{{ vcenter_hostname }}"
166 username: "{{ vcenter_username }}"
167 password: "{{ vcenter_password }}"
168 datacenter: "{{ datacenter_name }}"
169 name: vm01.domain.fake
170 mac_address: 00:50:56:11:22:33
171 network_name: admin-network
172 state: present
173
174 - name: add a nic on network with vlan id 2001 for 422d000d-2000-ffff-0000-b00000000000
175 community.vmware.vmware_guest_network:
176 hostname: "{{ vcenter_hostname }}"
177 username: "{{ vcenter_username }}"
178 password: "{{ vcenter_password }}"
179 datacenter: "{{ datacenter_name }}"
180 uuid: 422d000d-2000-ffff-0000-b00000000000
181 vlan_id: 2001
182
183 - name: remove nic with mac 00:50:56:11:22:33 from vm01.domain.fake
184 community.vmware.vmware_guest_network:
185 hostname: "{{ vcenter_hostname }}"
186 username: "{{ vcenter_username }}"
187 password: "{{ vcenter_password }}"
188 datacenter: "{{ datacenter_name }}"
189 mac_address: 00:50:56:11:22:33
190 name: vm01.domain.fake
191 state: absent
192
193 - name: add multiple nics to vm01.domain.fake
194 community.vmware.vmware_guest_network:
195 hostname: "{{ vcenter_hostname }}"
196 username: "{{ vcenter_username }}"
197 password: "{{ vcenter_password }}"
198 datacenter: "{{ datacenter_name }}"
199 name: vm01.domain.fake
200 state: present
201 vlan_id: "{{ item.vlan_id | default(omit) }}"
202 network_name: "{{ item.network_name | default(omit) }}"
203 connected: "{{ item.connected | default(omit) }}"
204 loop:
205 - vlan_id: 2000
206 connected: false
207 - network_name: guest-net
208 connected: true
209 '''
210
211 RETURN = r'''
212 network_info:
213 description: metadata about the virtual machine network adapters
214 returned: always
215 type: list
216 sample:
217 "network_info": [
218 {
219 "mac_address": "00:50:56:AA:AA:AA",
220 "allow_guest_ctl": true,
221 "connected": true,
222 "device_type": "vmxnet3",
223 "label": "Network adapter 2",
224 "network_name": "admin-net",
225 "start_connected": true,
226 "switch": "vSwitch0",
227 "unit_number": 8,
228 "vlan_id": 10,
229 "wake_onlan": false
230 },
231 {
232 "mac_address": "00:50:56:BB:BB:BB",
233 "allow_guest_ctl": true,
234 "connected": true,
235 "device_type": "vmxnet3",
236 "label": "Network adapter 1",
237 "network_name": "guest-net",
238 "start_connected": true,
239 "switch": "vSwitch0",
240 "unit_number": 7,
241 "vlan_id": 10,
242 "wake_onlan": true
243 }
244 ]
245 network_data:
246 description: For backwards compatibility, metadata about the virtual machine network adapters
247 returned: when using gather_network_info parameter
248 type: dict
249 sample:
250 "network_data": {
251 '0': {
252 "mac_addr": "00:50:56:AA:AA:AA",
253 "mac_address": "00:50:56:AA:AA:AA",
254 "allow_guest_ctl": true,
255 "connected": true,
256 "device_type": "vmxnet3",
257 "label": "Network adapter 2",
258 "name": "admin-net",
259 "network_name": "admin-net",
260 "start_connected": true,
261 "switch": "vSwitch0",
262 "unit_number": 8,
263 "vlan_id": 10,
264 "wake_onlan": false
265 },
266 '1': {
267 "mac_addr": "00:50:56:BB:BB:BB",
268 "mac_address": "00:50:56:BB:BB:BB",
269 "allow_guest_ctl": true,
270 "connected": true,
271 "device_type": "vmxnet3",
272 "label": "Network adapter 1",
273 "name": "guest-net",
274 "network_name": "guest-net",
275 "start_connected": true,
276 "switch": "vSwitch0",
277 "unit_number": 7,
278 "vlan_id": 10,
279 "wake_onlan": true
280 }
281 }
282
283 '''
284
285 try:
286 from pyVmomi import vim
287 except ImportError:
288 pass
289
290 import copy
291 from ansible.module_utils.common.text.converters import to_native
292 from ansible.module_utils.basic import AnsibleModule
293 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, TaskError, wait_for_task
294 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
295 from ansible_collections.community.vmware.plugins.module_utils.vm_device_helper import PyVmomiDeviceHelper
296
297
298 class PyVmomiHelper(PyVmomi):
299 def __init__(self, module):
300 super(PyVmomiHelper, self).__init__(module)
301 self.change_detected = False
302 self.device_helper = PyVmomiDeviceHelper(self.module)
303
304 def _get_network_object(self, vm_obj):
305 '''
306 return network object matching given parameters
307 :param vm_obj: vm object
308 :return: network object
309 :rtype: object
310 '''
311 if not self.params['esxi_hostname'] or not self.params['cluster']:
312 compute_resource = vm_obj.runtime.host
313 else:
314 compute_resource = self._get_compute_resource_by_name()
315
316 pg_lookup = {}
317 vlan_id = self.params['vlan_id']
318 network_name = self.params['network_name']
319 switch_name = self.params['switch']
320
321 for pg in vm_obj.runtime.host.config.network.portgroup:
322 pg_lookup[pg.spec.name] = {'switch': pg.spec.vswitchName, 'vlan_id': pg.spec.vlanId}
323
324 if network_name:
325 networks = self.find_network_by_name(network_name)
326 for network in networks:
327 if network in compute_resource.network:
328 if isinstance(network, vim.dvs.DistributedVirtualPortgroup):
329 dvs = network.config.distributedVirtualSwitch
330 if (switch_name and dvs.config.name == switch_name) or not switch_name:
331 return network
332 elif isinstance(network, vim.Network):
333 return network
334
335 if compute_resource:
336 for network in compute_resource.network:
337 if isinstance(network, vim.dvs.DistributedVirtualPortgroup):
338 dvs = network.config.distributedVirtualSwitch
339 if (switch_name and dvs.config.name == switch_name) or not switch_name:
340 if network.config.name == network_name:
341 return network
342 if hasattr(network.config.defaultPortConfig.vlan, 'vlanId') and \
343 network.config.defaultPortConfig.vlan.vlanId == vlan_id:
344 return network
345 if hasattr(network.config.defaultPortConfig.vlan, 'pvlanId') and \
346 network.config.defaultPortConfig.vlan.pvlanId == vlan_id:
347 return network
348 elif isinstance(network, vim.Network):
349 if network_name and network_name == network.name:
350 return network
351 if vlan_id:
352 for k in pg_lookup.keys():
353 if vlan_id == pg_lookup[k]['vlan_id']:
354 if k == network.name:
355 return network
356 break
357 return None
358
359 def _get_vlanid_from_network(self, network):
360 '''
361 get the vlan id from network object
362 :param network: network object to expect, either vim.Network or vim.dvs.DistributedVirtualPortgroup
363 :return: vlan id as an integer
364 :rtype: integer
365 '''
366 vlan_id = None
367 if isinstance(network, vim.dvs.DistributedVirtualPortgroup):
368 vlan_id = network.config.defaultPortConfig.vlan.vlanId
369
370 if isinstance(network, vim.Network) and hasattr(network, 'host'):
371 for host in network.host:
372 for pg in host.config.network.portgroup:
373 if pg.spec.name == network.name:
374 vlan_id = pg.spec.vlanId
375 return vlan_id
376
377 return vlan_id
378
379 def _get_nics_from_vm(self, vm_obj):
380 '''
381 return a list of dictionaries containing vm nic info and
382 a list of objects
383 :param vm_obj: object containing virtual machine
384 :return: list of dicts and list ith nic object(s)
385 :rtype: list, list
386 '''
387 nic_info_lst = []
388 nics = [nic for nic in vm_obj.config.hardware.device if isinstance(nic, vim.vm.device.VirtualEthernetCard)]
389 for nic in nics:
390 # common items of nic parameters
391 d_item = dict(
392 mac_address=nic.macAddress,
393 label=nic.deviceInfo.label,
394 unit_number=nic.unitNumber,
395 wake_onlan=nic.wakeOnLanEnabled,
396 allow_guest_ctl=nic.connectable.allowGuestControl,
397 connected=nic.connectable.connected,
398 start_connected=nic.connectable.startConnected,
399 )
400 # If NIC is a SR-IOV adapter
401 if isinstance(nic, vim.vm.device.VirtualSriovEthernetCard):
402 d_item['allow_guest_os_mtu_change'] = nic.allowGuestOSMtuChange
403 if isinstance(nic.sriovBacking, vim.vm.device.VirtualSriovEthernetCard.SriovBackingInfo):
404 if isinstance(nic.sriovBacking.physicalFunctionBacking, vim.vm.device.VirtualPCIPassthrough):
405 d_item['physical_function_backing'] = nic.sriovBacking.physicalFunctionBacking.id
406 if isinstance(nic.sriovBacking.virtualFunctionBacking, vim.vm.device.VirtualPCIPassthrough):
407 d_item['virtual_function_backing'] = nic.sriovBacking.virtualFunctionBacking.id
408 # If a distributed port group specified
409 if isinstance(nic.backing, vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo):
410 key = nic.backing.port.portgroupKey
411 for portgroup in vm_obj.network:
412 if hasattr(portgroup, 'key') and portgroup.key == key:
413 d_item['network_name'] = portgroup.name
414 d_item['switch'] = portgroup.config.distributedVirtualSwitch.name
415 break
416 # If an NSX-T port group specified
417 elif isinstance(nic.backing, vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo):
418 d_item['network_name'] = nic.backing.opaqueNetworkId
419 d_item['switch'] = nic.backing.opaqueNetworkType
420 # If a port group specified
421 elif isinstance(nic.backing, vim.vm.device.VirtualEthernetCard.NetworkBackingInfo):
422 d_item['network_name'] = nic.backing.network.name
423 d_item['vlan_id'] = self._get_vlanid_from_network(nic.backing.network)
424 if isinstance(nic.backing.network, vim.Network):
425 for pg in vm_obj.runtime.host.config.network.portgroup:
426 if pg.spec.name == nic.backing.network.name:
427 d_item['switch'] = pg.spec.vswitchName
428 break
429
430 for k in self.device_helper.nic_device_type:
431 if isinstance(nic, self.device_helper.nic_device_type[k]):
432 d_item['device_type'] = k
433 # VirtualVmxnet3Vrdma extends VirtualVmxnet3
434 if k == 'vmxnet3':
435 continue
436 else:
437 break
438 if d_item['device_type'] == 'pvrdma':
439 d_item['device_protocol'] = nic.deviceProtocol
440
441 nic_info_lst.append(d_item)
442
443 nic_info_lst = sorted(nic_info_lst, key=lambda d: d['mac_address'] if (d['mac_address'] is not None) else '00:00:00:00:00:00')
444 return nic_info_lst, nics
445
446 def _get_compute_resource_by_name(self, recurse=True):
447 '''
448 get compute resource object with matching name of esxi_hostname or cluster
449 parameters.
450 :param recurse: recurse vmware content folder, default is True
451 :return: object matching vim.ComputeResource or None if no match
452 :rtype: object
453 '''
454 resource_name = None
455 if self.params['esxi_hostname']:
456 resource_name = self.params['esxi_hostname']
457
458 if self.params['cluster']:
459 resource_name = self.params['cluster']
460
461 container = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.ComputeResource], recurse)
462 for obj in container.view:
463 if self.params['esxi_hostname'] and isinstance(obj, vim.ClusterComputeResource) and hasattr(obj, 'host'):
464 for host in obj.host:
465 if host.name == resource_name:
466 return obj
467
468 if obj.name == resource_name:
469 return obj
470
471 return None
472
473 def _new_nic_spec(self, vm_obj, nic_obj=None, network_params=None):
474 network = self._get_network_object(vm_obj)
475
476 if network_params:
477 connected = network_params['connected']
478 device_type = network_params['device_type'].lower()
479 directpath_io = network_params['directpath_io']
480 guest_control = network_params['guest_control']
481 label = network_params['label']
482 mac_address = network_params['mac_address']
483 start_connected = network_params['start_connected']
484 wake_onlan = network_params['wake_onlan']
485 pf_backing = network_params['physical_function_backing']
486 vf_backing = network_params['virtual_function_backing']
487 allow_guest_os_mtu_change = network_params['allow_guest_os_mtu_change']
488 else:
489 connected = self.params['connected']
490 device_type = self.params['device_type'].lower()
491 directpath_io = self.params['directpath_io']
492 guest_control = self.params['guest_control']
493 label = self.params['label']
494 mac_address = self.params['mac_address']
495 start_connected = self.params['start_connected']
496 wake_onlan = self.params['wake_onlan']
497 pf_backing = self.params['physical_function_backing']
498 vf_backing = self.params['virtual_function_backing']
499 allow_guest_os_mtu_change = self.params['allow_guest_os_mtu_change']
500 pvrdma_device_protocol = self.params['pvrdma_device_protocol']
501
502 if not nic_obj:
503 device_obj = self.device_helper.nic_device_type[device_type]
504 nic_spec = vim.vm.device.VirtualDeviceSpec(
505 device=device_obj()
506 )
507 if mac_address:
508 nic_spec.device.addressType = 'manual'
509 nic_spec.device.macAddress = mac_address
510
511 if label:
512 nic_spec.device.deviceInfo = vim.Description(
513 label=label
514 )
515
516 if device_type == 'pvrdma' and pvrdma_device_protocol:
517 nic_spec.device.deviceProtocol = pvrdma_device_protocol
518 else:
519 nic_spec = vim.vm.device.VirtualDeviceSpec(
520 operation=vim.vm.device.VirtualDeviceSpec.Operation.edit,
521 device=nic_obj
522 )
523 if label and label != nic_obj.deviceInfo.label:
524 nic_spec.device.deviceInfo = vim.Description(
525 label=label
526 )
527 if mac_address and mac_address != nic_obj.macAddress:
528 nic_spec.device.addressType = 'manual'
529 nic_spec.device.macAddress = mac_address
530
531 nic_spec.device.backing = self._nic_backing_from_obj(network)
532 nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
533 startConnected=start_connected,
534 allowGuestControl=guest_control,
535 connected=connected
536 )
537 nic_spec.device.wakeOnLanEnabled = wake_onlan
538
539 if (pf_backing is not None or vf_backing is not None) and not isinstance(nic_spec.device, vim.vm.device.VirtualSriovEthernetCard):
540 self.module_fail_json(msg='physical_function_backing, virtual_function_backing can only be used with the sriov device type')
541
542 if isinstance(nic_spec.device, vim.vm.device.VirtualSriovEthernetCard):
543 nic_spec.device.allowGuestOSMtuChange = allow_guest_os_mtu_change
544 nic_spec.device.sriovBacking = vim.vm.device.VirtualSriovEthernetCard.SriovBackingInfo()
545 if pf_backing is not None:
546 nic_spec.device.sriovBacking.physicalFunctionBacking = vim.vm.device.VirtualPCIPassthrough.DeviceBackingInfo()
547 nic_spec.device.sriovBacking.physicalFunctionBacking.id = pf_backing
548 if vf_backing is not None:
549 nic_spec.device.sriovBacking.virtualFunctionBacking = vim.vm.device.VirtualPCIPassthrough.DeviceBackingInfo()
550 nic_spec.device.sriovBacking.virtualFunctionBacking.id = vf_backing
551
552 if directpath_io and not isinstance(nic_spec.device, vim.vm.device.VirtualVmxnet3):
553 self.module.fail_json(msg='directpath_io can only be used with the vmxnet3 device type')
554
555 if directpath_io and isinstance(nic_spec.device, vim.vm.device.VirtualVmxnet3):
556 nic_spec.device.uptCompatibilityEnabled = True
557 return nic_spec
558
559 def _nic_backing_from_obj(self, network_obj):
560 rv = None
561 if isinstance(network_obj, vim.dvs.DistributedVirtualPortgroup):
562 rv = vim.VirtualEthernetCardDistributedVirtualPortBackingInfo(
563 port=vim.DistributedVirtualSwitchPortConnection(
564 portgroupKey=network_obj.key,
565 switchUuid=network_obj.config.distributedVirtualSwitch.uuid
566 )
567 )
568 elif isinstance(network_obj, vim.OpaqueNetwork):
569 rv = vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo(
570 opaqueNetworkType='nsx.LogicalSwitch',
571 opaqueNetworkId=network_obj.summary.opaqueNetworkId
572 )
573 elif isinstance(network_obj, vim.Network):
574 rv = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
575 deviceName=network_obj.name,
576 network=network_obj
577 )
578 return rv
579
580 def _nic_absent(self, network_params=None):
581 changed = False
582 diff = {'before': {}, 'after': {}}
583 if network_params:
584 mac_address = network_params['mac_address']
585 else:
586 mac_address = self.params['mac_address']
587
588 device_spec = None
589 vm_obj = self.get_vm()
590 if not vm_obj:
591 self.module.fail_json(msg='could not find vm: {0}'.format(self.params['name']))
592 nic_info, nic_obj_lst = self._get_nics_from_vm(vm_obj)
593
594 for nic in nic_info:
595 diff['before'].update({nic['mac_address']: copy.copy(nic)})
596
597 network_info = copy.deepcopy(nic_info)
598
599 for nic_obj in nic_obj_lst:
600 if nic_obj.macAddress == mac_address:
601 if self.module.check_mode:
602 changed = True
603 for nic in nic_info:
604 if nic.get('mac_address') != nic_obj.macAddress:
605 diff['after'].update({nic['mac_address']: copy.copy(nic)})
606 network_info = [nic for nic in nic_info if nic.get('mac_address') != nic_obj.macAddress]
607 return diff, changed, network_info
608 device_spec = vim.vm.device.VirtualDeviceSpec(
609 device=nic_obj,
610 operation=vim.vm.device.VirtualDeviceSpec.Operation.remove
611 )
612 break
613
614 if not device_spec:
615 diff['after'] = diff['before']
616 return diff, changed, network_info
617
618 try:
619 task = vm_obj.ReconfigVM_Task(vim.vm.ConfigSpec(deviceChange=[device_spec]))
620 wait_for_task(task)
621 except (vim.fault.InvalidDeviceSpec, vim.fault.RestrictedVersion) as e:
622 self.module.fail_json(msg='failed to reconfigure guest', detail=e.msg)
623
624 if task.info.state == 'error':
625 self.module.fail_json(msg='failed to reconfigure guest', detail=task.info.error.msg)
626
627 vm_obj = self.get_vm()
628 nic_info, nic_obj_lst = self._get_nics_from_vm(vm_obj)
629
630 for nic in nic_info:
631 diff['after'].update({nic.get('mac_address'): copy.copy(nic)})
632
633 network_info = nic_info
634 if diff['after'] != diff['before']:
635 changed = True
636
637 return diff, changed, network_info
638
639 def _get_nic_info(self):
640 rv = {'network_info': []}
641 vm_obj = self.get_vm()
642 nic_info, nic_obj_lst = self._get_nics_from_vm(vm_obj)
643
644 rv['network_info'] = nic_info
645 return rv
646
647 def _nic_present(self):
648 changed = False
649 diff = {'before': {}, 'after': {}}
650 force = self.params['force']
651 label = self.params['label']
652 mac_address = self.params['mac_address']
653 network_name = self.params['network_name']
654 switch = self.params['switch']
655 vlan_id = self.params['vlan_id']
656
657 vm_obj = self.get_vm()
658 if not vm_obj:
659 self.module.fail_json(msg='could not find vm: {0}'.format(self.params['name']))
660
661 if self.params['device_type'] == 'pvrdma':
662 if int(vm_obj.config.version.split('vmx-')[-1]) > 19 or int(vm_obj.config.version.split('vmx-')[-1]) == 13:
663 self.params['pvrdma_device_protocol'] = None
664 else:
665 if self.params['pvrdma_device_protocol'] and self.params['pvrdma_device_protocol'] not in ['rocev1', 'rocev2']:
666 self.module.fail_json(msg="Valid values of parameter 'pvrdma_device_protocol' are 'rocev1',"
667 " 'rocev2' for VM with hardware version >= 14 and <= 19.")
668 if self.params['pvrdma_device_protocol'] is None:
669 self.params['pvrdma_device_protocol'] = 'rocev2'
670
671 network_obj = self._get_network_object(vm_obj)
672 nic_info, nic_obj_lst = self._get_nics_from_vm(vm_obj)
673 label_lst = [d.get('label') for d in nic_info]
674 mac_addr_lst = [d.get('mac_address') for d in nic_info]
675 vlan_id_lst = [d.get('vlan_id') for d in nic_info]
676 network_name_lst = [d.get('network_name') for d in nic_info]
677
678 # TODO: make checks below less inelegant
679 if ((vlan_id and vlan_id in vlan_id_lst) or (network_name and network_name in network_name_lst)
680 and not mac_address
681 and not label
682 and not force):
683 for nic in nic_info:
684 diff['before'].update({nic.get('mac_address'): copy.copy(nic)})
685 diff['after'].update({nic.get('mac_address'): copy.copy(nic)})
686 return diff, changed, nic_info
687
688 if not network_obj and (network_name or vlan_id):
689 self.module.fail_json(
690 msg='unable to find specified network_name/vlan_id ({0}), check parameters'.format(
691 network_name or vlan_id
692 )
693 )
694
695 for nic in nic_info:
696 diff['before'].update({nic.get('mac_address'): copy.copy(nic)})
697
698 if (mac_address and mac_address in mac_addr_lst) or (label and label in label_lst):
699 for nic_obj in nic_obj_lst:
700 if (mac_address and nic_obj.macAddress == mac_address) or (label and label == nic_obj.deviceInfo.label):
701 device_spec = self._new_nic_spec(vm_obj, nic_obj)
702
703 # fabricate diff for check_mode
704 if self.module.check_mode:
705 for nic in nic_info:
706 nic_mac = nic.get('mac_address')
707 nic_label = nic.get('label')
708 if nic_mac == mac_address or nic_label == label:
709 diff['after'][nic_mac] = copy.deepcopy(nic)
710 diff['after'][nic_mac].update({'switch': switch or nic['switch']})
711 if network_obj:
712 diff['after'][nic_mac].update(
713 {
714 'vlan_id': self._get_vlanid_from_network(network_obj),
715 'network_name': network_obj.name
716 }
717 )
718 else:
719 diff['after'].update({nic_mac: copy.deepcopy(nic)})
720
721 if (not mac_address or mac_address not in mac_addr_lst) and (not label or label not in label_lst):
722 device_spec = self._new_nic_spec(vm_obj, None)
723 device_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
724 if self.module.check_mode:
725 # fabricate diff/returns for checkmode
726 diff['after'] = copy.deepcopy(diff['before'])
727 nic_mac = mac_address
728 if not nic_mac:
729 nic_mac = 'AA:BB:CC:DD:EE:FF'
730 if not label:
731 label = 'check_mode_adapter'
732 diff['after'].update(
733 {
734 nic_mac: {
735 'vlan_id': self._get_vlanid_from_network(network_obj),
736 'network_name': network_obj.name,
737 'label': label,
738 'mac_address': nic_mac,
739 'unit_number': 40000
740 }
741 }
742 )
743
744 if self.module.check_mode:
745 network_info = [diff['after'][i] for i in diff['after']]
746 if diff['after'] != diff['before']:
747 changed = True
748 return diff, changed, network_info
749
750 if not self.module.check_mode:
751 try:
752 task = vm_obj.ReconfigVM_Task(vim.vm.ConfigSpec(deviceChange=[device_spec]))
753 wait_for_task(task)
754 except (vim.fault.InvalidDeviceSpec, vim.fault.RestrictedVersion) as e:
755 self.module.fail_json(msg='failed to reconfigure guest', detail=e.msg)
756 except TaskError as task_e:
757 self.module.fail_json(msg=to_native(task_e))
758
759 if task.info.state == 'error':
760 self.module.fail_json(msg='failed to reconfigure guest', detail=task.info.error.msg)
761
762 vm_obj = self.get_vm()
763 network_info, nic_obj_lst = self._get_nics_from_vm(vm_obj)
764 for nic in network_info:
765 diff['after'].update({nic.get('mac_address'): copy.copy(nic)})
766
767 if diff['after'] != diff['before']:
768 changed = True
769 return diff, changed, network_info
770
771
772 def main():
773 argument_spec = base_argument_spec()
774 argument_spec.update(
775 name=dict(type='str'),
776 uuid=dict(type='str'),
777 use_instance_uuid=dict(type='bool', default=False),
778 moid=dict(type='str'),
779 folder=dict(type='str'),
780 datacenter=dict(type='str', default='ha-datacenter'),
781 esxi_hostname=dict(type='str'),
782 cluster=dict(type='str'),
783 mac_address=dict(type='str'),
784 vlan_id=dict(type='int'),
785 network_name=dict(type='str'),
786 device_type=dict(type='str', default='vmxnet3'),
787 pvrdma_device_protocol=dict(type='str'),
788 label=dict(type='str'),
789 switch=dict(type='str'),
790 connected=dict(type='bool', default=True),
791 start_connected=dict(type='bool', default=True),
792 wake_onlan=dict(type='bool', default=False),
793 directpath_io=dict(type='bool', default=False),
794 physical_function_backing=dict(type='str'),
795 virtual_function_backing=dict(type='str'),
796 allow_guest_os_mtu_change=dict(type='bool', default=True),
797 force=dict(type='bool', default=False),
798 gather_network_info=dict(type='bool', default=False, aliases=['gather_network_facts']),
799 guest_control=dict(type='bool', default=True),
800 state=dict(type='str', default='present', choices=['absent', 'present'])
801 )
802
803 module = AnsibleModule(
804 argument_spec=argument_spec,
805 mutually_exclusive=[
806 ['vlan_id', 'network_name']
807 ],
808 required_one_of=[
809 ['name', 'uuid', 'moid']
810 ],
811 supports_check_mode=True
812 )
813
814 pyv = PyVmomiHelper(module)
815
816 if module.params['gather_network_info']:
817 nics = pyv._get_nic_info()
818 network_data = {}
819 nics_sorted = sorted(nics.get('network_info'), key=lambda k: k['unit_number'])
820 for n, i in enumerate(nics_sorted):
821 key_name = '{0}'.format(n)
822 network_data[key_name] = i
823 network_data[key_name].update({'mac_addr': i['mac_address'], 'name': i['network_name']})
824
825 module.exit_json(network_info=nics.get('network_info'), network_data=network_data, changed=False)
826
827 if module.params['state'] == 'present':
828 diff, changed, network_info = pyv._nic_present()
829
830 if module.params['state'] == 'absent':
831 if not module.params['mac_address']:
832 module.fail_json(msg='parameter mac_address required when removing nics')
833 diff, changed, network_info = pyv._nic_absent()
834
835 module.exit_json(changed=changed, network_info=network_info, diff=diff)
836
837
838 if __name__ == '__main__':
839 main()