vmware / vmware/pyvmomi

How do I create NIC with static IP?

Open
#461 13 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

question
Dominant language
Python
Stars
2.3k
Forks
763
PR merge metrics
No merged PRs in 30d

Description

I have a VM with no NIC and it is powered off. When I execute the following code:

import atexit
import time
import ssl 
from pyVim import connect
from pyVmomi import vim, vmodl

# Disabling SSL certificate verification 
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) 
context.verify_mode = ssl.CERT_NONE 

inputs = {'vcenter_ip': '10.7.32.119',
          'vcenter_password': 'password',
          'vcenter_user': 'root',
          'vm_name' : 'myName',
          'isDHCP' : False,
          'vm_ip' : '10.7.42.91',
          'subnet' : '255.255.255.0',
          'gateway' : '10.7.42.40',
          'dns' : ['company.com', 'company.com'],
          'domain' : 'esx10g.company.com'
          }


def get_obj(content, vimtype, name):
    obj = None
    container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
    for c in container.view:
        if c.name == name:
            obj = c
            break
    return obj


def add_nic(vm, network):
    spec = vim.vm.ConfigSpec()

    # add Switch here
    dev_changes = []
    switch_spec                = vim.vm.device.VirtualDeviceSpec()
    switch_spec.operation      = vim.vm.device.VirtualDeviceSpec.Operation.add
    switch_spec.device         = vim.vm.device.VirtualVmxnet3()

    switch_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    switch_spec.device.backing.useAutoDetect = False
    switch_spec.device.backing.deviceName = network.name
    switch_spec.device.backing.network = network
    switch_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    switch_spec.device.connectable.startConnected = True
    switch_spec.device.connectable.connected = True

    dev_changes.append(switch_spec)

    spec.deviceChange = dev_changes
    output = vm.ReconfigVM_Task(spec=spec)
    time.sleep(2)
    print output.info


def wait_for_task(task, actionName='job', hideResult=False):
    """
    Waits and provides updates on a vSphere task
    """

    while task.info.state == vim.TaskInfo.State.running or task.info.state == vim.TaskInfo.State.queued:
        time.sleep(2)

    if task.info.state == vim.TaskInfo.State.success:
        if task.info.result is not None and not hideResult:
            out = '%s completed successfully, result: %s' % (actionName, task.info.result)
            print out
        else:
            out = '%s completed successfully.' % actionName
            print out
    else:
        out = '%s did not complete successfully: %s' % (actionName, task.info.error)
        print out
        raise task.info.error #error happens here

    return task.info.result


def ip_assign(vm):
    adaptermap = vim.vm.customization.AdapterMapping()
    globalip = vim.vm.customization.GlobalIPSettings()
    adaptermap.adapter = vim.vm.customization.IPSettings()

    """Static IP Configuration"""
    adaptermap.adapter.ip = vim.vm.customization.FixedIp()
    adaptermap.adapter.ip.ipAddress = inputs['vm_ip']
    adaptermap.adapter.subnetMask = inputs['subnet']
    adaptermap.adapter.gateway = inputs['gateway']  
    globalip.dnsServerList = inputs['dns']

    adaptermap.adapter.dnsDomain = inputs['domain']

    # Hostname settings
    ident = vim.vm.customization.LinuxPrep()
    ident.domain = inputs['domain']
    ident.hostName = vim.vm.customization.FixedName()
    ident.hostName.name = inputs['vm_name']

    customspec = vim.vm.customization.Specification()
    customspec.nicSettingMap = [adaptermap]
    customspec.globalIPSettings = globalip
    customspec.identity = ident

    print "Reconfiguring VM Networks . . ."
    task = vm.Customize(spec=customspec)

    # Wait for Network Reconfigure to complete
    wait_for_task(task, "config task") #error happens here



if __name__ == '__main__':
    service_instance = connect.SmartConnect(host=inputs['vcenter_ip'], user=inputs['vcenter_user'], pwd=inputs['vcenter_password'], sslContext=context)
    atexit.register(connect.Disconnect, service_instance)

    content = service_instance.RetrieveContent()
    vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name'])
    network = get_obj(content, [vim.Network], "DMZ")

    add_nic(vm, network)
    ip_assign(vm) #error happens here

NIC gets created but on assigning IP it gets an error:

Reconfiguring VM Networks . . .
config task did not complete successfully: (vmodl.fault.NotSupported) {
   dynamicType = <unset>,
   dynamicProperty = (vmodl.DynamicProperty) [],
   msg = 'The operation is not supported on the object.',
   faultCause = <unset>,
   faultMessage = (vmodl.LocalizableMessage) []
}
Traceback (most recent call last):
  File "test2.py", line 124, in <module>
    ip_assign(vm)
  File "test2.py", line 111, in ip_assign
    wait_for_task(task, "config task")
  File "test2.py", line 77, in wait_for_task
    raise task.info.error
pyVmomi.VmomiSupport.NotSupported: (vmodl.fault.NotSupported) {
   dynamicType = <unset>,
   dynamicProperty = (vmodl.DynamicProperty) [],
   msg = 'The operation is not supported on the object.',
   faultCause = <unset>,
   faultMessage = (vmodl.LocalizableMessage) []
}

What am I missing? What am I doing wrong? How do I create a new NIC with static IP assigned?

Would much appreciate any help!
@jm66
@Ctesias
@rreubenur
@thedeco
@tianhao64
@snobear
@ciorceri
@sitle
@bsherman
@czee

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the script and compare the successful ReconfigVM_Task in add_nic with the failing Customize task in ip_assign, inspecting task.info.error. Done means the existing powered-off VM receives the requested static IP through the shown workflow without the NotSupported failure.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
networking
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.