Using Java to create customized virtual machine clones on VMWare infrastructure

2023-10-26

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:

Connect to vSphere
Load a machine we will use as a template
Create a customization specification, which is a configuration of a clone
Create a clone with customization
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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Using Java to create customized virtual machine clones on VMWare infrastructure 的相关文章

  • YOLO V1 学习摘要

    YOLO V1是一种基于深度学习的目标检测算法 其原理和流程如下 1 利用卷积神经网络 CNN 提取输入图像的特征 2 将图像分割成S x S个网格 grid 每个网格负责检测其中一个特定尺寸和位置的目标 3 对于每个网格 预测一个包含5
  • Pycharm无法导入anaconda的包

    Pycharm无法导入anaconda的包 第一 检查是否设置了anaconda的环境变量 第二步 查看anaconda下面的envs是否为空包 如果是空包 便要创建虚拟环境详细过程可参照 2023最新 Python Pycharm Ana
  • 堆—特殊二叉树

    我们了解了树形结构之后 知道了二叉树 但是二叉树的具体用途我们还是不知道 今天就来看看一种特殊的二叉树 堆 它是一种完全二叉树 著名的topK问题就是用堆来求取的 可以求出一组数中的最大或者最小的元素 所使用的堆就是大根堆 小根堆 所谓大根

随机推荐

  • VMware安装Android-x86_64-9.0-r2系统兼容arm设置

    Android x86 64 9 0 r2虚拟机安装兼容arm的android应用程序 1 安装后WLAN提示已连接无网络 实际网络联通 终端模拟器依次输入以下命令后回车重启系统 su settings put global captive
  • Xray-基础详细使用

    一 Xray介绍 Xray 是一款功能强大的安全评估工具 由多名经验丰富的一线安全从业者呕心打造而成 可支持与AWVS BP等众多安全工具联合使用 二 Xray简易架构 说明 了解 Xray 的整体架构可以更好的理解客户端和配置文件的设置
  • for循环详解

    For循环详解 举例如图下 首先for循环相比其他循环可以把条件写在一起如图所示 这变量 条件 变化必不可少其他循环也是 但是for循环有一个点它在初始变量的时候 进入循环之前就已经执行了一次 条件是每次进入循环之前都会执行并且判断 还有当
  • 【git】git rebase -i 合并多次提交

    1 概述 git rebase i 命令用于交互式地重新应用提交历史 其中 i 选项表示以交互方式进行操作 通过使用这个命令 您可以合并 删除 编辑 重排等操作提交历史 从而修改提交的顺序或合并多次提交 下面是使用 git rebase i
  • Linux简介

    1 1操作系统是什么 操作系统概述 要讲明白 Linux 是什么 首先得说说什么是操作系统 计算机系统是指按用户的要求 接收和存储信息 自动进行数据处理并输出结果信息的系统 它由硬件子系统 计算机系统赖以工作的实体 包括显示屏 键盘 鼠标
  • Xcode9 xcodebuild 命令行打包遇到的坑与解决方案

    主要涉及的打包脚本命令 if xcodeversion lt 830 then Xcode 8 3 以下打包时使用该脚本 xcodebuild exportArchive exportFormat ipa archivePath schem
  • 十一、文件的读写

    一 文件的读写模式 1 文件常用的打开模式 r 只能读 r 可读可写 不会创建不存在的文件 如果直接写文件 则从顶部开始写 覆盖之前此位置的内容 如果先读后写 则会在文件最后追加内容 w 可读可写如果文件存在则覆盖整个文件 不存在则创建 w
  • 数学建模 —— 降维算法

    文章目录 前言 数据降维的作用 一 主成分分析 PCA 1 介绍 2 算法流程 3 主成分分析的说明 二 因子分析 FA 1 介绍 2 算法流程 3 因子分析和主成分分析的对比 三 典型相关性分析 CCA 1 介绍 2 算法思路 3 算法流
  • 用位运算实现两个整数的加减乘除运算

    位运算的思想可以应用到很多地方 这里简单的总结一下用位运算来实现整数的四则运算 1 整数加法 int Add int a int b for int i 1 i i lt lt 1 if b i for int j i j j lt lt
  • 网络七层及四层协议通俗详解

    1 OSI开放式网络七层协议模型 总体而言 理解记忆 我点击一个网络请求 假如使用http协议 这就是应用层 用户选择具体的协议 这个请求需要传输数据 但是不同系统因为编码等方式不同 无法识别彼此发送的消息 这个时候表示层就需要把数据整理成
  • 《剑指offer》读后感

    帮研二的学姐准备网易暑期实习的机试时 代码提交在一个OJ网站叫牛客网 出于好奇就多点了一下这个网站 看到 剑指offer 的在线编程专栏 就是把剑指offer中的题目都挂在了网上 可以在线判断是否AC 以前也总是听到学长们推荐该书 索性趁着
  • R语言实现样本量的估算(2)

    本文默认 0 05 sig level 0 2 power 根据研究需要可调整 导入包 library pwr 1 已知标准差和预期差异 1 单样本t检验 某治疗措施预期提高某物质水平8mg L 标准差为10mg L 单样本t检验 pwr
  • QVector用法详细介绍

    QVector类是动态数组的模板类 顺序容器 它将自己的每一个对象存储在连续的内存中 可以使用索引号来快速访问它们 使用前需要包含头文件 include
  • iOS(二)App第一次启动时出现的引导界面

    我们每次打开一个刚刚从AppStore下载下来的软件时 总会出来一个引导界面 有的是宣传产品 有的是介绍App的功能 最后再出来一个按钮正式进入到App 从此以后这个引导界面就再也不会出现了 除非你卸载重装 在查阅相关资料后 做了个简陋的引
  • 逆向爬虫06 bs4,xpath,pyquery实战

    逆向爬虫06 bs4 xpath pyquery实战 原本想要详细的对比一下这三个模块的使用方法 但是在实战的时候发现 只要遵循一个套路 抓取静态网页 即网页信息直接放在html源代码中 就比较容易了 一些使用细节上的问题 每个人遇到的都会
  • Unity Hub、unity、PlasticSCM安装

    目录 一 Unity Hub安装 二 Unity安装 三 PlasticSCM安装 一 Unity Hub安装 第一步 进入官网下载 地址 地址 第二步 安装 跟着提示走就行 二 Unity安装 第一步打开Unity Hub 激活许可证 点
  • 打印机服务器纸张属性不显示,为什么我的打印机能在打印机服务器属性里设置自定义纸张大小,却无法? 爱问知识人...

    问题原因及解决方法 在以往的Windows 98操作系统中 打印机属性里的 纸张大小 中有 自定义 一项 而Windows 2000和Windows XP中自定义的位置是不同于Windows 98的 这里用一个示例来表述 假定用户使用了一款
  • VMware中安装CentOS7

    在VMware中安装CentOS7 01 目录 CentOS7的下载 CentOS7的配置 CentOS7的安装 CentOS7的网络配置 自动获取IP 固定获取IP 02 安装前提 准备工作 提前下载和安装好VMware 下载centos
  • 环境扫描/透射电子显微镜气体样品架的真空压力和微小流量控制解决方案

    摘要 针对环境扫描 透射电子显微镜对样品杆中的真空压力气氛环境和流体流量精密控制控制要求 本文提出了更简单高效和准确的国产化解决方案 解决方案的关键是采用动态平衡法控制真空压力 真空压力控制范围为1E 03Pa 0 7MPa 采用压差法控制
  • 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