Completed
Pull Request — master (#462)
by
unknown
02:34
created

VMNicEdit   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %
Metric Value
wmc 6
dl 0
loc 47
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B run() 0 45 6
1
from pyVmomi import vim
2
3
from vmwarelib import inventory
4
from vmwarelib import checkinputs
5
from vmwarelib.actions import BaseAction
6
7
8
class VMNicEdit(BaseAction):
9
10
    def run(self, vm_id, vm_name, network_adapter, network_name):
11
        # check means of finding the VM was provided
12
        checkinputs.vm_identifier(vm_id, vm_name)
13
        # convert ids to stubs
14
        vm = inventory.get_virtualmachine(self.si_content,
15
                                          moid=vm_id,
16
                                          name=vm_name)
17
        network_obj = inventory.get_network(self.si_content,
18
                                            name=network_name)
19
20
        # find correct NIC
21
        for device in vm.config.hardware.device:
22
            if isinstance(device, vim.vm.device.VirtualEthernetCard)\
23
                    and device.deviceInfo.label == network_adapter:
24
                nic = device
25
26
        #Different test method due to fact that object
27
        #isn't instantiated if not found
28
        try:
29
            nic
30
        except:
31
            raise Exception('Unable to find Network Adapter provided')
32
33
        # Create object for new Specification
34
        new_spec = vim.vm.device.VirtualDeviceSpec()
35
        new_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
36
        new_spec.device = nic
37
38
        #If network name provided assign new network
39
        # Room to expand the following to set additional flags/values
40
        if network_name:
41
            new_spec.device.backing.network = network_obj
42
            new_spec.device.backing.deviceName = network_obj.name
43
            new_spec.device.deviceInfo.summary = network_obj.name
44
45
        #format changes for config spec update
46
        dev_changes = []
47
        dev_changes.append(new_spec)
48
        spec = vim.vm.ConfigSpec()
49
        spec.deviceChange = dev_changes
50
51
        task = vm.ReconfigVM_Task(spec)
52
        self._wait_for_task(task)
53
54
        return {'state': str(task.info.state)}
55