Runs the provisioners defined in the Vagrantfile.
        vm_name: optional VM name string.
        provision_with: optional list of provisioners to enable.
          e.g. ['shell', 'chef_solo']
490287
def provision(self, vm_name=None, provision_with=None):
        '''
        
        '''
        prov_with_arg = None if provision_with is None else '--provision-with'
        providers_arg = None if provision_with is None else ','.join(provision_with)
        self._call_vagrant_command(['provision', vm_name, prov_with_arg,
                                   providers_arg])
797390
def create(self, vm_, local_master=True):
        '''
        
        '''
        output = {}

        minion_dict = salt.config.get_cloud_config_value(
            'minion', vm_, self.opts, default={}
        )

        alias, driver = vm_['provider'].split(':')
        fun = '{0}.create'.format(driver)
        if fun not in self.clouds:
            log.error(
                'Creating \'%s\' using \'%s\' as the provider '
                'cannot complete since \'%s\' is not available',
                vm_['name'], vm_['provider'], driver
            )
            return

        deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts)
        make_master = salt.config.get_cloud_config_value(
            'make_master',
            vm_,
            self.opts
        )

        if deploy:
            if not make_master and 'master' not in minion_dict:
                log.warning(
                    'There\'s no master defined on the \'%s\' VM settings.',
                    vm_['name']
                )

            if 'pub_key' not in vm_ and 'priv_key' not in vm_:
                log.debug('Generating minion keys for \'%s\'', vm_['name'])
                priv, pub = salt.utils.cloud.gen_keys(
                    salt.config.get_cloud_config_value(
                        'keysize',
                        vm_,
                        self.opts
                    )
                )
                vm_['pub_key'] = pub
                vm_['priv_key'] = priv
        else:
            # Note(pabelanger): We still reference pub_key and priv_key when
            # deploy is disabled.
            vm_['pub_key'] = None
            vm_['priv_key'] = None

        key_id = minion_dict.get('id', vm_['name'])

        domain = vm_.get('domain')
        if vm_.get('use_fqdn') and domain:
            minion_dict['append_domain'] = domain

        if 'append_domain' in minion_dict:
            key_id = '.'.join([key_id, minion_dict['append_domain']])

        if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_:
            log.debug('Generating the master keys for \'%s\'', vm_['name'])
            master_priv, master_pub = salt.utils.cloud.gen_keys(
                salt.config.get_cloud_config_value(
                    'keysize',
                    vm_,
                    self.opts
                )
            )
            vm_['master_pub'] = master_pub
            vm_['master_pem'] = master_priv

        if local_master is True and deploy is True:
            # Accept the key on the local master
            salt.utils.cloud.accept_key(
                self.opts['pki_dir'], vm_['pub_key'], key_id
            )

        vm_['os'] = salt.config.get_cloud_config_value(
            'script',
            vm_,
            self.opts
        )

        try:
            vm_['inline_script'] = salt.config.get_cloud_config_value(
                'inline_script',
                vm_,
                self.opts
            )
        except KeyError:
            pass

        try:
            alias, driver = vm_['provider'].split(':')
            func = '{0}.create'.format(driver)
            with salt.utils.context.func_globals_inject(
                self.clouds[fun],
                __active_provider_name__=':'.join([alias, driver])
            ):
                output = self.clouds[func](vm_)
            if output is not False and 'sync_after_install' in self.opts:
                if self.opts['sync_after_install'] not in (
                        'all', 'modules', 'states', 'grains'):
                    log.error('Bad option for sync_after_install')
                    return output

                # A small pause helps the sync work more reliably
                time.sleep(3)

                start = int(time.time())
                while int(time.time()) < start + 60:
                    # We'll try every <timeout> seconds, up to a minute
                    mopts_ = salt.config.DEFAULT_MASTER_OPTS
                    conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1])
                    mopts_.update(
                        salt.config.master_config(
                            os.path.join(conf_path,
                                         'master')
                        )
                    )

                    client = salt.client.get_local_client(mopts=mopts_)

                    ret = client.cmd(
                        vm_['name'],
                        'saltutil.sync_{0}'.format(self.opts['sync_after_install']),
                        timeout=self.opts['timeout']
                    )
                    if ret:
                        log.info(
                            six.u('Synchronized the following dynamic modules: '
                                  '  {0}').format(ret)
                        )
                        break
        except KeyError as exc:
            log.exception(
                'Failed to create VM %s. Configuration value %s needs '
                'to be set', vm_['name'], exc
            )
        # If it's a map then we need to respect the 'requires'
        # so we do it later
        try:
            opt_map = self.opts['map']
        except KeyError:
            opt_map = False
        if self.opts['parallel'] and self.opts['start_action'] and not opt_map:
            log.info('Running %s on %s', self.opts['start_action'], vm_['name'])
            client = salt.client.get_local_client(mopts=self.opts)
            action_out = client.cmd(
                vm_['name'],
                self.opts['start_action'],
                timeout=self.opts['timeout'] * 60
            )
            output['ret'] = action_out
        return output
