Using Java to create customized virtual machine clones on VMWare infrastructure

Hello. Quite a while ago I was given a task to create a java module which would be able to create customized clones from existing virtual machines, managed by vSphere. Main focus was on creating clones, which has unique network settings so all machines can be used for testing at once on same network. To do this, I utilized an open source java library called VIJAVA , which is a Java API to VMWare infrastructure. It offers you pretty big set of operations, which you can do on top of the VMWare infrastructure. In this post I will focus only on cloning task with customized specification.

Generally the procedure to create customized clone is following:

  1. Connect to vSphere
  2. Load a machine we will use as a template
  3. Create a customization specification, which is a configuration of a clone
  4. Create a clone with customization
  5. Power it ON

Code Example

Now let’s show some examples. Before we start, you will need access to vSphere and have access with privileges to create/modify/delete machines on infrastructure. Also i recommend to see http://vijava.sourceforge.net/doc/getstarted/tutorial.htm for a vijava setup. Or if you are using maven, you can add following dependency into your pom file

<dependency>
<groupId>com.vmware</groupId>
<artifactId>vijava</artifactId>
<version>5.1</version>
</dependency>

Now let’s see the actual example code, that connects to vSphere, load the template machines, creates clone specifications and clones the machine. Code should be pretty self explaining with inline comments.

 
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

/**
 * Sample code for creating customized Linux/Windows VM clone from template using VIJAVA
 */
public class VMManager {
    public static void main(String args[]) throws MalformedURLException,
            RemoteException, InterruptedException {
        //Define needed vars
        String vSphereUrl = "https://vsphere.example.com:1234/sdk";
        String vSpherePassword = "password";
        String vSphereUsername  = "username";

        String templateVMName = "template-machine1";
        String cloneName = "vm-1";

        //Connect to vSphere server using VIJAVA
        ServiceInstance si = new ServiceInstance(new URL(vSphereUrl),vSphereUsername,vSpherePassword);

        //Find the template machine in the inventory
        InventoryNavigator inventoryNavigator = new InventoryNavigator(si.getRootFolder());
        VirtualMachine vmTemplate = (VirtualMachine) inventoryNavigator.
                searchManagedEntity("VirtualMachine", templateVMName);

        //Create customization for cloning process(Uncomment the one you need)
        VirtualMachineCloneSpec cloneSpec = createLinuxCustomization();
        //VirtualMachineCloneSpec cloneSpec = createWindowsCustomization();
        //Do the cloning - providing the clone specification
        Task cloneTask = vmTemplate.cloneVM_Task((Folder) vmTemplate.getParent(),cloneName,cloneSpec);
        cloneTask.waitForTask();

        //Here is our new customized virtual machine ready
        VirtualMachine vm = (VirtualMachine) inventoryNavigator.searchManagedEntity("VirtualMachine", cloneName);
        vm.powerOnVM_Task(null).waitForTask();
    }

    public static VirtualMachineCloneSpec createLinuxCustomization(){
        VirtualMachineCloneSpec vmCloneSpec = new VirtualMachineCloneSpec();

        //Set location of clone to be the same as template (Datastore)
        vmCloneSpec.setLocation(new VirtualMachineRelocateSpec());

        //Clone is not powered on, not a template.
        vmCloneSpec.setPowerOn(false);
        vmCloneSpec.setTemplate(false);

        //Create customization specs/linux specific options
        CustomizationSpec customSpec = new CustomizationSpec();
        CustomizationLinuxOptions linuxOptions = new CustomizationLinuxOptions();
        customSpec.setOptions(linuxOptions);

        CustomizationLinuxPrep linuxPrep = new CustomizationLinuxPrep();
        linuxPrep.setDomain("example.domain.com");
        linuxPrep.setHwClockUTC(true);
        linuxPrep.setTimeZone("Europe/London");

        CustomizationFixedName fixedName = new CustomizationFixedName();
        fixedName.setName("cloned-machine-hostname");
        linuxPrep.setHostName(fixedName);
        customSpec.setIdentity(linuxPrep);

        //Network related settings
        CustomizationGlobalIPSettings globalIPSettings = new CustomizationGlobalIPSettings();
        globalIPSettings.setDnsServerList(new String[]{"8.8.8.8", "8.8.4.4"});
        globalIPSettings.setDnsSuffixList(new String[]{"search.com","my.search.com"});
        customSpec.setGlobalIPSettings(globalIPSettings);

        CustomizationFixedIp fixedIp = new CustomizationFixedIp();
        fixedIp.setIpAddress("192.168.10.1");

        CustomizationIPSettings customizationIPSettings = new CustomizationIPSettings();
        customizationIPSettings.setIp(fixedIp);
        customizationIPSettings.setGateway(new String[]{"192.168.1.1"});
        customizationIPSettings.setSubnetMask("255.255.0.0");

        CustomizationAdapterMapping adapterMapping = new CustomizationAdapterMapping();
        adapterMapping.setAdapter(customizationIPSettings);

        CustomizationAdapterMapping[] adapterMappings = new CustomizationAdapterMapping[]{adapterMapping};
        customSpec.setNicSettingMap(adapterMappings);

        //Set all customization to clone specs
        vmCloneSpec.setCustomization(customSpec);
        return vmCloneSpec;
    }

