vsphere api to change ip address of VirtualMachine

Rossini picture Rossini · Jun 26, 2013 · Viewed 7k times · Source

I'm new to the vsphere api and I'm trying to change the network settings of a virtual machine from dynamic ip to static ip but I can't find the setting. Here's the code I have so far, it connects to vsphere, finds the virtual machine, and changes the name of the VM.
I assume there is a setting in the VirtualMachineConfigSpec that will also change the network settings, but I can't find it.

VimClient vimClient = new VimClient();
ServiceContent serviceContent = vimClient.Connect("https://[MY ADDRESS]/sdk");
UserSession us = vimClient.Login("[USERNAME]","[PASSWORD]");

ManagedObjectReference _svcRef = new ManagedObjectReference();
_svcRef.Type = "ServiceInstance";
_svcRef.Value = "ServiceInstance";

NameValueCollection filterForVM = new NameValueCollection();
filterForVM.Add("Name","[VIRTUAL MACHINE NAME]");
VirtualMachine vm = (VirtualMachine)vimClient.FindEntityView(typeof(VirtualMachine),null,filterForVM,null);
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();

vmConfigSpec.Name = "[NEW NAME]"; // change the VM name
vmConfigSpec.???? // how to set the ip address

vm.ReconfigVM_Task(vmConfigSpec);

vimClient.Disconnect();

Answer

Mikhail Shcherbakov picture Mikhail Shcherbakov · Jul 1, 2013

VMware API don’t have a setting to set IP address on virtual machine guest OS, because the IP address setting depends on version guest OS. You could use two ways to do it:

1) You could use GuestOperationsManager from VMware vSphere API to launch the script of IP address setting on guest OS.

Prerequisites:

  • You should write scripts of IP address setting for each supported OS (Linux, Windows, etc.)
  • VMware Tools must be installed on each supported VM (for use GuestOperationsManager).

Update2. The following simplified example of running a script on the guest OS. This example does not include error handling, getting logs of the script, VM power on, etc.

using System;
using System.IO;
using System.Net;
using Vim25Api;

namespace RunScriptOnGuestOsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var program = new Program();
            program.RunScriptInGuestOs(
                "https://10.1.1.10/sdk",
                "root",
                "vmware",
                "c:\\temp\\test.bat",
                "vm-73",
                "Administrator",
                "P@ssword",
                "c:\\test.bat",
                String.Empty);
        }

        public void RunScriptInGuestOs(string vCenterUrl, string vCenterUserName, string vCenterPassword, string scriptFilePatch, string vmKey, string username, string password, string destinationFilePath, string arguments)
        {
            var service = CreateVimService(vCenterUrl, 600000, true);
            var serviceContent = RetrieveServiceContent(service);
            service.Login(serviceContent.sessionManager, vCenterUserName, vCenterPassword, null);

            byte[] dataFile;
            using (var fileStream = new FileStream(scriptFilePatch, FileMode.Open, FileAccess.Read))
            {
                dataFile = new byte[fileStream.Length];
                fileStream.Read(dataFile, 0, dataFile.Length);
            }

            FileTransferToGuest(service, vmKey, username, password, destinationFilePath, dataFile);
            RunProgramInGuest(service, vmKey, username, password, destinationFilePath, arguments);
        }

        private static VimService CreateVimService(string url, int serviceTimeout, bool trustAllCertificates)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
            return new VimService
            {
                Url = url,
                Timeout = serviceTimeout,
                CookieContainer = new CookieContainer()
            };
        }

        private ServiceContent RetrieveServiceContent(VimService service)
        {
            var serviceInstance = new ManagedObjectReference
            {
                type = "ServiceInstance",
                Value = "ServiceInstance"
            };

            var content = service.RetrieveServiceContent(serviceInstance);
            if (content.sessionManager == null)
            {
                throw new ApplicationException("Session manager is null.");
            }

            return content;
        }

        private void FileTransferToGuest(VimService service, string vmKey, string username, string password, string fileName, byte[] fileData)
        {
            var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false };
            var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey };
            var fileMgr = new ManagedObjectReference { type = "GuestFileManager", Value = "guestOperationsFileManager" };
            var posixFileAttributes = new GuestPosixFileAttributes();
            posixFileAttributes.ownerId = 1;
            posixFileAttributes.groupId = 1;
            posixFileAttributes.permissions = (long)0777; //execution file

            var requestUrl = service.InitiateFileTransferToGuest(fileMgr, vmRef, auth, fileName, posixFileAttributes, fileData.Length, true);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
            request.ContentType = "application/octet-stream";
            request.Method = "PUT";
            request.ContentLength = fileData.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileData, 0, fileData.Length);
            requestStream.Close();

            request.GetResponse();
        }

        private void RunProgramInGuest(VimService service, string vmKey, string username, string password, string programPath, string arguments)
        {
            var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false };
            var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey };
            var progSpec = new GuestProgramSpec { programPath = programPath, arguments = arguments };
            var processMgr = new ManagedObjectReference { type = "GuestProcessManager", Value = "guestOperationsProcessManager" };
            var result = service.StartProgramInGuest(processMgr, vmRef, auth, progSpec);
        }
    }
}

2) You could use DHCP server to manage distributing IP addresses. Using VMware API, you can get MAC address of virtual machine. Next you should set up DHCP server for distributing desired IP addresses on obtained MAC addresses.

Prerequisites:

  • Each VM must be set up to obtain IP address from DHCP server.
  • DHCP server which can be configured to fit your needs.