Create a single VM from a data dict
541014
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 'gogrid',
                                                           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']
    )

    if len(vm_['name']) > 20:
        raise SaltCloudException('VM names must not be longer than 20 characters')

    log.info('Creating Cloud VM %s', vm_['name'])
    image_id = avail_images()[vm_['image']]['id']
    if 'assign_public_ip' in vm_:
        host_ip = vm_['assign_public_ip']
    else:
        public_ips = list_public_ips()
        if not public_ips:
            raise SaltCloudException('No more IPs available')
        host_ip = next(iter(public_ips))

    create_kwargs = {
        'name': vm_['name'],
        'image': image_id,
        'ram': vm_['size'],
        'ip': host_ip,
    }

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

    try:
        data = _query('grid', 'server/add', args=create_kwargs)
    except Exception:
        log.error(
            'Error creating %s on GOGRID\n\n'
            'The following exception was thrown when trying to '
            'run the initial deployment:\n', vm_['name'],
            # Show the traceback if the debug logging level is enabled
            exc_info_on_loglevel=logging.DEBUG
        )
        return False

    ssh_username = config.get_cloud_config_value(
        'ssh_username', vm_, __opts__, default='root'
    )

    def wait_for_apipass():
        '''
        Wait for the password to become available, via the API
        '''
        try:
            passwords = list_passwords()
            return passwords[vm_['name']][0]['password']
        except KeyError:
            pass
        time.sleep(5)
        return False

    vm_['password'] = salt.utils.cloud.wait_for_fun(
        wait_for_apipass,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )

    vm_['ssh_host'] = host_ip
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)
    ret.update(data)

    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
862257
def process_vm_json( self, json_dict, **kwargs ):
        ''' 
        ''' 
        mrf_lines = convert_vm_json_to_mrf( json_dict )
        return self.process_mrf_lines( mrf_lines, **kwargs )
