Python pyVmomi.vim.Network() Examples

The following are 28 code examples of pyVmomi.vim.Network(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyVmomi.vim , or try the search function .
Example #1
Source File: host.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def get_net_item(self, object_type, name):
        """
        Retrieves a network object of the specified type and name from a host.

        :param str object_type: Type of object to get:
        (portgroup | vswitch | proxyswitch | vnic | pnic)
        :param str name: Name of network object [default: first object found]
        :return: The network object
        :rtype: vim.Network or vim.VirtualSwitch
        or vim.VirtualEthernetCard or None
        .. todo:: determine what possible return types there are
        """
        if name:
            return self.get_net_obj(object_type, name)
        else:
            return self.get_net_objs(object_type)[0] 
Example #2
Source File: vm.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def remove_nic(self, nic_number):
        """Deletes a vNIC based on it's number.
        :param int nic_number: Number of the vNIC to delete
        :return: If removal succeeded
        :rtype: bool
        """
        nic_label = "Network adapter " + str(nic_number)
        self._log.debug("Removing Virtual %s from '%s'", nic_label, self.name)
        virtual_nic_device = self.get_nic_by_name(nic_label)
        if virtual_nic_device is not None:
            virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
            virtual_nic_spec.operation = \
                vim.vm.device.VirtualDeviceSpec.Operation.remove
            virtual_nic_spec.device = virtual_nic_device

            # Apply change to VM
            self._edit(vim.vm.ConfigSpec(deviceChange=[virtual_nic_spec]))
            return True
        else:
            self._log.error("Virtual %s could not be found for '%s'",
                            nic_label, self.name)
            return False 
Example #3
Source File: vm.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def edit_nic(self, nic_id, network=None, summary=None):
        """Edits a vNIC based on it's number.
        :param int nic_id: Number of network adapter on VM
        :param network: Network to assign the vNIC to
        :type network: vim.Network
        :param str summary: Human-readable device description
        :return: If the edit operation was successful
        :rtype: bool
        """
        nic_label = 'Network adapter ' + str(nic_id)
        self._log.debug("Changing '%s' on VM '%s'", nic_label, self.name)
        virtual_nic_device = self.get_nic_by_name(nic_label)
        if not virtual_nic_device:
            self._log.error('Virtual %s could not be found!', nic_label)
            return False
        nic_spec = vim.vm.device.VirtualDeviceSpec()
        nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
        nic_spec.device = virtual_nic_device
        if summary:
            nic_spec.device.deviceInfo.summary = str(summary)
        if network:
            self._log.debug("Changing PortGroup to: '%s'", network.name)
            nic_spec.device.backing.network = network
            nic_spec.device.backing.deviceName = network.name

        # Apply change to VM
        self._edit(vim.vm.ConfigSpec(deviceChange=[nic_spec]))
        return True

    # Based on: delete_nic_from_vm in pyvmomi-community-samples 
Example #4
Source File: vm.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def get_nics(self):
        """Returns a list of all Virtual Network Interface Cards (vNICs) on the VM.
        :return: All vNICs on the VM
        :rtype: list(vim.vm.device.VirtualEthernetCard) or list
        """
        return [dev for dev in self._vm.config.hardware.device if is_vnic(dev)] 
Example #5
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def create_network(self, name, cidr=None, dhcp=True, nat=True, domain=None, plan='kvirt', overrides={}):
        return {'result': 'failure', 'reason': "Not implemented yet..."}
        si = self.si
        cluster = self.clu
        networkFolder = self.dc.networkFolder
        rootFolder = self.rootFolder
        net = find(si, rootFolder, vim.Network, name)
        if net is not None:
            return {'result': 'failure', 'reason': "Network %s already there" % name}
        if self.distributed:
            pnic_specs = []
            dvs_host_configs = []
            uplink_port_names = []
            dvs_create_spec = vim.DistributedVirtualSwitch.CreateSpec()
            dvs_config_spec = vim.DistributedVirtualSwitch.ConfigSpec()
            dvs_config_spec.name = name
            dvs_config_spec.uplinkPortPolicy = vim.DistributedVirtualSwitch.NameArrayUplinkPortPolicy()
            for x in range(len(cluster.host)):
                uplink_port_names.append("dvUplink%d" % x)
            for host in cluster.host:
                dvs_config_spec.uplinkPortPolicy.uplinkPortName = uplink_port_names
                dvs_config_spec.maxPorts = 2000
                pnic_spec = vim.dvs.HostMember.PnicSpec()
                pnic_spec.pnicDevice = 'vmnic1'
                pnic_specs.append(pnic_spec)
                dvs_host_config = vim.dvs.HostMember.ConfigSpec()
                dvs_host_config.operation = vim.ConfigSpecOperation.add
                dvs_host_config.host = host
                dvs_host_configs.append(dvs_host_config)
                dvs_host_config.backing = vim.dvs.HostMember.PnicBacking()
                dvs_host_config.backing.pnicSpec = pnic_specs
                dvs_config_spec.host = dvs_host_configs
                dvs_create_spec.configSpec = dvs_config_spec
            dvs_create_spec.productInfo = vim.dvs.ProductSpec(version='5.1.0')
            networkFolder.CreateDistributedVirtualSwitch()
        return {'result': 'success'} 
Example #6
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def list_networks(self):
        si = self.si
        rootFolder = si.content.rootFolder
        networks = {}
        view = si.content.viewManager.CreateContainerView(rootFolder, [vim.dvs.DistributedVirtualPortgroup], True)
        dvslist = collectproperties(si, view=view, objtype=vim.dvs.DistributedVirtualPortgroup, pathset=['name'],
                                    includemors=True)
        view = si.content.viewManager.CreateContainerView(rootFolder, [vim.Network], True)
        netlist = collectproperties(si, view=view, objtype=vim.Network, pathset=['name'], includemors=True)
        for o in netlist:
            network = o['obj']
            cidr, dhcp, domainname = '', '', ''
            mode = 'accesible' if network.summary.accessible else 'notaccessible'
            networks[network.name] = {'cidr': cidr, 'dhcp': dhcp, 'domain': domainname, 'type': 'routed', 'mode': mode}
        for o in dvslist:
            network = o['obj']
            cidr, dhcp, domainname, mode = '', '', '', ''
            networks[network.name] = {'cidr': cidr, 'dhcp': dhcp, 'domain': domainname, 'type': 'routed', 'mode': mode}
        return networks 
Example #7
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def add_nic(self, name, network):
        if network == 'default':
            network = 'VM Network'
        si = self.si
        dc = self.dc
        vmFolder = dc.vmFolder
        vm = findvm(si, vmFolder, name)
        if vm is None:
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        spec = vim.vm.ConfigSpec()
        nicnumber = len([dev for dev in vm.config.hardware.device if "addressType" in dir(dev)])
        nicname = 'Network adapter %d' % (nicnumber + 1)
        nicspec = createnicspec(nicname, network)
        nic_changes = [nicspec]
        spec.deviceChange = nic_changes
        t = vm.ReconfigVM_Task(spec=spec)
        waitForMe(t)
        return {'result': 'success'} 
Example #8
Source File: vsphere_class.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def get_network(self, network_name, distributed=False):
        """
        Finds and returns the named Network.

        :param str network_name: Name or path of the Network
        :param bool distributed: If the Network is a Distributed PortGroup
        :return: The network found
        :rtype: vim.Network or vim.dvs.DistributedVirtualPortgroup or None
        """
        if not distributed:
            return self.get_obj(container=self.datacenter.networkFolder,
                                vimtypes=[vim.Network],
                                name=str(network_name), recursive=True)
        else:
            return self.get_item(vim.dvs.DistributedVirtualPortgroup,
                                 network_name) 
Example #9
Source File: vSphere.py    From im with GNU General Public License v3.0 6 votes vote down vote up
def gen_nic(num, network):
        """
        Get a nic for the specified network
        """
        nic = vim.vm.device.VirtualDeviceSpec()
        nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add  # or edit if a device exists
        nic.device = vim.vm.device.VirtualVmxnet3()
        nic.device.wakeOnLanEnabled = True
        nic.device.addressType = 'assigned'
        nic.device.key = 4000  # 4000 seems to be the value to use for a vmxnet3 device
        nic.device.deviceInfo = vim.Description()
        nic.device.deviceInfo.label = "Network Adapter %d" % num
        nic.device.deviceInfo.summary = "Net summary"
        nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
        nic.device.backing.network = network
        nic.device.backing.deviceName = "Device%d" % num
        nic.device.backing.useAutoDetect = False
        nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        nic.device.connectable.startConnected = True
        nic.device.connectable.allowGuestControl = True

        return nic 
Example #10
Source File: nsxt_vcenter_moids.py    From ansible-module-chaperone with Apache License 2.0 6 votes vote down vote up
def find_object_by_name(module,content, object_name):
    try:
    	if(object_name == module.params['datacenter']):
    	    vmware_objects = get_all_objs(module,content,[vim.Datacenter])
    	elif (object_name == module.params['cluster']):
    	    vmware_objects = get_all_objs(module,content,[vim.ComputeResource])
    	elif (object_name == module.params['datastore']):
            vmware_objects = get_all_objs(module,content,[vim.Datastore])
    	elif (object_name == module.params['portgroup1'] or module.params['portgroup2'] or module.params['portgroup3'] ):
            vmware_objects = get_all_objs(module,content,[vim.dvs.DistributedVirtualPortgroup, vim.Network])
 
    	for object in vmware_objects:
            if object.name == object_name:
            	logger.info('object: %s',object.name)
            	return object
    	return None
    except Exception as err:
       module.fail_json(changed=False, msg= "Error Occured while Finding the Object by name. Error is %s" %(to_native(err))) 
Example #11
Source File: host.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def get_net_obj(self, object_type, name, refresh=False):
        """
        Retrieves a network object of the specified type and name from a host.

        :param str object_type: Type of object to get:
        (portgroup | vswitch | proxyswitch | vnic | pnic)
        :param name: Name of network object
        :param bool refresh: Refresh the host's network system information
        :return: The network object
        :rtype: vim.Network or vim.VirtualSwitch
        or vim.VirtualEthernetCard or None

        .. todo:: determine what possible return types there are
        """
        objs = self.get_net_objs(object_type=object_type, refresh=refresh)
        obj_name = name.lower()
        if objs is not None:
            for obj in objs:
                if object_type == "portgroup" or object_type == "proxyswitch":
                    if obj.spec.name.lower() == obj_name:
                        return obj
                elif object_type == "pnic" or object_type == "vnic":
                    if obj.device.lower() == obj_name:
                        return obj
                elif obj.name.lower() == obj_name:
                    return obj
        return None 
Example #12
Source File: vmware.py    From skylight with GNU General Public License v3.0 5 votes vote down vote up
def get_all_host_objs(self, cluster_name=None, esxi_host_name=None):
        """
        Function to get all host system managed object

        Args:
            cluster_name: Name of Cluster
            esxi_host_name: Name of ESXi server

        Returns: A list of all host system managed objects, else empty list

        """
        host_obj_list = []
        if not self.is_vcenter():
            hosts = get_all_objs(self.content, [vim.HostSystem]).keys()
            if hosts:
                host_obj_list.append(list(hosts)[0])
        else:
            if cluster_name:
                cluster_obj = self.find_cluster_by_name(cluster_name=cluster_name)
                if cluster_obj:
                    host_obj_list = [host for host in cluster_obj.host]
                else:
                    self.module.fail_json(changed=False, msg="Cluster '%s' not found" % cluster_name)
            elif esxi_host_name:
                if isinstance(esxi_host_name, str):
                    esxi_host_name = [esxi_host_name]

                for host in esxi_host_name:
                    esxi_host_obj = self.find_hostsystem_by_name(host_name=host)
                    if esxi_host_obj:
                        host_obj_list = [esxi_host_obj]
                    else:
                        self.module.fail_json(changed=False, msg="ESXi '%s' not found" % host)

        return host_obj_list

    # Network related functions 
Example #13
Source File: vm.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def get_nic_by_network(self, network):
        """Finds a vNIC by it's network backing.
        :param vim.Network network: Network of the vNIC to match
        :return: Name of the vNIC
        :rtype: str or None
        """
        for dev in self._vm.config.hardware.device:
            if is_vnic(dev) and dev.backing.network == network:
                return dev
        self._log.debug("Could not find vNIC with network '%s' on '%s'",
                        network.name, self.name)
        return None 
Example #14
Source File: fix_mac.py    From contrail-server-manager with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()
    try:
        if is_xenial_or_above():
            ssl = __import__("ssl")
            context = ssl._create_unverified_context()
            si = connect.SmartConnect(host=args.host,
                                      user=args.user,
                                      pwd=args.password,
                                      port=args.port, sslContext=context)
        else:
            si = connect.SmartConnect(host=args.host,
                                      user=args.user,
                                      pwd=args.password,
                                      port=args.port)
        si_content = si.RetrieveContent()
    except:
        print "Unable to connect to %s" % args.host
        exit(1)
    # get VM object
    vm_obj = get_obj(si_content, [vim.VirtualMachine], args.vm_name)
    if not vm_obj:
        print "VM %s not pressent" %(args.vm_name)
        exit(1)
    #net_obj = get_obj(si_content, [vim.Network], args.network_name)
    nics = args.nics.split(',')
    for nic in nics:
        if not nic:
           continue
        task = update_mac(nic, vm_obj, si_content)
        wait_for_task(task)
    connect.Disconnect(si) 
Example #15
Source File: get_portgroup.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for retrieving a port group
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # searching for port group
        pg = get_obj(content, [vim.Network], args.portgroupname)
        print(pg)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : {0}".format(error.msg))
        return -1

    return 0


# Start program 
Example #16
Source File: vm.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def get_nic_by_name(self, name):
        """Gets a Virtual Network Interface Card (vNIC) from a VM.
        :param str  name: Name of the vNIC
        :return: The vNIC found
        :rtype: vim.vm.device.VirtualEthernetCard or None
        """
        for dev in self._vm.config.hardware.device:
            if is_vnic(dev) and dev.deviceInfo.label.lower() == name.lower():
                return dev
        self._log.debug("Could not find vNIC '%s' on '%s'", name, self.name)
        return None 
Example #17
Source File: get_vcenter_id.py    From ansible-module-chaperone with Apache License 2.0 5 votes vote down vote up
def core(module):

    vim_type = module.params['vcenter_vim_type']
    vcenter_object_name = module.params['vcenter_object_name']

    vim_rec_type = {
        'cluster': vim.ClusterComputeResource,
        'datacenter': vim.Datacenter,
        'datastore': vim.Datastore,
        'vds': vim.DistributedVirtualSwitch,
        'dvs-port': vim.Network,
        'vm': vim.VirtualMachine
    }

    try:
        vimtype = vim_rec_type[vim_type]
    except KeyError:
        module.fail_json(msg="Please specify valid vim type: cluster, datacenter, datastore, vds, vm")

    si = si_connect(module)

    vcenter_id = get_id(module, si,
                        [vimtype],
                        vcenter_object_name,
                        False, True)

    return False, vcenter_id 
Example #18
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def delete_network(self, name=None, cidr=None):
        si = self.si
        rootFolder = self.rootFolder
        if self.distributed:
            net = find(si, rootFolder, vim.dvs.DistributedVirtualPortgroup, name)
        else:
            net = find(si, rootFolder, vim.Network, name)
        if net is None:
            return {'result': 'failure', 'reason': "Network %s not found" % name}
        net.Destroy()
        return {'result': 'success'} 
Example #19
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def get_network(self, network_name):
        """Fetch the network object from specified network name

        Args:
            network_name: The name of the network from Vmware
        Returns: A object of vim.Network object
        """
        network = self.get_obj(vimtype=vim.Network, name=network_name)
        if not network:
            raise NotFoundError
        return network 
Example #20
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def list_networks(self):
        """Fetch the list of network names

        Returns: A list of Network names
        """
        return [str(h.name) for h in self.get_obj_list(vim.Network)] 
Example #21
Source File: network.py    From vsphere-automation-sdk-python with MIT License 5 votes vote down vote up
def detect_stdportgroup(context, host_name, network_name):
    """Find Distributed Switch based on host and network name"""
    # Ensure the standard switch is available on the host
    names = set([host_name])

    # Use vAPI find the Host managed identities
    host_summaries = context.client.vcenter.Host.list(
        Host.FilterSpec(names=names))

    for host_summary in host_summaries:
        # Convert the host identifier into a ManagedObject
        host = host_summary.host
        host_mo = vim.HostSystem(host, context.soap_stub)

        for network_mo in host_mo.network:
            if (type(network_mo) == vim.Network and
                        network_mo.name == network_name):
                network = network_mo._moId
                print(
                    "Detected Standard Portgroup '{}' as {} on Host '{}' ({})".
                    format(network_name, network, host_name, host))
                context.testbed.entities['HOST_STANDARD_SWITCH_IDS'][
                    host_name] = network
                return True

    print("Standard Portgroup '{}' missing on Host '{}'".
          format(network_name, host_name))
    return False 
Example #22
Source File: vSphere.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def CreateContainerView(self, rootFolder, type_list, flag):
        container = MagicMock()
        c = MagicMock()
        container.view = [c]
        if type_list[0] == vim.Datastore:
            c.name = "datastore"
        elif type_list[0] == vim.Network:
            c.name = "vsnet1"
            c.summary.ipPoolName = "ippool1"
            c2 = MagicMock()
            c2.name = "vsnet2"
            c2.summary.ipPoolName = "ippool2"
            container.view.append(c2)
        elif type_list[0] == vim.VirtualMachine:
            c.name = "vm-template"
            c.Clone.return_value = vim.Task("CreateVM")
            c.Suspend.return_value = vim.Task("SuspendVM")
            c.PowerOn.return_value = vim.Task("PowerOnVM")
            c.Reset.return_value = vim.Task("ResetVM")
            c.PowerOff.return_value = vim.Task("PowerOffVM")
            c.Destroy.return_value = vim.Task("DestroyVM")
            c.summary.runtime.powerState = self.vm_state
            c.runtime.powerState = self.vm_state
            nic1 = MagicMock()
            nic1.ipAddress = "10.0.0.1"
            nic2 = MagicMock()
            nic2.ipAddress = "8.8.8.8"
            c.guest.net = [nic1, nic2]
            dev1 = MagicMock()
            dev2 = vim.vm.device.VirtualSCSIController()
            c.config.hardware.device = [dev1, dev2]
            dev1.backing.fileName = ""
            dev1.unitNumber = 1
        else:
            raise Exception("Invalid type")

        return container 
Example #23
Source File: vSphere.py    From im with GNU General Public License v3.0 5 votes vote down vote up
def get_networks(content, datacenter):
        """
        Returns all metworks
        """
        nets = {}
        poolmgr = vim.IpPoolManager()
        ippools = poolmgr.QueryIpPools(datacenter)
        container = content.viewManager.CreateContainerView(content.rootFolder, [vim.Network], True)
        for c in container.view:
            is_public = None
            for ippool in ippools:
                if c.summary.ipPoolName == ippool.name:
                    is_public = not any([IPAddress(ippool.ipv4Config.subnetAddress) in IPNetwork(
                        mask) for mask in Config.PRIVATE_NET_MASKS])
                    break

            nets[c.name] = (c, is_public, ippool.ipv4Config)

        return nets 
Example #24
Source File: vmware_guest2.py    From skylight with GNU General Public License v3.0 5 votes vote down vote up
def get_network(self, network):
        if network not in self.networks:
            self.networks[network] = self.find_obj(self.content, [vim.Network], network)

        return self.networks[network] 
Example #25
Source File: vmware.py    From skylight with GNU General Public License v3.0 5 votes vote down vote up
def find_network_by_name(content, network_name):
    return find_object_by_name(content, network_name, [vim.Network]) 
Example #26
Source File: vsphere_interface.py    From ADLES with Apache License 2.0 4 votes vote down vote up
def _configure_nics(self, vm, networks, instance=None):
        """
        Configures Virtual Network Interfaces Cards (vNICs)
        for a service instance.

        :param vm: Virtual Machine to configure vNICs on
        :type vm: vim.VirtualMachine
        :param list networks: List of networks to configure
        :param int instance: Current instance of a folder
        for Deployment purposes
        """
        self._log.info("Editing NICs for VM '%s'", vm.name)
        num_nics = len(list(vm.network))
        num_nets = len(networks)
        nets = networks  # Copy the passed variable so we can edit it later

        # Ensure number of NICs on VM
        # matches number of networks configured for the service
        #
        # Note that monitoring interfaces will be
        # counted and included in the networks list
        if num_nics > num_nets:     # Remove excess interfaces
            diff = int(num_nics - num_nets)
            self._log.debug("VM '%s' has %d extra NICs, removing...",
                            vm.name, diff)
            for _, nic in enumerate(reversed(range(num_nics)), start=1):
                vm.remove_nic(nic)
        elif num_nics < num_nets:   # Create missing interfaces
            diff = int(num_nets - num_nics)
            self._log.debug("VM '%s' is deficient %d NICs, adding...",
                            vm.name, diff)
            # Add NICs to VM and pop them from the list of networks
            for _ in range(diff):
                # Select NIC hardware
                nic_model = ("vmxnet3" if vm.has_tools() else "e1000")
                net_name = nets.pop()
                vm.add_nic(network=self.server.get_network(net_name),
                           model=nic_model, summary=net_name)

        # Edit the interfaces
        # (NOTE: any NICs added earlier shouldn't be affected by this)
        for i, net_name in enumerate(networks, start=1):
            # Setting the summary to network name
            # allows viewing of name without requiring
            # read permissions to the network itself
            if instance is not None:
                # Resolve generic networks for deployment phase
                net_name = self._get_net(net_name, instance)
            network = self.server.get_network(net_name)
            if vm.get_nic_by_id(i).backing.network == network:
                continue  # Skip NICs that are already configured
            else:
                vm.edit_nic(nic_id=i, network=network, summary=net_name) 
Example #27
Source File: add_nic_to_vm.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def add_nic(si, vm, network_name):
    """
    :param si: Service Instance
    :param vm: Virtual Machine Object
    :param network_name: Name of the Virtual Network
    """
    spec = vim.vm.ConfigSpec()
    nic_changes = []

    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add

    nic_spec.device = vim.vm.device.VirtualE1000()

    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.summary = 'vCenter API test'

    content = si.RetrieveContent()
    network = get_obj(content, [vim.Network], network_name)
    if isinstance(network, vim.OpaqueNetwork):
        nic_spec.device.backing = \
            vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo()
        nic_spec.device.backing.opaqueNetworkType = \
            network.summary.opaqueNetworkType
        nic_spec.device.backing.opaqueNetworkId = \
            network.summary.opaqueNetworkId
    else:
        nic_spec.device.backing = \
            vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
        nic_spec.device.backing.useAutoDetect = False
        nic_spec.device.backing.deviceName = network

    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = False
    nic_spec.device.connectable.status = 'untried'
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'assigned'

    nic_changes.append(nic_spec)
    spec.deviceChange = nic_changes
    e = vm.ReconfigVM_Task(spec=spec)
    print("NIC CARD ADDED") 
Example #28
Source File: vSphere.py    From im with GNU General Public License v3.0 4 votes vote down vote up
def map_radl_vsphere_networks(radl_nets, vsphere_nets):
        """
        Generate a mapping between the RADL networks and the ONE networks

        Arguments:
           - radl_nets(list of :py:class:`radl.network` objects): RADL networks.
           - vsphere_nets(a list of :py:class:`vim.Network` objects): vSpehere networks

         Returns: a dict with key the RADL network id and value a tuple (one_net_name, one_net_id, is_public)
        """
        # TODO: get the ip and subnet of an interface to select the network
        res = {}

        used_nets = []
        last_net = None
        for radl_net in radl_nets:
            # First check if the user has specified a provider ID
            net_provider_id = radl_net.getValue('provider_id')
            if net_provider_id:
                for net_name, net_values in vsphere_nets.items():
                    is_public = net_values[1]
                    # If the name is the same and have the same "publicity" value
                    if net_name == net_provider_id and radl_net.isPublic() == is_public:
                        res[radl_net.id] = net_values
                        used_nets.append(net_name)
                        break
            else:
                for net_name, net_values in vsphere_nets.items():
                    is_public = net_values[1]
                    if net_name not in used_nets and radl_net.isPublic() == is_public:
                        res[radl_net.id] = net_values
                        used_nets.append(net_name)
                        last_net = net_values
                        break
                if radl_net.id not in res:
                    res[radl_net.id] = last_net

        # In case of there are no private network, use public ones for non mapped networks
        used_nets = []
        for radl_net in radl_nets:
            if not res[radl_net.id]:
                for net_name, net_values in vsphere_nets.items():
                    is_public = net_values[1]
                    if net_name not in used_nets and is_public:
                        res[radl_net.id] = net_values
                        used_nets.append(net_name)
                        last_net = net_values
                        break
                if radl_net.id not in res:
                    res[radl_net.id] = last_net

        return res