    public static VirtualMachineCloneSpec createWindowsCustomization(){
        //Windows needs valid product key in order to create fully working clone. Otherwise you will get error message
        //when machine is cloned
        String productID="XXXXX-XXXXX-XXXXXX-XXXXX";

        VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();

        //Set location of clone to be the same as template (Datastore)
        cloneSpec.setLocation(new VirtualMachineRelocateSpec());

        //Clone is not powered on, not a template.
        cloneSpec.setPowerOn(false);
        cloneSpec.setTemplate(false);

        //Create customization specs/win specific options
        //Windows are using SYSPREP for these kind of stuff
        CustomizationSpec customSpec = new CustomizationSpec();
        CustomizationWinOptions winOptions = new CustomizationWinOptions();
        
        winOptions.setChangeSID(true);
        //We don't want our preconfigured users to be deleted
        winOptions.setDeleteAccounts(false);

        customSpec.setOptions(winOptions);
        CustomizationSysprep sprep = new CustomizationSysprep();

        CustomizationGuiUnattended guiUnattended = new CustomizationGuiUnattended();
        guiUnattended.setAutoLogon(false);
        guiUnattended.setAutoLogonCount(0);
        guiUnattended.setTimeZone(4);
        sprep.setGuiUnattended(guiUnattended);

        CustomizationIdentification custIdent = new CustomizationIdentification();
        custIdent.setJoinWorkgroup("WORKGROUP");
        sprep.setIdentification(custIdent);

        CustomizationUserData custUserData = new CustomizationUserData();
        CustomizationFixedName fixedName = new CustomizationFixedName();
        fixedName.setName("windows-clone");

        //set from cloned machine
        custUserData.setProductId(productID);     // REQUIRED FOR Windows
        custUserData.setComputerName(fixedName);
        custUserData.setFullName("windows-clone.example.com");
        custUserData.setOrgName("example.com");

        sprep.setUserData(custUserData);
        customSpec.setIdentity(sprep);

        //Network related settings
        CustomizationGlobalIPSettings globalIPSettings = new CustomizationGlobalIPSettings();
        globalIPSettings.setDnsServerList(new String[]{"8.8.8.8","8.8.4.4"});
        globalIPSettings.setDnsSuffixList(new String[]{"example.com"});

        customSpec.setGlobalIPSettings(globalIPSettings);
        CustomizationFixedIp fixedIp = new CustomizationFixedIp();
        fixedIp.setIpAddress("192.168.10.2");

        CustomizationIPSettings customizationIPSettings = new CustomizationIPSettings();
        customizationIPSettings.setIp(fixedIp);
        customizationIPSettings.setGateway(new String[]{"192.168.1.1"});
        customizationIPSettings.setSubnetMask("255.255.0.0");

        //Disabling netBIOS
        customizationIPSettings.setNetBIOS(CustomizationNetBIOSMode.disableNetBIOS);
        customizationIPSettings.setDnsDomain("example.com");

        CustomizationAdapterMapping adapterMapping = new CustomizationAdapterMapping();
        adapterMapping.setAdapter(customizationIPSettings);

        CustomizationAdapterMapping[] adapterMappings = new CustomizationAdapterMapping[]{adapterMapping};
        customSpec.setNicSettingMap(adapterMappings);

        //Set all customization to clone specs
        cloneSpec.setCustomization(customSpec);

        return cloneSpec;
    }
}