667703
def options(self, options):
        

        log.info('QEMU VM "{name}" [{id}] has set the QEMU options to {options}'.format(name=self._name,
                                                                                        id=self._id,
                                                                                        options=options))

        if not sys.platform.startswith("linux"):
            if "-no-kvm" in options:
                options = options.replace("-no-kvm", "")
            if "-enable-kvm" in options:
                options = options.replace("-enable-kvm", "")
        elif "-icount" in options and ("-no-kvm" not in options):
            # automatically add the -no-kvm option if -icount is detected
            # to help with the migration of ASA VMs created before version 1.4
            options = "-no-kvm " + options
        self._options = options.strip()
1135955
def execute
      options = {
        :_method => :run,
        :_rebootable => true,
        :auto_reboot => false
      }
      opts = OptionParser.new do |opts|
        opts.banner = "Usage: vagrant vbguest [vm-name] "\
                      "[--do start|rebuild|install] "\
                      "[--status] "\
                      "[-f|--force] "\
                      "[-b|--auto-reboot] "\
                      "[-R|--no-remote] "\
                      "[--iso VBoxGuestAdditions.iso] "\
                      "[--no-cleanup]"

        opts.separator ""

        opts.on("--do COMMAND", [:start, :rebuild, :install], "Manually `start`, `rebuild` or `install` GuestAdditions.") do |command|
          options[:_method] = command
          options[:force] = true
        end

        opts.on("--status", "Print current GuestAdditions status and exit.") do
          options[:_method] = :status
          options[:_rebootable] = false
        end

        opts.on("-f", "--force", "Whether to force the installation. (Implied by --do start|rebuild|install)") do
          options[:force] = true
        end

        opts.on("--auto-reboot", "-b", "Allow rebooting the VM after installation. (when GuestAdditions won't start)") do
          options[:auto_reboot] = true
        end

        opts.on("--no-remote", "-R", "Do not attempt do download the iso file from a webserver") do
          options[:no_remote] = true
        end

        opts.on("--iso file_or_uri", "Full path or URI to the VBoxGuestAdditions.iso") do |file_or_uri|
          options[:iso_path] = file_or_uri
        end

        opts.on("--no-cleanup", "Do not run cleanup tasks after installation. (for debugging)") do
          options[:no_cleanup] = true
        end

        build_start_options(opts, options)
      end


      argv = parse_options(opts)
      return if !argv

      if argv.empty?
        with_target_vms(nil) { |vm| execute_on_vm(vm, options) }
      else
        argv.each do |vm_name|
          with_target_vms(vm_name) { |vm| execute_on_vm(vm, options) }
        end
      end
    end
155860
def create(vm_):
    '''
    
    '''
    if 'driver' not in vm_:
        vm_['driver'] = vm_['provider']

    private_networking = config.get_cloud_config_value(
        'enable_private_network', vm_, __opts__, search_global=False, default=False,
    )

    startup_script = config.get_cloud_config_value(
        'startup_script_id', vm_, __opts__, search_global=False, default=None,
    )

    if startup_script and str(startup_script) not in avail_scripts():
        log.error('Your Vultr account does not have a startup script with ID %s', str(startup_script))
        return False

    if private_networking is not None:
        if not isinstance(private_networking, bool):
            raise SaltCloudConfigError("'private_networking' should be a boolean value.")
    if private_networking is True:
        enable_private_network = 'yes'
    else:
        enable_private_network = 'no'

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    osid = _lookup_vultrid(vm_['image'], 'avail_images', 'OSID')
    if not osid:
        log.error('Vultr does not have an image with id or name %s', vm_['image'])
        return False

    vpsplanid = _lookup_vultrid(vm_['size'], 'avail_sizes', 'VPSPLANID')
    if not vpsplanid:
        log.error('Vultr does not have a size with id or name %s', vm_['size'])
        return False

    dcid = _lookup_vultrid(vm_['location'], 'avail_locations', 'DCID')
    if not dcid:
        log.error('Vultr does not have a location with id or name %s', vm_['location'])
        return False

    kwargs = {
        'label': vm_['name'],
        'OSID': osid,
        'VPSPLANID': vpsplanid,
        'DCID': dcid,
        'hostname': vm_['name'],
        'enable_private_network': enable_private_network,
    }
    if startup_script:
        kwargs['SCRIPTID'] = startup_script

    log.info('Creating Cloud VM %s', vm_['name'])

    __utils__['cloud.fire_event'](
        'event',
        'requesting instance',
        'salt/cloud/{0}/requesting'.format(vm_['name']),
        args={
            'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport'],
    )

    try:
        data = _query('server/create', method='POST', data=_urlencode(kwargs))
        if int(data.get('status', '200')) >= 300:
            log.error(
                'Error creating %s on Vultr\n\n'
                'Vultr API returned %s\n', vm_['name'], data
            )
            log.error('Status 412 may mean that you are requesting an\n'
                      'invalid location, image, or size.')

            __utils__['cloud.fire_event'](
                'event',
                'instance request failed',
                'salt/cloud/{0}/requesting/failed'.format(vm_['name']),
                args={'kwargs': kwargs},
                sock_dir=__opts__['sock_dir'],
                transport=__opts__['transport'],
            )
            return False
    except Exception as exc:
        log.error(
            'Error creating %s on Vultr\n\n'
            'The following exception was thrown when trying to '
            'run the initial deployment:\n%s',
            vm_['name'], exc,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        __utils__['cloud.fire_event'](
            'event',
            'instance request failed',
            'salt/cloud/{0}/requesting/failed'.format(vm_['name']),
            args={'kwargs': kwargs},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport'],
        )
        return False

    def wait_for_hostname():
        '''
        Wait for the IP address to become available
        '''
        data = show_instance(vm_['name'], call='action')
        main_ip = six.text_type(data.get('main_ip', '0'))
        if main_ip.startswith('0'):
            time.sleep(3)
            return False
        return data['main_ip']

    def wait_for_default_password():
        '''
        Wait for the IP address to become available
        '''
        data = show_instance(vm_['name'], call='action')
        # print("Waiting for default password")
        # pprint.pprint(data)
        if six.text_type(data.get('default_password', '')) == '':
            time.sleep(1)
            return False
        return data['default_password']

    def wait_for_status():
        '''
        Wait for the IP address to become available
        '''
        data = show_instance(vm_['name'], call='action')
        # print("Waiting for status normal")
        # pprint.pprint(data)
        if six.text_type(data.get('status', '')) != 'active':
            time.sleep(1)
            return False
        return data['default_password']

    def wait_for_server_state():
        '''
        Wait for the IP address to become available
        '''
        data = show_instance(vm_['name'], call='action')
        # print("Waiting for server state ok")
        # pprint.pprint(data)
        if six.text_type(data.get('server_state', '')) != 'ok':
            time.sleep(1)
            return False
        return data['default_password']

    vm_['ssh_host'] = __utils__['cloud.wait_for_fun'](
        wait_for_hostname,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )
    vm_['password'] = __utils__['cloud.wait_for_fun'](
        wait_for_default_password,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )
    __utils__['cloud.wait_for_fun'](
        wait_for_status,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )
    __utils__['cloud.wait_for_fun'](
        wait_for_server_state,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )

    __opts__['hard_timeout'] = config.get_cloud_config_value(
        'hard_timeout',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default=None,
    )

    # Bootstrap
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    ret.update(show_instance(vm_['name'], call='action'))

    log.info('Created Cloud VM \'%s\'', vm_['name'])
    log.debug(
        '\'%s\' VM creation details:\n%s',
        vm_['name'], pprint.pformat(data)
    )

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    return ret
408106
def running?
      raise Fission::Error,"VM #{@name} does not exist" unless self.exists?

      command = "#{vmrun_cmd} list"
      output = `#{command}`

      response = Fission::Response.new :code => $?.exitstatus

      if response.successful?
        vms = output.split("\n").select do |vm|
          vm.include?('.vmx') && File.exists?(vm) && File.extname(vm) == '.vmx'
        end
        return vms.include?(self.vmx_path)
      else
        raise Fission::Error,"Error listing the state of vm #{@name}:\n#{output}"
      end
    end
593389
def prepare_vagrant(node)
      project_name = Bebox::Project.name_from_file(node.project_root)
      vagrant_box_base = Bebox::Project.vagrant_box_base_from_file(node.project_root)
      configure_local_hosts(project_name, node)
      add_vagrant_node(project_name, vagrant_box_base, node)
    end
222877
def generate_builtin_set(system_plugins=[])
      builtin_set = BuiltinSet.new
      @logger.debug("Generating new builtin set instance.")
      vagrant_internal_specs.each do |spec|
        if !system_plugins.include?(spec.name)
          builtin_set.add_builtin_spec(spec)
        end
      end
      builtin_set
    end
527577
def _call_vagrant_command(self, args):
        '''
        

        '''
        # Make subprocess command
        command = self._make_vagrant_command(args)
        with self.out_cm() as out_fh, self.err_cm() as err_fh:
            subprocess.check_call(command, cwd=self.root, stdout=out_fh,
                                  stderr=err_fh, env=self.env)
647247
def _run_vagrant_command(self, args):
        '''
        
        '''
        # Make subprocess command
        command = self._make_vagrant_command(args)
        with self.err_cm() as err_fh:
            return compat.decode(subprocess.check_output(command, cwd=self.root,
                                               env=self.env, stderr=err_fh))
1340938
def create(vm_):
    '''
    
    '''
    try:
        # Check for required profile parameters before sending any API calls.
        if (vm_['profile'] and
            config.is_profile_configured(__opts__,
                                         __active_provider_name__ or 'vmware',
                                         vm_['profile'],
                                         vm_=vm_) is False):
            return False
    except AttributeError:
        pass

    __utils__['cloud.fire_event'](
        'event',
        'starting create',
        'salt/cloud/{0}/creating'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    vm_name = config.get_cloud_config_value(
        'name', vm_, __opts__, default=None
    )
    folder = config.get_cloud_config_value(
        'folder', vm_, __opts__, default=None
    )
    datacenter = config.get_cloud_config_value(
        'datacenter', vm_, __opts__, default=None
    )
    resourcepool = config.get_cloud_config_value(
        'resourcepool', vm_, __opts__, default=None
    )
    cluster = config.get_cloud_config_value(
        'cluster', vm_, __opts__, default=None
    )
    datastore = config.get_cloud_config_value(
        'datastore', vm_, __opts__, default=None
    )
    host = config.get_cloud_config_value(
        'host', vm_, __opts__, default=None
    )
    template = config.get_cloud_config_value(
        'template', vm_, __opts__, default=False
    )
    num_cpus = config.get_cloud_config_value(
        'num_cpus', vm_, __opts__, default=None
    )
    cores_per_socket = config.get_cloud_config_value(
        'cores_per_socket', vm_, __opts__, default=None
    )
    memory = config.get_cloud_config_value(
        'memory', vm_, __opts__, default=None
    )
    devices = config.get_cloud_config_value(
        'devices', vm_, __opts__, default=None
    )
    extra_config = config.get_cloud_config_value(
        'extra_config', vm_, __opts__, default=None
    )
    annotation = config.get_cloud_config_value(
        'annotation', vm_, __opts__, default=None
    )
    power = config.get_cloud_config_value(
        'power_on', vm_, __opts__, default=True
    )
    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )
    deploy = config.get_cloud_config_value(
        'deploy', vm_, __opts__, search_global=True, default=True
    )
    wait_for_ip_timeout = config.get_cloud_config_value(
        'wait_for_ip_timeout', vm_, __opts__, default=20 * 60
    )
    domain = config.get_cloud_config_value(
        'domain', vm_, __opts__, search_global=False, default='local'
    )
    hardware_version = config.get_cloud_config_value(
        'hardware_version', vm_, __opts__, search_global=False, default=None
    )
    guest_id = config.get_cloud_config_value(
        'image', vm_, __opts__, search_global=False, default=None
    )
    customization = config.get_cloud_config_value(
        'customization', vm_, __opts__, search_global=False, default=True
    )
    customization_spec = config.get_cloud_config_value(
        'customization_spec', vm_, __opts__, search_global=False, default=None
    )
    win_password = config.get_cloud_config_value(
        'win_password', vm_, __opts__, search_global=False, default=None
    )
    win_organization_name = config.get_cloud_config_value(
        'win_organization_name', vm_, __opts__, search_global=False, default='Organization'
    )
    plain_text = config.get_cloud_config_value(
        'plain_text', vm_, __opts__, search_global=False, default=False
    )
    win_user_fullname = config.get_cloud_config_value(
        'win_user_fullname', vm_, __opts__, search_global=False, default='Windows User'
    )
    win_run_once = config.get_cloud_config_value(
        'win_run_once', vm_, __opts__, search_global=False, default=None
    )
    win_ad_domain = config.get_cloud_config_value(
        'win_ad_domain', vm_, __opts__, search_global=False, default=''
    )
    win_ad_user = config.get_cloud_config_value(
        'win_ad_user', vm_, __opts__, search_global=False, default=''
    )
    win_ad_password = config.get_cloud_config_value(
        'win_ad_password', vm_, __opts__, search_global=False, default=''
    )
    win_autologon = config.get_cloud_config_value(
        'win_autologon', vm_, __opts__, search_global=False, default=True
    )
    timezone = config.get_cloud_config_value(
        'timezone', vm_, __opts__, search_global=False, default=''
    )
    hw_clock_utc = config.get_cloud_config_value(
        'hw_clock_utc', vm_, __opts__, search_global=False, default=''
    )
    clonefrom_datacenter = config.get_cloud_config_value(
        'clonefrom_datacenter', vm_, __opts__, search_global=False, default=datacenter
    )

    # Get service instance object
    si = _get_si()

    container_ref = None
    clonefrom_datacenter_ref = None

    # If datacenter is specified, set the container reference to start search from it instead
    if datacenter:
        datacenter_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.Datacenter, datacenter)
        container_ref = datacenter_ref if datacenter_ref else None

    if 'clonefrom' in vm_:
        # If datacenter is specified, set the container reference to start search from it instead
        if datacenter:
            datacenter_ref = salt.utils.vmware.get_mor_by_property(
                                 si,
                                 vim.Datacenter,
                                 datacenter
                             )
            container_ref = datacenter_ref if datacenter_ref else None
            clonefrom_container_ref = datacenter_ref if datacenter_ref else None
        # allow specifying a different datacenter that the template lives in
        if clonefrom_datacenter:
            clonefrom_datacenter_ref = salt.utils.vmware.get_mor_by_property(
                                           si,
                                           vim.Datacenter,
                                           clonefrom_datacenter
                                       )
            clonefrom_container_ref = clonefrom_datacenter_ref if clonefrom_datacenter_ref else None

        # Clone VM/template from specified VM/template
        object_ref = salt.utils.vmware.get_mor_by_property(
                         si,
                         vim.VirtualMachine,
                         vm_['clonefrom'],
                         container_ref=clonefrom_container_ref
                     )
        if object_ref:
            clone_type = "template" if object_ref.config.template else "vm"
        else:
            raise SaltCloudSystemExit(
                'The VM/template that you have specified under clonefrom does not exist.'
            )
    else:
        clone_type = None
        object_ref = None

    # Either a cluster, or a resource pool must be specified when cloning from template or creating.
    if resourcepool:
        resourcepool_ref = salt.utils.vmware.get_mor_by_property(
                               si,
                               vim.ResourcePool,
                               resourcepool,
                               container_ref=container_ref
                           )
        if not resourcepool_ref:
            log.error("Specified resource pool: '%s' does not exist", resourcepool)
            if not clone_type or clone_type == "template":
                raise SaltCloudSystemExit('You must specify a resource pool that exists.')
    elif cluster:
        cluster_ref = salt.utils.vmware.get_mor_by_property(
                          si,
                          vim.ClusterComputeResource,
                          cluster,
                          container_ref=container_ref
                      )
        if not cluster_ref:
            log.error("Specified cluster: '%s' does not exist", cluster)
            if not clone_type or clone_type == "template":
                raise SaltCloudSystemExit('You must specify a cluster that exists.')
        else:
            resourcepool_ref = cluster_ref.resourcePool
    elif clone_type == "template":
        raise SaltCloudSystemExit(
            'You must either specify a cluster or a resource pool when cloning from a template.'
        )
    elif not clone_type:
        raise SaltCloudSystemExit(
            'You must either specify a cluster or a resource pool when creating.'
        )
    else:
        log.debug("Using resource pool used by the %s %s", clone_type, vm_['clonefrom'])

    # Either a datacenter or a folder can be optionally specified when cloning, required when creating.
    # If not specified when cloning, the existing VM/template\'s parent folder is used.
    if folder:
        folder_parts = folder.split('/')
        search_reference = container_ref
        for folder_part in folder_parts:
            if folder_part:
                folder_ref = salt.utils.vmware.get_mor_by_property(
                                 si,
                                 vim.Folder,
                                 folder_part,
                                 container_ref=search_reference
                             )
                search_reference = folder_ref
        if not folder_ref:
            log.error("Specified folder: '%s' does not exist", folder)
            log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
            folder_ref = object_ref.parent
    elif datacenter:
        if not datacenter_ref:
            log.error("Specified datacenter: '%s' does not exist", datacenter)
            log.debug("Using datacenter folder in which %s %s is present", clone_type, vm_['clonefrom'])
            folder_ref = object_ref.parent
        else:
            folder_ref = datacenter_ref.vmFolder
    elif not clone_type:
        raise SaltCloudSystemExit(
            'You must either specify a folder or a datacenter when creating not cloning.'
        )
    else:
        log.debug("Using folder in which %s %s is present", clone_type, vm_['clonefrom'])
        folder_ref = object_ref.parent

    if 'clonefrom' in vm_:
        # Create the relocation specs
        reloc_spec = vim.vm.RelocateSpec()

        if (resourcepool and resourcepool_ref) or (cluster and cluster_ref):
            reloc_spec.pool = resourcepool_ref

        # Either a datastore/datastore cluster can be optionally specified.
        # If not specified, the current datastore is used.
        if datastore:
            datastore_ref = salt.utils.vmware.get_mor_by_property(
                                si,
                                vim.Datastore,
                                datastore,
                                container_ref=container_ref
                            )
            if datastore_ref:
                # specific datastore has been specified
                reloc_spec.datastore = datastore_ref
            else:
                datastore_cluster_ref = salt.utils.vmware.get_mor_by_property(si, vim.StoragePod, datastore, container_ref=container_ref)
                if not datastore_cluster_ref:
                    log.error("Specified datastore/datastore cluster: '%s' does not exist", datastore)
                    log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])
        else:
            log.debug("No datastore/datastore cluster specified")
            log.debug("Using datastore used by the %s %s", clone_type, vm_['clonefrom'])

        if host:
            host_ref = salt.utils.vmware.get_mor_by_property(
                           si,
                           vim.HostSystem,
                           host,
                           container_ref=container_ref
                       )
            if host_ref:
                reloc_spec.host = host_ref
            else:
                log.error("Specified host: '%s' does not exist", host)
    else:
        if not datastore:
            raise SaltCloudSystemExit(
                'You must specify a datastore when creating not cloning.'
            )
        else:
            datastore_ref = salt.utils.vmware.get_mor_by_property(
                                si,
                                vim.Datastore,
                                datastore
                            )
            if not datastore_ref:
                raise SaltCloudSystemExit("Specified datastore: '{0}' does not exist".format(datastore))

        if host:
            host_ref = salt.utils.vmware.get_mor_by_property(
                           _get_si(),
                           vim.HostSystem,
                           host,
                           container_ref=container_ref
                       )
            if not host_ref:
                log.error("Specified host: '%s' does not exist", host)

    # Create the config specs
    config_spec = vim.vm.ConfigSpec()

    # If the hardware version is specified and if it is different from the current
    # hardware version, then schedule a hardware version upgrade
    if hardware_version and object_ref is not None:
        hardware_version = 'vmx-{0:02}'.format(hardware_version)
        if hardware_version != object_ref.config.version:
            log.debug(
                "Scheduling hardware version upgrade from %s to %s",
                object_ref.config.version, hardware_version
            )
            scheduled_hardware_upgrade = vim.vm.ScheduledHardwareUpgradeInfo()
            scheduled_hardware_upgrade.upgradePolicy = 'always'
            scheduled_hardware_upgrade.versionKey = hardware_version
            config_spec.scheduledHardwareUpgradeInfo = scheduled_hardware_upgrade
        else:
            log.debug("Virtual hardware version already set to %s", hardware_version)

    if num_cpus:
        log.debug("Setting cpu to: %s", num_cpus)
        config_spec.numCPUs = int(num_cpus)

    if cores_per_socket:
        log.debug("Setting cores per socket to: %s", cores_per_socket)
        config_spec.numCoresPerSocket = int(cores_per_socket)

    if memory:
        try:
            memory_num, memory_unit = re.findall(r"[^\W\d_]+|\d+.\d+|\d+",
                                                 memory)
            if memory_unit.lower() == "mb":
                memory_mb = int(memory_num)
            elif memory_unit.lower() == "gb":
                memory_mb = int(float(memory_num)*1024.0)
            else:
                err_msg = "Invalid memory type specified: '{0}'".format(memory_unit)
                log.error(err_msg)
                return {'Error': err_msg}
        except (TypeError, ValueError):
            memory_mb = int(memory)
        log.debug("Setting memory to: %s MB", memory_mb)
        config_spec.memoryMB = memory_mb

    if devices:
        specs = _manage_devices(devices, vm=object_ref, container_ref=container_ref, new_vm_name=vm_name)
        config_spec.deviceChange = specs['device_specs']

    if extra_config:
        for key, value in six.iteritems(extra_config):
            option = vim.option.OptionValue(key=key, value=value)
            config_spec.extraConfig.append(option)

    if annotation:
        config_spec.annotation = six.text_type(annotation)

    if 'clonefrom' in vm_:
        clone_spec = handle_snapshot(
            config_spec,
            object_ref,
            reloc_spec,
            template,
            vm_
        )
        if not clone_spec:
            clone_spec = build_clonespec(config_spec,
                                         object_ref,
                                         reloc_spec,
                                         template)

        if customization and customization_spec:
            customization_spec = salt.utils.vmware.get_customizationspec_ref(si=si, customization_spec_name=customization_spec)
            clone_spec.customization = customization_spec.spec
        elif customization and (devices and 'network' in list(devices.keys())):
            global_ip = vim.vm.customization.GlobalIPSettings()
            if 'dns_servers' in list(vm_.keys()):
                global_ip.dnsServerList = vm_['dns_servers']

            non_hostname_chars = re.compile(r'[^\w-]')
            if re.search(non_hostname_chars, vm_name):
                host_name = re.split(non_hostname_chars,
                                     vm_name,
                                     maxsplit=1)[0]
                domain_name = re.split(non_hostname_chars,
                                       vm_name,
                                       maxsplit=1)[-1]
            else:
                host_name = vm_name
                domain_name = domain

            if 'Windows' not in object_ref.config.guestFullName:
                identity = vim.vm.customization.LinuxPrep()
                identity.hostName = vim.vm.customization.FixedName(name=host_name)
                identity.domain = domain_name
                if timezone:
                    identity.timeZone = timezone
                if isinstance(hw_clock_utc, bool):
                    identity.hwClockUTC = hw_clock_utc
            else:
                identity = vim.vm.customization.Sysprep()
                identity.guiUnattended = vim.vm.customization.GuiUnattended()
                identity.guiUnattended.autoLogon = win_autologon
                if win_autologon:
                    identity.guiUnattended.autoLogonCount = 1
                else:
                    identity.guiUnattended.autoLogonCount = 0
                identity.guiUnattended.password = vim.vm.customization.Password()
                identity.guiUnattended.password.value = win_password
                identity.guiUnattended.password.plainText = plain_text
                if timezone:
                    identity.guiUnattended.timeZone = timezone
                if win_run_once:
                    identity.guiRunOnce = vim.vm.customization.GuiRunOnce()
                    identity.guiRunOnce.commandList = win_run_once
                identity.userData = vim.vm.customization.UserData()
                identity.userData.fullName = win_user_fullname
                identity.userData.orgName = win_organization_name
                identity.userData.computerName = vim.vm.customization.FixedName()
                identity.userData.computerName.name = host_name
                identity.identification = vim.vm.customization.Identification()
                if win_ad_domain and win_ad_user and win_ad_password:
                    identity.identification.joinDomain = win_ad_domain
                    identity.identification.domainAdmin = win_ad_user
                    identity.identification.domainAdminPassword = vim.vm.customization.Password()
                    identity.identification.domainAdminPassword.value = win_ad_password
                    identity.identification.domainAdminPassword.plainText = plain_text
            custom_spec = vim.vm.customization.Specification(
                globalIPSettings=global_ip,
                identity=identity,
                nicSettingMap=specs['nics_map']
            )
            clone_spec.customization = custom_spec

        if not template:
            clone_spec.powerOn = power

        log.debug('clone_spec set to:\n%s', pprint.pformat(clone_spec))

    else:
        config_spec.name = vm_name
        config_spec.files = vim.vm.FileInfo()
        config_spec.files.vmPathName = '[{0}] {1}/{1}.vmx'.format(datastore, vm_name)
        config_spec.guestId = guest_id

        log.debug('config_spec set to:\n%s', pprint.pformat(config_spec))

    event_kwargs = vm_.copy()
    if event_kwargs.get('password'):
        del event_kwargs['password']

    try:
        __utils__['cloud.fire_event'](
            'event',
            'requesting instance',
            'salt/cloud/{0}/requesting'.format(vm_['name']),
            args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        if 'clonefrom' in vm_:
            log.info("Creating %s from %s(%s)", vm_['name'], clone_type, vm_['clonefrom'])

            if datastore and not datastore_ref and datastore_cluster_ref:
                # datastore cluster has been specified so apply Storage DRS recommendations
                pod_spec = vim.storageDrs.PodSelectionSpec(storagePod=datastore_cluster_ref)

                storage_spec = vim.storageDrs.StoragePlacementSpec(
                    type='clone',
                    vm=object_ref,
                    podSelectionSpec=pod_spec,
                    cloneSpec=clone_spec,
                    cloneName=vm_name,
                    folder=folder_ref
                )

                # get recommended datastores
                recommended_datastores = si.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec)

                # apply storage DRS recommendations
                task = si.content.storageResourceManager.ApplyStorageDrsRecommendation_Task(recommended_datastores.recommendations[0].key)
                salt.utils.vmware.wait_for_task(task, vm_name, 'apply storage DRS recommendations', 5, 'info')
            else:
                # clone the VM/template
                task = object_ref.Clone(folder_ref, vm_name, clone_spec)
                salt.utils.vmware.wait_for_task(task, vm_name, 'clone', 5, 'info')
        else:
            log.info('Creating %s', vm_['name'])

            if host:
                task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref, host_ref)
            else:
                task = folder_ref.CreateVM_Task(config_spec, resourcepool_ref)
            salt.utils.vmware.wait_for_task(task, vm_name, "create", 15, 'info')
    except Exception as exc:
        err_msg = 'Error creating {0}: {1}'.format(vm_['name'], exc)
        log.error(
            err_msg,
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return {'Error': err_msg}

    new_vm_ref = salt.utils.vmware.get_mor_by_property(si, vim.VirtualMachine, vm_name, container_ref=container_ref)

    # Find how to power on in CreateVM_Task (if possible), for now this will do
    try:
        if not clone_type and power:
            task = new_vm_ref.PowerOn()
            salt.utils.vmware.wait_for_task(task, vm_name, 'power', 5, 'info')
    except Exception as exc:
        log.info('Powering on the VM threw this exception. Ignoring.')
        log.info(exc)

    # If it a template or if it does not need to be powered on then do not wait for the IP
    out = None
    if not template and power:
        ip = _wait_for_ip(new_vm_ref, wait_for_ip_timeout)
        if ip:
            log.info("[ %s ] IPv4 is: %s", vm_name, ip)
            # ssh or smb using ip and install salt only if deploy is True
            if deploy:
                vm_['key_filename'] = key_filename
                # if specified, prefer ssh_host to the discovered ip address
                if 'ssh_host' not in vm_:
                    vm_['ssh_host'] = ip
                log.info("[ %s ] Deploying to %s", vm_name, vm_['ssh_host'])

                out = __utils__['cloud.bootstrap'](vm_, __opts__)

    data = show_instance(vm_name, call='action')

    if deploy and isinstance(out, dict):
        data['deploy_kwargs'] = out.get('deploy_kwargs', {})

    __utils__['cloud.fire_event'](
        'event',
        'created instance',
        'salt/cloud/{0}/created'.format(vm_['name']),
        args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return data
919873
def execute_on_vm(vm, options)
      check_runable_on(vm)

      options     = options.clone
      _method     = options.delete(:_method)
      _rebootable = options.delete(:_rebootable)

      options = vm.config.vbguest.to_hash.merge(options)
      machine = VagrantVbguest::Machine.new(vm, options)
      status  = machine.state
      vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", machine.info))

      if _method != :status
        machine.send(_method)
      end

      reboot!(vm, options) if _rebootable && machine.reboot?
    rescue VagrantVbguest::Installer::NoInstallerFoundError => e
      vm.env.ui.error e.message
    end
1041963
def generate_vagrant_set
      sets = [generate_builtin_set, generate_plugin_set]
      if env_plugin_gem_path && env_plugin_gem_path.exist?
        sets << generate_plugin_set(env_plugin_gem_path)
      end
      Gem::Resolver.compose_sets(*sets)
    end
256382
def add_vhost(vhost, runas=None):
    '''
    
    '''
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    res = __salt__['cmd.run_all'](
        [RABBITMQCTL, 'add_vhost', vhost],
        reset_system_locale=False,
        runas=runas,
        python_shell=False)

    msg = 'Added'
    return _format_response(res, msg)
1281921
def execute(node):
    
    with hide('everything'):
        virt = json.loads(sudo('ohai virtualization'))
    if not len(virt) or virt[0][1] != "host":
        # It may work for virtualization solutions other than Xen
        print("This node is not a Xen host, doing nothing")
        return
    node['virtualization'] = {
        'role': 'host',
        'system': 'xen',
        'vms': [],
    }
    # VMs
    with hide('everything'):
        vm_list = sudo("xm list")
    for vm in vm_list.split("\n")[2:]:
        data = vm.split()
        if len(data) != 6:
            break
        node['virtualization']['vms'].append({
            'fqdn': data[0], 'RAM': data[2], 'cpus': data[3]})
    print("Found {0} VMs for this Xen host".format(
          len(node['virtualization']['vms'])))
    # Save node file and remove the returned temp file
    del node['name']
    os.remove(chef.save_config(node, True))
525492
def ensure_vm_running(self, vm_location):
        
        import vagrant

        if self.vagrant is None:
            vagrant_file = vm_location / "Vagrantfile"
            if not vagrant_file.exists():
                self.init_vagrant(vagrant_file)

            self.vagrant = vagrant.Vagrant(vm_location,
                                           quiet_stdout=self.quiet,
                                           quiet_stderr=self.quiet,
                                           out_cm=self.log_cm,
                                           err_cm=self.log_cm)

        status = [x for x in self.vagrant.status() if x.name == "default"][0]

        if status.state != "running":
            try:
                self.vagrant.up()
            except subprocess.CalledProcessError:
                raise BuildError("Vagrant VM couldn't up launched. See output for details.")
238265
def ssh(self, vm_name=None, command=None, extra_ssh_args=None):
        '''
        
        '''
        cmd = ['ssh', vm_name, '--command', command]
        if extra_ssh_args is not None:
            cmd += ['--', extra_ssh_args]

        return self._run_vagrant_command(cmd)