Last active
March 8, 2016 18:34
-
-
Save dwallraff/15ef7117daa05be1d309 to your computer and use it in GitHub Desktop.
Python script for cloning a VM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import atexit | |
from pyVmomi import vim | |
from pyVim import connect | |
from pyVim.connect import Disconnect | |
INPUTS = {'vcenter_ip': '123.123.123.123', | |
'vcenter_user': 'Administrator', | |
'vcenter_password': 'Password123', | |
'dea_name': 'CustomTest', | |
'new_clone_name': 'TestVM2', | |
'new_clone_domain': 'domain.local', | |
'new_clone_ip': '10.10.10.23', | |
'new_clone_netmask': '255.255.255.0', | |
'new_clone_gateway': '10.10.10.1', | |
'new_clone_dns': '10.0.0.1' | |
} | |
def clone(vm): | |
adaptermap = vim.vm.customization.AdapterMapping() | |
adaptermap.adapter = vim.vm.customization.IPSettings(ip=vim.vm.customization.FixedIp(address=INPUTS['new_clone_ip']), subnetMask=INPUTS['new_clone_netmask'], gateway=INPUTS['new_clone_gateway']) | |
globalip = vim.vm.customization.GlobalIPSettings(dnsServerList=[INPUTS['new_clone_dns']]) | |
ident = vim.vm.customization.LinuxPrep(domain=INPUTS['new_clone_domain'], hostName=vim.vm.customization.FixedName(name=INPUTS['new_clone_name'])) | |
vmconf = vim.vm.ConfigSpec() | |
customspec = vim.vm.customization.Specification(nicSettingMap=[adaptermap], globalIPSettings=globalip, identity=ident) | |
clonespec = vim.vm.CloneSpec(powerOn=True, template=False, customization=customspec, config=vmconf) | |
new_clone = vm.Clone(name=INPUTS['new_clone_name'], folder=vm.parent, spec=clonespec) | |
def get_obj(content, vimtype, name): | |
""" | |
Get the vsphere object associated with a given text 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 main(): | |
si = None | |
try: | |
print "Trying to connect to VCENTER SERVER . . ." | |
si = connect.SmartConnect('https', INPUTS['vcenter_ip'], 443, INPUTS['vcenter_user'], INPUTS['vcenter_password']) | |
except Exception: | |
atexit.register(Disconnect, si) | |
print "Connected to VCENTER SERVER !" | |
content = si.RetrieveContent() | |
vm = get_obj(content, [vim.VirtualMachine], INPUTS['dea_name']) | |
clone(vm) | |
Disconnect(si) | |
# Start program | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment