def vmware_reboot_vm(self, msg, args): ''' reboot a virtual machine options: vm (name): name of virtual machine example: !vmware log1 ''' username = self.config['user'] password = self.config['pass'] vcenter = self.config['vcenter'] try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443) except: err_text = 'Error connecting to {0}'.format(vcenter) logging.info(err_text) return err_text # Finding source VM try: vm = vmutils.get_vm_by_name(si, vmname) except: return '{0} not found.'.format(vmname) try: vm.RebootGuest() except: vm.ResetVM_Task() Disconnect(si) return 'Rebooting {0}'.format(vmname)
def getIP(configParser, hostname): vchost = configParser.get('pyvmomi_config', 'vchost') vcuser = configParser.get('pyvmomi_config', 'vcuser') vcpassword = configParser.get('pyvmomi_config', 'vcpassword') vcport = configParser.get('pyvmomi_config', 'vcport') si = SmartConnect(host=vchost, user=vcuser,pwd=vcpassword, port=vcport) vm = vmutils.get_vm_by_name(si, hostname) ipAddress= vm.summary.guest.ipAddress while(not isinstance(ipAddress, str)): ipAddress= vm.summary.guest.ipAddress return ipAddress
def vmware_reboot_vm(self, msg, args): ''' reboot a virtual machine options: vm (name): name of virtual machine example: !vmware log1 ''' username = self.config['user'] password = self.config['pass'] vcenter = self.config['vcenter'] try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443) except: err_text = 'Error connecting to {0}'.format(vcenter) log.info(err_text) self.send(msg.frm, err_text, message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return # Finding source VM vmname = args.pop(0) try: vm = vmutils.get_vm_by_name(si, vmname) except: err_text = '{0} virtual machine not found.'.format(vmname) self.send(msg.frm, err_text, message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return try: vm.RebootGuest() except: vm.ResetVM_Task() Disconnect(si) self.send(msg.frm, 'Reboot task for {0} sent successfully'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True)
def vmware_migrate(self, msg, args): """ Vmotion vm to a specific esx host Example: vmware migrate server1 esxhost2 """ username = self.config['user'] password = self.config['pass'] vcenter = self.config['vcenter'] vmname = args.pop(0) try: hostname = args.pop(0) except IndexError: hostname = None try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443) except: err_text = 'Error connecting to {0}'.format(vcenter) logging.info(err_text) return err_text if hostname: try: host = vmutils.get_host_by_name(si, hostname) hostname = host.name except: return '{0} not found'.format(hostname) else: # hostname was not passed all_hosts = vmutils.get_hosts(si) host = vmutils.get_host_by_name(si, random.choice(all_hosts.values())) hostname = host.name # Finding source VM try: vm = vmutils.get_vm_by_name(si, vmname) except: return '{0} not found.'.format(vmname) # relocate spec, to migrate to another host # this can do other things, like storage and resource pool # migrations relocate_spec = vim.vm.RelocateSpec(host=host) # does the actual migration to host vm.Relocate(relocate_spec) Disconnect(si) return 'Migrating {0} to {1}'.format(vmname, hostname)
def do_scale_in(vmware_settings, instance_names): """ Perform scale in of pool. vmware_settings: vcenter: IP address or hostname of vCenter user: Username for vCenter access password: Password for vCenter access vm_folder_name: Folder containing VMs (or None for same as template) instance_names: Names of VMs to destroy """ with vmutils.vcenter_session(host=vmware_settings['vcenter'], user=vmware_settings['user'], pwd=vmware_settings['password']) as session: vm_folder_name = vmware_settings.get('vm_folder_name', None) if vm_folder_name: vm_folder = vmutils.get_folder(session, vm_folder_name) else: vm_folder = None for instance_name in instance_names: vm = vmutils.get_vm_by_name(session, instance_name, vm_folder) if vm: print('Powering off VM %s...' % instance_name) power_off_task = vm.PowerOffVM_Task() (power_off_task_status, power_off_task_result) = vmutils.wait_for_task(power_off_task) if power_off_task_status: print('Deleting VM %s...' % instance_name) destroy_task = vm.Destroy_Task() (destroy_task_status, destroy_task_result) = vmutils.wait_for_task(destroy_task) if destroy_task_status: print('VM %s deleted!' % instance_name) else: print('VM %s deletion failed!' % instance_name) else: print('Unable to power off VM %s!' % instance_name) else: print('Unable to find VM %s!' % instance_name)
from pyVmomi import vim import vmutils # Create VM by cloning the existing vm ( By using vmname.clone() method ) # We need to pass the New VM name ,folder and spec to the clone() si = vmutils.connect() # Finding source VM target_vm = raw_input("Enter the Vm name , From which Vm you want to clone: ") newvm = raw_input('New vm name: ') template_vm = vmutils.get_vm_by_name(si, target_vm) ''' There are two roads for modifying a vm creation from a template 1. ConfigSpec -> CloneSpec 2. ConfigSpec -> (AdapterMapping -> GlobalIPSettings -> LinuxPrep) -> CustomSpec -> CloneSpec Notes: ConfigSpec and CustomSpecificiation are purely optional and independent ''' # cpu/ram changes #mem = 512 * 1024 # convert to GB mem = 512 # MB vmconf = vim.vm.ConfigSpec(numCPUs=1, memoryMB=mem) print vmconf #vmconf.deviceChange = devices # Network adapter settings adaptermap = vim.vm.customization.AdapterMapping() adaptermap.adapter = vim.vm.customization.IPSettings( ip=vim.vm.customization.DhcpIpGenerator(), dnsDomain='domain.local')
parser.add_argument('--vmtemplate', help='Name of template to use as vmware server ') ARGS = parser.parse_args() try: si = SmartConnect(user=ARGS.username, pwd=ARGS.password, host=ARGS.vcenter, port=ARGS.vcenterport) except IOError, e: pass # Finding source VM newvm = ARGS.vmname template_vm = vmutils.get_vm_by_name(si, 'ARGS.vmtemplate') ''' There are two roads for modifying a vm creation from a template 1. ConfigSpec -> CloneSpec 2. ConfigSpec -> (AdapterMapping -> GlobalIPSettings -> LinuxPrep) -> CustomSpec -> CloneSpec Notes: ConfigSpec and CustomSpecificiation are purely optional and independent ''' # cpu/ram changes #mem = 512 * 1024 # convert to GB mem = 512 # MB vmconf = vim.vm.ConfigSpec(numCPUs=1, memoryMB=mem) #vmconf.deviceChange = devices
from pyVmomi import vim import vmutils # Create VM by cloning the existing vm ( By using vmname.clone() method ) # We need to pass the New VM name ,folder and spec to the clone() si = vmutils.connect() # Finding source VM newvm = raw_input('New vm name: ') template_vm = vmutils.get_vm_by_name(si, 'mytemp') print template_vm print template_vm.name ''' There are two roads for modifying a vm creation from a template 1. ConfigSpec -> CloneSpec 2. ConfigSpec -> (AdapterMapping -> GlobalIPSettings -> LinuxPrep) -> CustomSpec -> CloneSpec Notes: ConfigSpec and CustomSpecificiation are purely optional and independent ''' # cpu/ram changes #mem = 512 * 1024 # convert to GB mem = 512 # MB vmconf = vim.vm.ConfigSpec(numCPUs=1, memoryMB=mem) #vmconf.deviceChange = devices # Network adapter settings adaptermap = vim.vm.customization.AdapterMapping() adaptermap.adapter = vim.vm.customization.IPSettings( ip=vim.vm.customization.DhcpIpGenerator(), dnsDomain='domain.local')
def vmware_clone(self, msg, args): ''' create a cloned vm from a template options: cpu (int): number of cpus mem (int): amount of RAM in MB tmpl (str): template name to use pool (str): allocate clone to resource pool dnsdomain (str): dns suffix of vm vcenter (str): vcenter server puppet (bool): run puppet after provisioning example: !vmware clone --cpu=2 --mem=2048 --pool=DEV --dnsdomain=example.com --puppet app-server1 ''' parser = OptionParser() parser.add_option("--cpu", dest="cpu", type='int', default=1) parser.add_option("--mem", dest="mem", type='int', default=1024) parser.add_option("--tmpl", dest="tmpl", default=self.config['template']) parser.add_option("--pool", dest="pool", default=self.config['resource_pool']) parser.add_option("--dnsdomain", dest="dnsdomain", default=self.config['vm_dnsdomain']) parser.add_option("--vcenter", dest="vcenter", default=self.config['vcenter']) parser.add_option("--puppet", action="store_false", dest="puppet", default=self.config['puppet']) #(options, t_args) = parser.parse_args(args.split(' ')) (options, t_args) = parser.parse_args(args) data = vars(options) username = self.config['user'] password = self.config['pass'] vm_username = self.config['vm_user'] vm_password = self.config['vm_pass'] vmname = t_args.pop(0) try: si = SmartConnect(host=data['vcenter'], user=username, pwd=password, port=443) except IOError: err_text = 'Error connecting to {0}'.format(data['vcenter']) log.info(err_text) self.send(msg.frm, err_text, message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return if vmutils.get_vm_by_name(si, vmname): self.send(msg.frm, 'virtual machine "{0}" already exists.'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return # Finding source VM template_vm = vmutils.get_vm_by_name(si, data['tmpl']) # mem / cpu vmconf = vim.vm.ConfigSpec(numCPUs=data['cpu'], memoryMB=data['mem'], annotation='Created by {0} on {1}'.format( msg.nick, str(datetime.datetime.now()))) # Network adapter settings adaptermap = vim.vm.customization.AdapterMapping() adaptermap.adapter = vim.vm.customization.IPSettings( ip=vim.vm.customization.DhcpIpGenerator(), dnsDomain=data['dnsdomain']) # IP globalip = vim.vm.customization.GlobalIPSettings() # Hostname settings ident = vim.vm.customization.LinuxPrep( domain=data['dnsdomain'], hostName=vim.vm.customization.FixedName(name=vmname)) # Putting all these pieces together in a custom spec customspec = vim.vm.customization.Specification( nicSettingMap=[adaptermap], globalIPSettings=globalip, identity=ident) # Creating relocate spec and clone spec resource_pool = vmutils.get_resource_pool(si, data['pool']) relocateSpec = vim.vm.RelocateSpec(pool=resource_pool) cloneSpec = vim.vm.CloneSpec(powerOn=True, template=False, location=relocateSpec, customization=customspec, config=vmconf) # Creating clone task clone = template_vm.Clone(name=vmname, folder=template_vm.parent, spec=cloneSpec) self.send(msg.frm, '{0}: [1/3] Cloning'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) # Checking clone progress time.sleep(5) while True: progress = clone.info.progress if progress is None: break time.sleep(2) # let's get clone vm info vm_clone = vmutils.get_vm_by_name(si, vmname) # waiting for new vm to bootup vmutils.is_ready(vm_clone) # Credentials used to login to the guest system creds = vmutils.login_in_guest(username=vm_username, password=vm_password) self.send(msg.frm, '{0}: [2/3] Running post setup'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) pid = vmutils.start_process( si=si, vm=vm_clone, auth=creds, program_path='/bin/sed', args='-i "/^HOST/s:$:.{0}:" /etc/sysconfig/network'.format( data['dnsdomain'])) #pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/bin/sed', args='-i "/^127.0.1.1/d" /etc/hosts') pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/sbin/reboot', args='') # get new vm instance time.sleep(15) vmutils.is_ready(vm_clone) if data['puppet']: # ready for puppet... let's go! pid = vmutils.start_process( si=si, vm=vm_clone, auth=creds, program_path='/bin/echo', args= '$(A=$(facter ipaddress); B=$(facter hostname); C=${B}.{0}; echo $A $C $B >> /etc/hosts)' .format(data['dnsdomain'])) pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/usr/bin/puppet', args='agent --test') self.send(msg.frm, '{0}: [3/3] Request completed'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True)
from pyVmomi import vim from pyVim.connect import SmartConnect, Disconnect import vmutils import ssl s = ssl.SSLContext(ssl.PROTOCOL_TLSv1) s.verify_mode = ssl.CERT_NONE c = None try: c = SmartConnect(host="183.82.41.58", user="******", pwd='Nexii@123') print('Valid certificate') except: c = SmartConnect(host="183.82.41.58", user="******", pwd='Nexii@123', sslContext=s) print "successfully connected" # Finding source VM template_vm = vmutils.get_vm_by_name(si, 'centos-6.5-x64') Disconnect(c) print "successfully disconnected"
vcenter = raw_input('vcenter: ') # requests.packages.urllib3.disable_warnings() # # Disabling SSL certificate verification # context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # context.verify_mode = ssl.CERT_NONE try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443) except IOError, e: pass # Finding source VM newvm = raw_input('New vm name: ') template_vm = vmutils.get_vm_by_name(si, 'WIN_PRACT_V') ''' There are two roads for modifying a vm creation from a template 1. ConfigSpec -> CloneSpec 2. ConfigSpec -> (AdapterMapping -> GlobalIPSettings -> LinuxPrep) -> CustomSpec -> CloneSpec Notes: ConfigSpec and CustomSpecificiation are purely optional and independent ''' # cpu/ram changes #mem = 512 * 1024 # convert to GB mem = 512 # MB vmconf = vim.vm.ConfigSpec(numCPUs=1, memoryMB=mem) #vmconf.deviceChange = devices
def vmware_clone(self, msg, args): ''' create a cloned vm from a template options: cpu (int): number of cpus mem (int): amount of RAM in MB tmpl (str): template name to use pool (str): allocate clone to resource pool dnsdomain (str): dns suffix of vm vcenter (str): vcenter server puppet (bool): run puppet after provisioning example: !vmware clone --cpu=2 --mem=2048 --pool=DEV --dnsdomain=example.com --puppet app-server1 ''' parser = OptionParser() parser.add_option("--cpu", dest="cpu", type='int', default=1) parser.add_option("--mem", dest="mem", type='int', default=1024) parser.add_option("--tmpl", dest="tmpl", default=self.config['template']) parser.add_option("--pool", dest="pool", default=self.config['resource_pool']) parser.add_option("--dnsdomain", dest="dnsdomain", default=self.config['vm_dnsdomain']) parser.add_option("--vcenter", dest="vcenter", default=self.config['vcenter']) parser.add_option("--puppet", action="store_false", dest="puppet", default=self.config['puppet']) #(options, t_args) = parser.parse_args(args.split(' ')) (options, t_args) = parser.parse_args(args) data = vars(options) username = self.config['user'] password = self.config['pass'] vm_username = self.config['vm_user'] vm_password = self.config['vm_pass'] vmname = t_args.pop(0) try: si = SmartConnect(host=data['vcenter'], user=username, pwd=password, port=443) except IOError: err_text = 'Error connecting to {0}'.format(data['vcenter']) log.info(err_text) self.send(msg.frm, err_text, message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return if vmutils.get_vm_by_name(si, vmname): self.send(msg.frm, 'virtual machine "{0}" already exists.'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return # Finding source VM template_vm = vmutils.get_vm_by_name(si, data['tmpl']) # mem / cpu vmconf = vim.vm.ConfigSpec(numCPUs=data['cpu'], memoryMB=data['mem'], annotation='Created by {0} on {1}'.format(msg.nick, str(datetime.datetime.now()))) # Network adapter settings adaptermap = vim.vm.customization.AdapterMapping() adaptermap.adapter = vim.vm.customization.IPSettings(ip=vim.vm.customization.DhcpIpGenerator(), dnsDomain=data['dnsdomain']) # IP globalip = vim.vm.customization.GlobalIPSettings() # Hostname settings ident = vim.vm.customization.LinuxPrep(domain=data['dnsdomain'], hostName=vim.vm.customization.FixedName(name=vmname)) # Putting all these pieces together in a custom spec customspec = vim.vm.customization.Specification(nicSettingMap=[adaptermap], globalIPSettings=globalip, identity=ident) # Creating relocate spec and clone spec resource_pool = vmutils.get_resource_pool(si, data['pool']) relocateSpec = vim.vm.RelocateSpec(pool=resource_pool) cloneSpec = vim.vm.CloneSpec(powerOn=True, template=False, location=relocateSpec, customization=customspec, config=vmconf) # Creating clone task clone = template_vm.Clone(name=vmname, folder=template_vm.parent, spec=cloneSpec) self.send(msg.frm, '{0}: [1/3] Cloning'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) # Checking clone progress time.sleep(5) while True: progress = clone.info.progress if progress is None: break time.sleep(2) # let's get clone vm info vm_clone = vmutils.get_vm_by_name(si, vmname) # waiting for new vm to bootup vmutils.is_ready(vm_clone) # Credentials used to login to the guest system creds = vmutils.login_in_guest(username=vm_username, password=vm_password) self.send(msg.frm, '{0}: [2/3] Running post setup'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/bin/sed', args='-i "/^HOST/s:$:.{0}:" /etc/sysconfig/network'.format(data['dnsdomain'])) #pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/bin/sed', args='-i "/^127.0.1.1/d" /etc/hosts') pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/sbin/reboot', args='') # get new vm instance time.sleep(15) vmutils.is_ready(vm_clone) if data['puppet']: # ready for puppet... let's go! pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/bin/echo', args='$(A=$(facter ipaddress); B=$(facter hostname); C=${B}.{0}; echo $A $C $B >> /etc/hosts)'.format(data['dnsdomain'])) pid = vmutils.start_process(si=si, vm=vm_clone, auth=creds, program_path='/usr/bin/puppet', args='agent --test') self.send(msg.frm, '{0}: [3/3] Request completed'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True)
import getpass import vmutils si = None username = raw_input('Username: '******'Password: '******'vcenter: ') try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443) except IOError, e: pass # Finding source VM newvm = raw_input('New vm name: ') template_vm = vmutils.get_vm_by_name(si, 'centos-6.5-x64') ''' There are two roads for modifying a vm creation from a template 1. ConfigSpec -> CloneSpec 2. ConfigSpec -> (AdapterMapping -> GlobalIPSettings -> LinuxPrep) -> CustomSpec -> CloneSpec Notes: ConfigSpec and CustomSpecificiation are purely optional and independent ''' # cpu/ram changes #mem = 512 * 1024 # convert to GB mem = 512 # MB vmconf = vim.vm.ConfigSpec(numCPUs=1, memoryMB=mem) #vmconf.deviceChange = devices
help='Domain of the vsphere client. i.e.: somevcenter.yourhost.com ') parser.add_argument('--vcenterport', help='Port number of the vsphere client. Example: 443 ') parser.add_argument( '--vmname', help= 'Name of virtual machine as it appears in vsphere. i.e.: example-mysqldb-server ' ) ARGS = parser.parse_args() try: si = SmartConnect(user=ARGS.username, pwd=ARGS.password, host=ARGS.vcenter, port=ARGS.vcenterport) except IOError, e: pass # Finding source VM vm = vmutils.get_vm_by_name(si, ARGS.vmname) # does the actual vm reboot try: vm.ResetGuest() except: # forceably shutoff/on # need to do if vmware guest additions isn't running vm.ResetVM_Task() Disconnect(si)
def vmware_migrate(self, msg, args): """ Vmotion vm to a specific esx host Example: vmware migrate server1 esxhost2 """ username = self.config['user'] password = self.config['pass'] vcenter = self.config['vcenter'] vmname = args.pop(0) try: hostname = args.pop(0) except IndexError: hostname = None try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443) except: err_text = 'Error connecting to {0}'.format(vcenter) log.info(err_text) self.send(msg.frm, err_text, message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return if hostname: try: host = vmutils.get_host_by_name(si, hostname) hostname = host.name except: self.send(msg.frm, '{0} not found'.format(hostname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return else: # hostname was not passed all_hosts = vmutils.get_hosts(si) host = vmutils.get_host_by_name(si, random.choice(all_hosts.values())) hostname = host.name # Finding source VM try: vm = vmutils.get_vm_by_name(si, vmname) except: self.send(msg.frm, '{0} not found.'.format(vmname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True) return # relocate spec, to migrate to another host # this can do other things, like storage and resource pool # migrations relocate_spec = vim.vm.RelocateSpec(host=host) # does the actual migration to host vm.Relocate(relocate_spec) Disconnect(si) self.send(msg.frm, 'Migrating {0} to {1}'.format(vmname, hostname), message_type=msg.type, in_reply_to=msg, groupchat_nick_reply=True)
password = i[2] template_name = i[3] new_vm_name = i[4] pool_resource = i[5] cpu_number = i[6] memory_on_mb = i[7] si = None try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443, sslContext=ssl._create_unverified_context()) except IOError, e: pass template_vm = vmutils.get_vm_by_name(si, template_name) vmconf = vim.vm.ConfigSpec(numCPUs=int(cpu_number), memoryMB=int(memory_on_mb)) adaptermap = vim.vm.customization.AdapterMapping() adaptermap.adapter = vim.vm.customization.IPSettings( ip=vim.vm.customization.DhcpIpGenerator(), dnsDomain='domain.local') globalip = vim.vm.customization.GlobalIPSettings() ident = vim.vm.customization.LinuxPrep( domain='domain.local', hostName=vim.vm.customization.FixedName(name=new_vm_name)) customspec = vim.vm.customization.Specification( nicSettingMap=[adaptermap], globalIPSettings=globalip, identity=ident) resource_pool = vmutils.get_resource_pool(si, pool_resource)
def do_scale_out(vmware_settings, pool_name, num_scaleout): """ Perform scale out of pool. vmware_settings: vcenter: IP address or hostname of vCenter user: Username for vCenter access password: Password for vCenter access cluster_name: vCenter cluster name template_folder_name: Folder containing template VM, e.g. 'Datacenter1/Folder1/Subfolder1' or None to search all template_name: Name of template VM vm_folder_name: Folder to place new VM (or None for same as template) customization_spec_name: Name of a customization spec to use resource_pool_name: Name of VMWare Resource Pool or None for default port_group: Name of port group containing pool member IP pool_name: Name of the pool num_scaleout: Number of new instances """ new_instances = [] with vmutils.vcenter_session(host=vmware_settings['vcenter'], user=vmware_settings['user'], pwd=vmware_settings['password']) as session: template_folder_name = vmware_settings.get('template_folder_name', None) template_name = vmware_settings['template_name'] if template_folder_name: template_folder = vmutils.get_folder(session, template_folder_name) template_vm = vmutils.get_vm_by_name(session, template_name, template_folder) else: template_vm = vmutils.get_vm_by_name(session, template_name) vm_folder_name = vmware_settings.get('vm_folder_name', None) if vm_folder_name: vm_folder = vmutils.get_folder(session, vm_folder_name) else: vm_folder = template_vm.parent csm = session.RetrieveContent().customizationSpecManager customization_spec = csm.GetCustomizationSpec( name=vmware_settings['customization_spec_name']) cluster = vmutils.get_cluster(session, vmware_settings['cluster_name']) resource_pool_name = vmware_settings.get('resource_pool_name', None) if resource_pool_name: resource_pool = vmutils.get_resource_pool(session, resource_pool_name) else: resource_pool = cluster.resourcePool relocate_spec = vim.vm.RelocateSpec(pool=resource_pool) clone_spec = vim.vm.CloneSpec(powerOn=True, template=False, location=relocate_spec, customization=customization_spec.spec) port_group = vmware_settings.get('port_group', None) clone_tasks = [] for instance in range(num_scaleout): new_vm_name = '%s-%s' % (pool_name, str(uuid.uuid4())) print('Initiating clone of %s to %s' % (template_name, new_vm_name)) clone_task = template_vm.Clone(name=new_vm_name, folder=vm_folder, spec=clone_spec) print('Task %s created.' % clone_task.info.key) clone_tasks.append(clone_task) for clone_task in clone_tasks: print('Waiting for %s...' % clone_task.info.key) clone_task_status, clone_vm = vmutils.wait_for_task(clone_task, timeout=600) ip_address = None if clone_vm: print('Waiting for VM %s to be ready...' % clone_vm.name) if vmutils.wait_for_vm_status( clone_vm, condition=vmutils.net_info_available, timeout=600): print('Getting IP address from VM %s' % clone_vm.name) for nic in clone_vm.guest.net: if port_group is None or nic.network == port_group: for ip in nic.ipAddress: if '.' in ip: ip_address = ip break if ip_address: break else: print('Timed out waiting for VM %s!' % clone_vm.name) if not ip_address: print('Could not get IP for VM %s!' % clone_vm.name) power_off_task = clone_vm.PowerOffVM_Task() (power_off_task_status, power_off_task_result ) = vmutils.wait_for_task(power_off_task) if power_off_task_status: destroy_task = clone_vm.Destroy_Task() else: print('New VM %s with IP %s' % (clone_vm.name, ip_address)) new_instances.append((clone_vm.name, ip_address)) elif clone_task_status is None: print('Clone task %s timed out!' % clone_task.info.key) return new_instances
from pyVmomi import vim import vmutils # Connect to Vcenter si = vmutils.connect() # Finding source VM , that need to Power Off vm_name = raw_input("Enter the VM name, that you want to Power ON: ") vm = vmutils.get_vm_by_name(si, vm_name) vm.PowerOnVM_Task() print "The given Vm " + vm.name.upper() + ", Powered ON Successfully" vmutils.disconnect(si)
si = None username = raw_input('Username: '******'Password: '******'vcenter: ') vm_name = raw_input('VM: ') esx_host = raw_input('ESX Host: ') try: si = SmartConnect(host=vcenter, user=username, pwd=password, port=443) except IOError, e: pass if esx_host == '': all_hosts = vmutils.get_hosts(si) esx_host = vmutils.get_host_by_name(si, random.choice(all_hosts.values())) else: esx_host = vmutils.get_host_by_name(si, esx_host) # Finding source VM vm = vmutils.get_vm_by_name(si, vm_name) # relocate spec, to migrate to another host # this can do other things, like storage and resource pool # migrations relocate_spec = vim.vm.RelocateSpec(host=esx_host) # does the actual migration to host vm.Relocate(relocate_spec) Disconnect(si)