コード例 #1
0
     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)
     relocateSpec = vim.vm.RelocateSpec(pool=resource_pool)
     cloneSpec = vim.vm.CloneSpec(powerOn=True,
                                  template=False,
                                  location=relocateSpec,
                                  customization=None,
                                  config=vmconf)
     clone = template_vm.Clone(name=new_vm_name,
                               folder=template_vm.parent,
                               spec=cloneSpec)
     Disconnect(si)
     line_counter += 1
 else:
     vcenter = i[0]
     username = i[1]
     password = i[2]
コード例 #2
0
# IP
globalip = vim.vm.customization.GlobalIPSettings()
# for static ip
#globalip = vim.vm.customization.GlobalIPSettings(dnsServerList=['10.0.1.4', '10.0.1.1'])

# Hostname settings
ident = vim.vm.customization.LinuxPrep(
    domain='domain.local', hostName=vim.vm.customization.FixedName(name=newvm))

# 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, 'DEV')
relocateSpec = vim.vm.RelocateSpec(pool=resource_pool)
#cloneSpec = vim.vm.CloneSpec(powerOn=True, template=False, location=relocateSpec, customization=customspec, config=vmconf)
cloneSpec = vim.vm.CloneSpec(powerOn=True,
                             template=False,
                             location=relocateSpec,
                             customization=None,
                             config=vmconf)

# Creating clone task
clone = template_vm.Clone(name=newvm,
                          folder=template_vm.parent,
                          spec=cloneSpec)

# close out connection
Disconnect(si)
コード例 #3
0
ファイル: vmware_scale.py プロジェクト: arghya7das/avinet2
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
コード例 #4
0
ファイル: vmware.py プロジェクト: sijis/err-vmware
    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)
コード例 #5
0
ファイル: create_vm.py プロジェクト: sambavsphere/vcenter
# Network adapter settings
adaptermap = vim.vm.customization.AdapterMapping()
adaptermap.adapter = vim.vm.customization.IPSettings(ip=vim.vm.customization.DhcpIpGenerator(), dnsDomain='domain.local')
# static ip
#adaptermap.adapter = vim.vm.customization.IPSettings(ip=vim.vm.customization.FixedIp(address='10.0.1.10'),
#                                                     subnetMask='255.255.255.0', gateway='10.0.0.1')

# IP
globalip = vim.vm.customization.GlobalIPSettings()
# for static ip
#globalip = vim.vm.customization.GlobalIPSettings(dnsServerList=['10.0.1.4', '10.0.1.1'])

# Hostname settings
ident = vim.vm.customization.LinuxPrep(domain='domain.local', hostName=vim.vm.customization.FixedName(name=newvm))

# 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, 'DEV')
relocateSpec = vim.vm.RelocateSpec(pool=resource_pool)
#cloneSpec = vim.vm.CloneSpec(powerOn=True, template=False, location=relocateSpec, customization=customspec, config=vmconf)
cloneSpec = vim.vm.CloneSpec(powerOn=True, template=False, location=relocateSpec, customization=None, config=vmconf)

# Creating clone task
clone = template_vm.Clone(name=newvm, folder=template_vm.parent, spec=cloneSpec)

# close out connection
Disconnect(si)
コード例 #6
0
ファイル: vmware.py プロジェクト: sijis/err-vmware
    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)