// Load the template
VirtualMachineTemplate virtualMachineTemplate = enterprise.getTemplateInRepository(datacenter,
Integer.valueOf(template.getImage().getId()));
// Get the zone where the template will be deployed
VirtualDatacenter vdc = cloudService.getVirtualDatacenter(Integer.valueOf(template.getHardware().getLocation()
.getId()));
// Load the virtual appliance or create it if it does not exist
VirtualAppliance vapp = vdc.findVirtualAppliance(VirtualAppliancePredicates.name(tag));
if (vapp == null) {
vapp = VirtualAppliance.builder(context, vdc).name(tag).build();
vapp.save();
}
Integer overrideCores = options.getOverrideCores();
Integer overrideRam = options.getOverrideRam();
VirtualMachine vm = VirtualMachine.builder(context, vapp, virtualMachineTemplate) //
.nameLabel(name) //
.cpu(overrideCores != null ? overrideCores : totalCores(template.getHardware())) //
.ram(overrideRam != null ? overrideRam : template.getHardware().getRam()) //
.password(options.getVncPassword()) // Can be null
.build();
vm.save();
// Once the virtual machine is created, override the default network
// settings if needed
// If no public ip is available in the virtual datacenter, the virtual
// machine will be assigned by default an ip address in the default
// private VLAN for the virtual datacenter
PublicIp publicIp = vdc.findPurchasedPublicIp(IpPredicates.<PublicIp> notUsed());
if (publicIp != null) {
List<PublicIp> ips = Lists.newArrayList();
ips.add(publicIp);
vm.setNics(ips);
}