762887
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 'azure',
                                                           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']
    )

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

    label = vm_.get('label', vm_['name'])
    service_name = vm_.get('service_name', vm_['name'])
    service_kwargs = {
        'service_name': service_name,
        'label': label,
        'description': vm_.get('desc', vm_['name']),
    }

    loc_error = False
    if 'location' in vm_:
        if 'affinity_group' in vm_:
            loc_error = True
        else:
            service_kwargs['location'] = vm_['location']
    elif 'affinity_group' in vm_:
        service_kwargs['affinity_group'] = vm_['affinity_group']
    else:
        loc_error = True

    if loc_error:
        raise SaltCloudSystemExit(
            'Either a location or affinity group must be specified, but not both'
        )

    ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
                                             default=22, search_global=True)

    ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
        name='SSH',
        protocol='TCP',
        port=ssh_port,
        local_port=22,
    )

    network_config = azure.servicemanagement.ConfigurationSet()
    network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
    network_config.configuration_set_type = 'NetworkConfiguration'

    if 'win_username' in vm_:
        system_config = azure.servicemanagement.WindowsConfigurationSet(
            computer_name=vm_['name'],
            admin_username=vm_['win_username'],
            admin_password=vm_['win_password'],
        )

        smb_port = '445'
        if 'smb_port' in vm_:
            smb_port = vm_['smb_port']

        smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
            name='SMB',
            protocol='TCP',
            port=smb_port,
            local_port=smb_port,
        )

        network_config.input_endpoints.input_endpoints.append(smb_endpoint)

        # Domain and WinRM configuration not yet supported by Salt Cloud
        system_config.domain_join = None
        system_config.win_rm = None

    else:
        system_config = azure.servicemanagement.LinuxConfigurationSet(
            host_name=vm_['name'],
            user_name=vm_['ssh_username'],
            user_password=vm_['ssh_password'],
            disable_ssh_password_authentication=False,
        )

    # TODO: Might need to create a storage account
    media_link = vm_['media_link']
    # TODO: Probably better to use more than just the name in the media_link
    media_link += '/{0}.vhd'.format(vm_['name'])
    os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)

    vm_kwargs = {
        'service_name': service_name,
        'deployment_name': service_name,
        'deployment_slot': vm_['slot'],
        'label': label,
        'role_name': vm_['name'],
        'system_config': system_config,
        'os_virtual_hard_disk': os_hd,
        'role_size': vm_['size'],
        'network_config': network_config,
    }

    if 'virtual_network_name' in vm_:
        vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
        if 'subnet_name' in vm_:
            network_config.subnet_names.append(vm_['subnet_name'])

    log.debug('vm_kwargs: %s', vm_kwargs)

    event_kwargs = {'service_kwargs': service_kwargs.copy(),
                    'vm_kwargs': vm_kwargs.copy()}
    del event_kwargs['vm_kwargs']['system_config']
    del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
    del event_kwargs['vm_kwargs']['network_config']
    __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']
    )
    log.debug('vm_kwargs: %s', vm_kwargs)

    # Azure lets you open winrm on a new VM
    # Can open up specific ports in Azure; but not on Windows
    try:
        conn.create_hosted_service(**service_kwargs)
    except AzureConflictHttpError:
        log.debug('Cloud service already exists')
    except Exception as exc:
        error = 'The hosted service name is invalid.'
        if error in six.text_type(exc):
            log.error(
                'Error creating %s on Azure.\n\n'
                'The hosted service name is invalid. The name can contain '
                'only letters, numbers, and hyphens. The name must start with '
                'a letter and must end with a letter or a number.',
                vm_['name'],
                # Show the traceback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
        else:
            log.error(
                'Error creating %s on Azure\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
            )
        return False
    try:
        result = conn.create_virtual_machine_deployment(**vm_kwargs)
        log.debug('Request ID for machine: %s', result.request_id)
        _wait_for_async(conn, result.request_id)
    except AzureConflictHttpError:
        log.debug('Conflict error. The deployment may already exist, trying add_role')
        # Deleting two useless keywords
        del vm_kwargs['deployment_slot']
        del vm_kwargs['label']
        del vm_kwargs['virtual_network_name']
        result = conn.add_role(**vm_kwargs)
        _wait_for_async(conn, result.request_id)
    except Exception as exc:
        error = 'The hosted service name is invalid.'
        if error in six.text_type(exc):
            log.error(
                'Error creating %s on Azure.\n\n'
                'The VM name is invalid. The name can contain '
                'only letters, numbers, and hyphens. The name must start with '
                'a letter and must end with a letter or a number.',
                vm_['name'],
                # Show the traceback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
        else:
            log.error(
                'Error creating %s on Azure.\n\n'
                'The Virtual Machine could not be created. If you '
                'are using an already existing Cloud Service, '
                'make sure you set up the `port` variable corresponding '
                'to the SSH port exists and that the port number is not '
                'already in use.\nThe 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
            )
        return False

    def wait_for_hostname():
        '''
        Wait for the IP address to become available
        '''
        try:
            conn.get_role(service_name, service_name, vm_['name'])
            data = show_instance(vm_['name'], call='action')
            if 'url' in data and data['url'] != six.text_type(''):
                return data['url']
        except AzureMissingResourceHttpError:
            pass
        time.sleep(1)
        return False

    hostname = salt.utils.cloud.wait_for_fun(
        wait_for_hostname,
        timeout=config.get_cloud_config_value(
            'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
    )

    if not hostname:
        log.error('Failed to get a value for the hostname.')
        return False

    vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
    vm_['password'] = config.get_cloud_config_value(
        'ssh_password', vm_, __opts__
    )
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    # Attaching volumes
    volumes = config.get_cloud_config_value(
        'volumes', vm_, __opts__, search_global=True
    )
    if volumes:
        __utils__['cloud.fire_event'](
            'event',
            'attaching volumes',
            'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
            args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )

        log.info('Create and attach volumes to node %s', vm_['name'])
        created = create_attach_volumes(
            vm_['name'],
            {
                'volumes': volumes,
                'service_name': service_name,
                'deployment_name': vm_['name'],
                'media_link': media_link,
                'role_name': vm_['name'],
                'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
            },
            call='action'
        )
        ret['Attached Volumes'] = created

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

    ret.update(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
838358
def _clone_vm(image=None, name=None, session=None):
    '''
    

    '''
    if session is None:
        session = _get_session()
    log.debug('Creating VM %s by cloning %s', name, image)
    source = _get_vm(image, session)
    task = session.xenapi.Async.VM.clone(source, name)
    _run_async_task(task, session)
1243471
def create(gandi, name, vm, size, snapshotprofile, datacenter, source,
           background):
    
    try:
        gandi.datacenter.is_opened(datacenter, 'iaas')
    except DatacenterLimited as exc:
        gandi.echo('/!\ Datacenter %s will be closed on %s, '
                   'please consider using another datacenter.' %
                   (datacenter, exc.date))

    if vm:
        vm_dc = gandi.iaas.info(vm)
        vm_dc_id = vm_dc['datacenter_id']
        dc_id = int(gandi.datacenter.usable_id(datacenter))
        if vm_dc_id != dc_id:
            gandi.echo('/!\ VM %s datacenter will be used instead of %s.'
                       % (vm, datacenter))
        datacenter = vm_dc_id

    output_keys = ['id', 'type', 'step']
    name = name or randomstring('vdi')

    disk_type = 'data'
    oper = gandi.disk.create(name, vm, size, snapshotprofile, datacenter,
                             source, disk_type, background)

    if background:
        output_generic(gandi, oper, output_keys)

    return oper
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
1335697
def create(cls, name, vm, size, snapshotprofile, datacenter,
               source, disk_type='data', background=False):
        
        if isinstance(size, tuple):
            prefix, size = size

        if source:
            size = None
        disk_params = cls.disk_param(name, size, snapshotprofile)
        disk_params['datacenter_id'] = int(Datacenter.usable_id(datacenter))
        disk_params['type'] = disk_type

        if source:
            disk_id = int(Image.usable_id(source,
                                          disk_params['datacenter_id']))
            result = cls.call('hosting.disk.create_from', disk_params, disk_id)
        else:
            result = cls.call('hosting.disk.create', disk_params)

        if background and not vm:
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your disk.')
        cls.display_progress(result)

        if not vm:
            return

        vm_id = Iaas.usable_id(vm)
        result = cls._attach(result['disk_id'], vm_id)

        if background:
            return result

        cls.echo('Attaching your disk.')
        cls.display_progress(result)
597432
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'environment_id' in _dict:
            args['environment_id'] = _dict.get('environment_id')
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        if 'description' in _dict:
            args['description'] = _dict.get('description')
        if 'created' in _dict:
            args['created'] = string_to_datetime(_dict.get('created'))
        if 'updated' in _dict:
            args['updated'] = string_to_datetime(_dict.get('updated'))
        if 'status' in _dict:
            args['status'] = _dict.get('status')
        if 'read_only' in _dict:
            args['read_only'] = _dict.get('read_only')
        if 'size' in _dict:
            args['size'] = _dict.get('size')
        if 'requested_size' in _dict:
            args['requested_size'] = _dict.get('requested_size')
        if 'index_capacity' in _dict:
            args['index_capacity'] = IndexCapacity._from_dict(
                _dict.get('index_capacity'))
        if 'search_status' in _dict:
            args['search_status'] = SearchStatus._from_dict(
                _dict.get('search_status'))
        return cls(**args)
813145
def volume_create(name, size=100, snapshot=None, voltype=None, **kwargs):
    '''
    
    '''
    conn = get_conn()
    create_kwargs = {'name': name,
                     'size': size,
                     'snapshot': snapshot,
                     'voltype': voltype}
    create_kwargs['availability_zone'] = kwargs.get('availability_zone', None)
    return conn.volume_create(**create_kwargs)
425197
def vms(nictag):
    '''
    
    '''
    ret = {}
    cmd = 'nictagadm vms {0}'.format(nictag)
    res = __salt__['cmd.run_all'](cmd)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.'
    else:
        ret = res['stdout'].splitlines()
    return ret
1287779
def _find_vm(name, data, quiet=False):
    '''
    
    '''
    for hv_ in data:
        # Check if data is a dict, and not '"virt.full_info" is not available.'
        if not isinstance(data[hv_], dict):
            continue
        if name in data[hv_].get('vm_info', {}):
            ret = {hv_: {name: data[hv_]['vm_info'][name]}}
            if not quiet:
                __jid_event__.fire_event({'data': ret, 'outputter': 'nested'}, 'progress')
            return ret
    return {}
361364
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'documents' in _dict:
            args['documents'] = EnvironmentDocuments._from_dict(
                _dict.get('documents'))
        if 'disk_usage' in _dict:
            args['disk_usage'] = DiskUsage._from_dict(_dict.get('disk_usage'))
        if 'collections' in _dict:
            args['collections'] = CollectionUsage._from_dict(
                _dict.get('collections'))
        return cls(**args)
377906
def _create_update_from_cfg(mode='create', uuid=None, vmcfg=None):
    '''
    
    '''
    ret = {}

    # write json file
    vmadm_json_file = __salt__['temp.file'](prefix='vmadm-')
    with salt.utils.files.fopen(vmadm_json_file, 'w') as vmadm_json:
        salt.utils.json.dump(vmcfg, vmadm_json)

    # vmadm validate create|update [-f <filename>]
    cmd = 'vmadm validate {mode} {brand} -f {vmadm_json_file}'.format(
        mode=mode,
        brand=get(uuid)['brand'] if uuid is not None else '',
        vmadm_json_file=vmadm_json_file
    )
    res = __salt__['cmd.run_all'](cmd, python_shell=True)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = _exit_status(retcode)
        if 'stderr' in res:
            if res['stderr'][0] == '{':
                ret['Error'] = salt.utils.json.loads(res['stderr'])
            else:
                ret['Error'] = res['stderr']
        return ret
    # vmadm create|update [-f <filename>]
    cmd = 'vmadm {mode} {uuid} -f {vmadm_json_file}'.format(
        mode=mode,
        uuid=uuid if uuid is not None else '',
        vmadm_json_file=vmadm_json_file
    )
    res = __salt__['cmd.run_all'](cmd, python_shell=True)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = _exit_status(retcode)
        if 'stderr' in res:
            if res['stderr'][0] == '{':
                ret['Error'] = salt.utils.json.loads(res['stderr'])
            else:
                ret['Error'] = res['stderr']
        return ret
    else:
        # cleanup json file (only when successful to help troubleshooting)
        salt.utils.files.safe_rm(vmadm_json_file)

        # return uuid
        if res['stderr'].startswith('Successfully created VM'):
            return res['stderr'][24:]

    return True
683972
def create_datacenter(service_instance, datacenter_name):
    '''
    
    '''
    root_folder = get_root_folder(service_instance)
    log.trace('Creating datacenter \'%s\'', datacenter_name)
    try:
        dc_obj = root_folder.CreateDatacenter(datacenter_name)
    except vim.fault.NoPermission as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(
            'Not enough permissions. Required privilege: '
            '{}'.format(exc.privilegeId))
    except vim.fault.VimFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareApiError(exc.msg)
    except vmodl.RuntimeFault as exc:
        log.exception(exc)
        raise salt.exceptions.VMwareRuntimeError(exc.msg)
    return dc_obj
187209
def create(vm_):
    '''
    
    '''
    creds = get_creds()
    clc.v1.SetCredentials(creds["token"], creds["token_pass"])
    cloud_profile = config.is_provider_configured(
        __opts__,
        __active_provider_name__ or __virtualname__,
        ('token',)
    )
    group = config.get_cloud_config_value(
        'group', vm_, __opts__, search_global=False, default=None,
    )
    name = vm_['name']
    description = config.get_cloud_config_value(
        'description', vm_, __opts__, search_global=False, default=None,
    )
    ram = config.get_cloud_config_value(
        'ram', vm_, __opts__, search_global=False, default=None,
    )
    backup_level = config.get_cloud_config_value(
        'backup_level', vm_, __opts__, search_global=False, default=None,
    )
    template = config.get_cloud_config_value(
        'template', vm_, __opts__, search_global=False, default=None,
    )
    password = config.get_cloud_config_value(
        'password', vm_, __opts__, search_global=False, default=None,
    )
    cpu = config.get_cloud_config_value(
        'cpu', vm_, __opts__, search_global=False, default=None,
    )
    network = config.get_cloud_config_value(
        'network', vm_, __opts__, search_global=False, default=None,
    )
    location = config.get_cloud_config_value(
        'location', vm_, __opts__, search_global=False, default=None,
    )
    if len(name) > 6:
        name = name[0:6]
    if len(password) < 9:
        password = ''
    clc_return = clc.v1.Server.Create(alias=None, location=(location), name=(name), template=(template), cpu=(cpu), ram=(ram), backup_level=(backup_level), group=(group), network=(network), description=(description), password=(password))
    req_id = clc_return["RequestID"]
    vm_['ssh_host'] = get_build_status(req_id, name)
    __utils__['cloud.fire_event'](
        'event',
        'waiting for ssh',
        'salt/cloud/{0}/waiting_for_ssh'.format(name),
        sock_dir=__opts__['sock_dir'],
        args={'ip_address': vm_['ssh_host']},
        transport=__opts__['transport']
    )

    # Bootstrap!
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)
    return_message = {"Server Name": name, "IP Address": vm_['ssh_host']}
    ret.update(return_message)
    return return_message
1115968
def request_instance(vm_):
    '''
    
    '''
    compconn = get_conn(client_type='compute')

    # pylint: disable=invalid-name
    CachingTypes = getattr(
        compute_models, 'CachingTypes'
    )
    # pylint: disable=invalid-name
    DataDisk = getattr(
        compute_models, 'DataDisk'
    )
    # pylint: disable=invalid-name
    DiskCreateOptionTypes = getattr(
        compute_models, 'DiskCreateOptionTypes'
    )
    # pylint: disable=invalid-name
    HardwareProfile = getattr(
        compute_models, 'HardwareProfile'
    )
    # pylint: disable=invalid-name
    ImageReference = getattr(
        compute_models, 'ImageReference'
    )
    # pylint: disable=invalid-name
    LinuxConfiguration = getattr(
        compute_models, 'LinuxConfiguration'
    )
    # pylint: disable=invalid-name
    SshConfiguration = getattr(
        compute_models, 'SshConfiguration'
    )
    # pylint: disable=invalid-name
    SshPublicKey = getattr(
        compute_models, 'SshPublicKey'
    )
    # pylint: disable=invalid-name
    NetworkInterfaceReference = getattr(
        compute_models, 'NetworkInterfaceReference'
    )
    # pylint: disable=invalid-name
    NetworkProfile = getattr(
        compute_models, 'NetworkProfile'
    )
    # pylint: disable=invalid-name
    OSDisk = getattr(
        compute_models, 'OSDisk'
    )
    # pylint: disable=invalid-name
    OSProfile = getattr(
        compute_models, 'OSProfile'
    )
    # pylint: disable=invalid-name
    StorageProfile = getattr(
        compute_models, 'StorageProfile'
    )
    # pylint: disable=invalid-name
    VirtualHardDisk = getattr(
        compute_models, 'VirtualHardDisk'
    )
    # pylint: disable=invalid-name
    VirtualMachine = getattr(
        compute_models, 'VirtualMachine'
    )
    # pylint: disable=invalid-name
    VirtualMachineSizeTypes = getattr(
        compute_models, 'VirtualMachineSizeTypes'
    )

    subscription_id = config.get_cloud_config_value(
        'subscription_id',
        get_configured_provider(), __opts__, search_global=False
    )

    if vm_.get('driver') is None:
        vm_['driver'] = 'azurearm'

    if vm_.get('location') is None:
        vm_['location'] = get_location()

    if vm_.get('resource_group') is None:
        vm_['resource_group'] = config.get_cloud_config_value(
            'resource_group', vm_, __opts__, search_global=True
        )

    if vm_.get('name') is None:
        vm_['name'] = config.get_cloud_config_value(
            'name', vm_, __opts__, search_global=True
        )

    # pylint: disable=unused-variable
    iface_data, public_ips, private_ips = create_network_interface(
        call='action',
        kwargs=vm_
    )
    vm_['iface_id'] = iface_data['id']

    disk_name = '{0}-vol0'.format(vm_['name'])

    vm_username = config.get_cloud_config_value(
        'ssh_username', vm_, __opts__, search_global=True,
        default=config.get_cloud_config_value(
            'win_username', vm_, __opts__, search_global=True
        )
    )

    ssh_publickeyfile_contents = None
    ssh_publickeyfile = config.get_cloud_config_value(
        'ssh_publickeyfile',
        vm_,
        __opts__,
        search_global=False,
        default=None
    )
    if ssh_publickeyfile is not None:
        try:
            with salt.utils.files.fopen(ssh_publickeyfile, 'r') as spkc_:
                ssh_publickeyfile_contents = spkc_.read()
        except Exception as exc:
            raise SaltCloudConfigError(
                "Failed to read ssh publickey file '{0}': "
                "{1}".format(ssh_publickeyfile,
                             exc.args[-1])
            )

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

    vm_password = salt.utils.stringutils.to_str(
        config.get_cloud_config_value(
            'ssh_password', vm_, __opts__, search_global=True,
            default=config.get_cloud_config_value(
                'win_password', vm_, __opts__, search_global=True
            )
        )
    )

    os_kwargs = {}
    win_installer = config.get_cloud_config_value(
        'win_installer', vm_, __opts__, search_global=True
    )
    if not win_installer and ssh_publickeyfile_contents is not None:
        sshpublickey = SshPublicKey(
            key_data=ssh_publickeyfile_contents,
            path='/home/{0}/.ssh/authorized_keys'.format(vm_username),
        )
        sshconfiguration = SshConfiguration(
            public_keys=[sshpublickey],
        )
        linuxconfiguration = LinuxConfiguration(
            disable_password_authentication=disable_password_authentication,
            ssh=sshconfiguration,
        )
        os_kwargs['linux_configuration'] = linuxconfiguration

    if win_installer or (vm_password is not None and not disable_password_authentication):
        if not isinstance(vm_password, str):
            raise SaltCloudSystemExit(
                'The admin password must be a string.'
            )
        if len(vm_password) < 8 or len(vm_password) > 123:
            raise SaltCloudSystemExit(
                'The admin password must be between 8-123 characters long.'
            )
        complexity = 0
        if any(char.isdigit() for char in vm_password):
            complexity += 1
        if any(char.isupper() for char in vm_password):
            complexity += 1
        if any(char.islower() for char in vm_password):
            complexity += 1
        if any(char in string.punctuation for char in vm_password):
            complexity += 1
        if complexity < 3:
            raise SaltCloudSystemExit(
                'The admin password must contain at least 3 of the following types: '
                'upper, lower, digits, special characters'
            )
        os_kwargs['admin_password'] = vm_password

    availability_set = config.get_cloud_config_value(
        'availability_set',
        vm_,
        __opts__,
        search_global=False,
        default=None
    )
    if availability_set is not None and isinstance(availability_set, six.string_types):
        availability_set = {
            'id': '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/availabilitySets/{2}'.format(
                subscription_id,
                vm_['resource_group'],
                availability_set
            )
        }
    else:
        availability_set = None

    cloud_env = _get_cloud_environment()

    storage_endpoint_suffix = cloud_env.suffixes.storage_endpoint

    if isinstance(vm_.get('volumes'), six.string_types):
        volumes = salt.utils.yaml.safe_load(vm_['volumes'])
    else:
        volumes = vm_.get('volumes')

    data_disks = None
    if isinstance(volumes, list):
        data_disks = []
    else:
        volumes = []

    lun = 0
    luns = []
    for volume in volumes:
        if isinstance(volume, six.string_types):
            volume = {'name': volume}

        volume.setdefault(
            'name',
            volume.get(
                'name',
                volume.get(
                    'name',
                    '{0}-datadisk{1}'.format(vm_['name'], six.text_type(lun))
                )
            )
        )

        volume.setdefault(
            'disk_size_gb',
            volume.get(
                'logical_disk_size_in_gb',
                volume.get('size', 100)
            )
        )
        # Old kwarg was host_caching, new name is caching
        volume.setdefault('caching', volume.get('host_caching', 'ReadOnly'))
        while lun in luns:
            lun += 1
            if lun > 15:
                log.error('Maximum lun count has been reached')
                break
        volume.setdefault('lun', lun)
        lun += 1
        # The default vhd is {vm_name}-datadisk{lun}.vhd
        if 'media_link' in volume:
            volume['vhd'] = VirtualHardDisk(volume['media_link'])
            del volume['media_link']
        elif volume.get('vhd') == 'unmanaged':
            volume['vhd'] = VirtualHardDisk(
                'https://{0}.blob.{1}/vhds/{2}-datadisk{3}.vhd'.format(
                    vm_['storage_account'],
                    storage_endpoint_suffix,
                    vm_['name'],
                    volume['lun'],
                ),
            )
        elif 'vhd' in volume:
            volume['vhd'] = VirtualHardDisk(volume['vhd'])

        if 'image' in volume:
            volume['create_option'] = 'from_image'
        elif 'attach' in volume:
            volume['create_option'] = 'attach'
        else:
            volume['create_option'] = 'empty'
        data_disks.append(DataDisk(**volume))

    img_ref = None
    if vm_['image'].startswith('http') or vm_.get('vhd') == 'unmanaged':
        if vm_['image'].startswith('http'):
            source_image = VirtualHardDisk(vm_['image'])
        else:
            source_image = None
            if '|' in vm_['image']:
                img_pub, img_off, img_sku, img_ver = vm_['image'].split('|')
                img_ref = ImageReference(
                    publisher=img_pub,
                    offer=img_off,
                    sku=img_sku,
                    version=img_ver,
                )
            elif vm_['image'].startswith('/subscriptions'):
                img_ref = ImageReference(id=vm_['image'])
        if win_installer:
            os_type = 'Windows'
        else:
            os_type = 'Linux'
        os_disk = OSDisk(
            caching=CachingTypes.none,
            create_option=DiskCreateOptionTypes.from_image,
            name=disk_name,
            vhd=VirtualHardDisk(
                'https://{0}.blob.{1}/vhds/{2}.vhd'.format(
                    vm_['storage_account'],
                    storage_endpoint_suffix,
                    disk_name,
                ),
            ),
            os_type=os_type,
            image=source_image,
            disk_size_gb=vm_.get('os_disk_size_gb')
        )
    else:
        source_image = None
        os_type = None
        os_disk = OSDisk(
            create_option=DiskCreateOptionTypes.from_image,
            disk_size_gb=vm_.get('os_disk_size_gb')
        )
        if '|' in vm_['image']:
            img_pub, img_off, img_sku, img_ver = vm_['image'].split('|')
            img_ref = ImageReference(
                publisher=img_pub,
                offer=img_off,
                sku=img_sku,
                version=img_ver,
            )
        elif vm_['image'].startswith('/subscriptions'):
            img_ref = ImageReference(id=vm_['image'])

    userdata_file = config.get_cloud_config_value(
        'userdata_file', vm_, __opts__, search_global=False, default=None
    )
    userdata = config.get_cloud_config_value(
        'userdata', vm_, __opts__, search_global=False, default=None
    )
    userdata_template = config.get_cloud_config_value(
        'userdata_template', vm_, __opts__, search_global=False, default=None
    )

    if userdata_file:
        if os.path.exists(userdata_file):
            with salt.utils.files.fopen(userdata_file, 'r') as fh_:
                userdata = fh_.read()

    if userdata and userdata_template:
        userdata_sendkeys = config.get_cloud_config_value(
            'userdata_sendkeys', vm_, __opts__, search_global=False, default=None
        )
        if userdata_sendkeys:
            vm_['priv_key'], vm_['pub_key'] = salt.utils.cloud.gen_keys(
                config.get_cloud_config_value(
                    'keysize',
                    vm_,
                    __opts__
                )
            )

            key_id = vm_.get('name')
            if 'append_domain' in vm_:
                key_id = '.'.join([key_id, vm_['append_domain']])

            salt.utils.cloud.accept_key(
                __opts__['pki_dir'], vm_['pub_key'], key_id
            )

        userdata = salt.utils.cloud.userdata_template(__opts__, vm_, userdata)

    custom_extension = None
    if userdata is not None or userdata_file is not None:
        try:
            if win_installer:
                publisher = 'Microsoft.Compute'
                virtual_machine_extension_type = 'CustomScriptExtension'
                type_handler_version = '1.8'
                if userdata_file and userdata_file.endswith('.ps1'):
                    command_prefix = 'powershell -ExecutionPolicy Unrestricted -File '
                else:
                    command_prefix = ''
            else:
                publisher = 'Microsoft.Azure.Extensions'
                virtual_machine_extension_type = 'CustomScript'
                type_handler_version = '2.0'
                command_prefix = ''

            settings = {}
            if userdata:
                settings['commandToExecute'] = userdata
            elif userdata_file.startswith('http'):
                settings['fileUris'] = [userdata_file]
                settings['commandToExecute'] = command_prefix + './' + userdata_file[userdata_file.rfind('/')+1:]

            custom_extension = {
                'resource_group': vm_['resource_group'],
                'virtual_machine_name': vm_['name'],
                'extension_name': vm_['name'] + '_custom_userdata_script',
                'location': vm_['location'],
                'publisher': publisher,
                'virtual_machine_extension_type': virtual_machine_extension_type,
                'type_handler_version': type_handler_version,
                'auto_upgrade_minor_version': True,
                'settings': settings,
                'protected_settings': None
            }
        except Exception as exc:
            log.exception('Failed to encode userdata: %s', exc)

    params = VirtualMachine(
        location=vm_['location'],
        plan=None,
        hardware_profile=HardwareProfile(
            vm_size=getattr(
                VirtualMachineSizeTypes, vm_['size'].lower()
            ),
        ),
        storage_profile=StorageProfile(
            os_disk=os_disk,
            data_disks=data_disks,
            image_reference=img_ref,
        ),
        os_profile=OSProfile(
            admin_username=vm_username,
            computer_name=vm_['name'],
            **os_kwargs
        ),
        network_profile=NetworkProfile(
            network_interfaces=[
                NetworkInterfaceReference(vm_['iface_id']),
            ],
        ),
        availability_set=availability_set,
    )

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

    try:
        vm_create = compconn.virtual_machines.create_or_update(
            resource_group_name=vm_['resource_group'],
            vm_name=vm_['name'],
            parameters=params
        )
        vm_create.wait()
        vm_result = vm_create.result()
        vm_result = vm_result.as_dict()
        if custom_extension:
            create_or_update_vmextension(kwargs=custom_extension)
    except CloudError as exc:
        __utils__['azurearm.log_cloud_error']('compute', exc.message)
        vm_result = {}

    return vm_result
745876
def _generate_create_dict(self,
                              hostname=None,
                              domain=None,
                              flavor=None,
                              router=None,
                              datacenter=None,
                              hourly=True):
        """"""
        package = self._get_package()
        item = self._get_item(package, flavor)

        location = self._get_location(package['regions'], datacenter)
        price = self._get_price(item)

        routers = self._get_backend_router(
            location['location']['locationPackageDetails'], item)

        router = self._get_default_router(routers, router)

        hardware = {
            'hostname': hostname,
            'domain': domain,
            'primaryBackendNetworkComponent': {
                'router': {
                    'id': router
                }
            }
        }

        complex_type = "SoftLayer_Container_Product_Order_Virtual_DedicatedHost"

        order = {
            "complexType": complex_type,
            "quantity": 1,
            'location': location['keyname'],
            'packageId': package['id'],
            'prices': [{'id': price}],
            'hardware': [hardware],
            'useHourlyPricing': hourly,
        }
        return order