Note that all customization properties what you can see in the method above are required otherwise you will get exception related to bad XML parsing. From my experience, process of cloning Linux machine is flawless and i never experienced any kind of problems except when i missed customization properties. On a infrastructure I was working, this process took around 3 minutes to fully booted and prepared machine(CentOS 6.4 Linux OS). Looks like windows is more time consuming with this operation as it took around 5 minutes. Also it’s good to mention, that for a successful cloning of Windows VM, you will need a valid product key for Windows.

Choose the road you want to drive in 2015

12/01/2015 Leave a comment

First of all, with a New Year, we wish everyone to start 2015 on the right path to success and happiness!

Having no options for employment and career building is one of the common themes I’m hearing from Software Engineers in the Ostrava region. There is a few employers with a limited variety of technology projects. We are introducing a new alternative you can consider: innovative engineering projects for agile software houses in the Silicon Valley. Would you consider it?

Read more…

Categories: General Tags: , ,

Entering the Valley

“Silicon Valley is more of a state of mind than a physical location. It has no large monuments, magnificent buildings or ancient heritage. There are no tours of companies or venture capital firms. From Santa Clara to South San Francisco it’s 45 miles of one bedroom community after another. Yet what’s been occurring for the last 50 years within this tight cluster of suburban towns is nothing short of an “entrepreneurial explosion” on par with classic Athens, renaissance Florence or 1920’s Paris.

(Hackers Guide to Silicon Valley by Steve Blank, 2011)

The 5 Rules for Silicon Valley Success That Can Work Anywhere

Source: http://www.enterpreneur.com

Read more…

Categories: General Tags:

VoLTE in the news!!

T-Mobile Czech Republic started testing VoLTE technology, that is IP telephony over LTE. A nice article was published about it in the Czech news (see [1] for an English summary). VoLTE should be generally available for customers from January!

Bringing innovation to life from new office in Ostrava

01/11/2014 1 comment

The demand for profiq’s services from Silicon Valley based hi-tech companies is increasing. This brings new opportunities for technical talent in the Ostrava region. People started seeing us as a competitive alternative to existing IT vendors on the job market of the region, even before moving to Ostrava. Opening a new engineering center in Ostrava increases our dedication to being the alternative.

Most of all, we are now even closer (couldn’t be any closer than that :) ) to university students to enable them to work on technically challenging projects. We welcome fresh graduates with IT background, who are eager to bring innovation in technology to life.

Please visit us to have a chat in person over a coffee or tea. We are interested in hearing from you and ready to share things that you may be interested in hearing about us. You can find us just next to Technical University of Ostrava at premises of Business Incubator on Studentska 6202/17, Ostrava – Poruba:

Studentska

If you do not have a way around, please check our currently open positions at jobs.profiq.cz or contact us at jobs@profiq.cz. We are happy to get in touch!

Why didn’t you tell me!

Here comes a testing focused article after a series of technical blogs! It is based on experience with projects managed through waterfall processes and it continues the series about tackling test complexity.

It is about a luxury that we so often ask for and we often don’t have in testing: to be involved early in the product development process. What does it mean actually to be involved early in the process? Why is it so important? And how does it help tackling test complexity anyway?

Read more…

How to run Liferay with EnterpriseDB’s PPAS as WCM

27/02/2014 1 comment

In case you are evaluating a database for your project(s), you might come across an EnterpriseDB’s Postgres Plus Advanced Server (PPAS). This database is part of an EnterpriseDB (EDB) offering, which is a company providing optimizations, support, performance and security additions and tools (such as Oracle compatibility) for Postgres SQL database.

Lately I had a need to use a database for my Liferay portal other than the one that is bundled within Liferay installation, so I have picked up EnterpriseDB’s PPAS. Read more…

Categories: Integration Tags: , , ,
Follow

Get every new post delivered to your Inbox.

Join 33 other followers