Create a new virtual machine.
493028
def create(cls, datacenter, memory, cores, ip_version, bandwidth,
               login, password, hostname, image, run, background, sshkey,
               size, vlan, ip, script, script_args, ssh):
        """"""
        from gandi.cli.modules.network import Ip, Iface
        if not background and not cls.intty():
            background = True

        datacenter_id_ = int(Datacenter.usable_id(datacenter))

        if not hostname:
            hostname = randomstring('vm')
            disk_name = 'sys_%s' % hostname[2:]
        else:
            disk_name = 'sys_%s' % hostname.replace('.', '')

        vm_params = {
            'hostname': hostname,
            'datacenter_id': datacenter_id_,
            'memory': memory,
            'cores': cores,
        }

        if login:
            vm_params['login'] = login

        if run:
            vm_params['run'] = run

        if password:
            vm_params['password'] = password

        if ip_version:
            vm_params['ip_version'] = ip_version
            vm_params['bandwidth'] = bandwidth

        if script:
            with open(script) as fd:
                vm_params['script'] = fd.read()
            if script_args:
                vm_params['script_args'] = script_args

        vm_params.update(cls.convert_sshkey(sshkey))

        # XXX: name of disk is limited to 15 chars in ext2fs, ext3fs
        # but api allow 255, so we limit to 15 for now
        disk_params = {'datacenter_id': vm_params['datacenter_id'],
                       'name': disk_name[:15]}

        if size:
            if isinstance(size, tuple):
                prefix, size = size
            disk_params['size'] = size

        sys_disk_id_ = int(Image.usable_id(image, datacenter_id_))

        ip_summary = []
        if ip_version == 4:
            ip_summary = ['v4', 'v6']
        elif ip_version == 6:
            ip_summary = ['v6']

        if vlan:
            ip_ = None
            ip_summary.append('private')
            if ip:
                try:
                    ip_ = Ip.info(ip)
                except Exception:
                    pass
                else:
                    if not Ip._check_and_detach(ip_, None):
                        return
            if ip_:
                iface_id = ip_['iface_id']
            else:
                ip_create = Ip.create(4,
                                      vm_params['datacenter_id'],
                                      bandwidth,
                                      None,
                                      vlan,
                                      ip)

                iface_id = ip_create['iface_id']

            # if there is a public ip, will attach this one later, else give
            # the iface to vm.create
            if not ip_version:
                vm_params['iface_id'] = iface_id

        result = cls.call('hosting.vm.create_from', vm_params, disk_params,
                          sys_disk_id_)

        cls.echo('* Configuration used: %d cores, %dMb memory, ip %s, '
                 'image %s, hostname: %s, datacenter: %s' %
                 (cores, memory, '+'.join(ip_summary), image, hostname,
                  datacenter))

        # background mode, bail out now (skip interactive part)
        if background and (not vlan or not ip_version):
            return result

        # interactive mode, run a progress bar
        cls.echo('Creating your Virtual Machine %s.' % hostname)
        cls.display_progress(result)
        cls.echo('Your Virtual Machine %s has been created.' % hostname)

        vm_id = None
        for oper in result:
            if oper.get('vm_id'):
                vm_id = oper.get('vm_id')
                break

        if vlan and ip_version:
            attach = Iface._attach(iface_id, vm_id)
            if background:
                return attach

        if 'ssh_key' not in vm_params and 'keys' not in vm_params:
            return

        if vm_id and ip_version:
            cls.wait_for_sshd(vm_id)
            if ssh:
                cls.ssh_keyscan(vm_id)
                cls.ssh(vm_id, 'root', None)
73282
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 'joyent',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )

    __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 in %s',
        vm_['name'], vm_.get('location', DEFAULT_LOCATION)
    )

    # added . for fqdn hostnames
    salt.utils.cloud.check_name(vm_['name'], 'a-zA-Z0-9-.')
    kwargs = {
        'name': vm_['name'],
        'image': get_image(vm_),
        'size': get_size(vm_),
        'location': vm_.get('location', DEFAULT_LOCATION)
    }
    # Let's not assign a default here; only assign a network value if
    # one is explicitly configured
    if 'networks' in vm_:
        kwargs['networks'] = vm_.get('networks')

    __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']
    )

    data = create_node(**kwargs)
    if data == {}:
        log.error('Error creating %s on JOYENT', vm_['name'])
        return False

    query_instance(vm_)
    data = show_instance(vm_['name'], call='action')

    vm_['key_filename'] = key_filename
    vm_['ssh_host'] = data[1]['primaryIp']

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

    __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[1]
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
424905
def _clones(self):
        """"""
        vbox = VirtualBox()
        machines = []
        for machine in vbox.machines:
            if machine.name == self.machine_name:
                continue
            if machine.name.startswith(self.machine_name):
                machines.append(machine)
        return machines
1163267
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
                                          'profitbricks'),
                                         vm_['profile']) is False):
            return False
    except AttributeError:
        pass

    if 'image_alias' in vm_ and not version_compatible('4.0'):
        raise SaltCloudNotFound(
            "The 'image_alias' parameter requires the profitbricks "
            "SDK v4.0.0 or greater."
        )

    if 'image' not in vm_ and 'image_alias' not in vm_:
        log.error('The image or image_alias parameter is required.')

    signal_event(vm_, 'creating', 'starting create')

    data = None
    datacenter_id = get_datacenter_id()
    conn = get_conn()

    # Assemble list of network interfaces from the cloud profile config.
    nics = _get_nics(vm_)

    # Assemble list of volumes from the cloud profile config.
    volumes = [_get_system_volume(vm_)]
    if 'volumes' in vm_:
        volumes.extend(_get_data_volumes(vm_))

    # Assembla the composite server object.
    server = _get_server(vm_, volumes, nics)

    signal_event(vm_, 'requesting', 'requesting instance')

    try:
        data = conn.create_server(datacenter_id=datacenter_id, server=server)
        log.info(
            'Create server request ID: %s',
            data['requestId'], exc_info_on_loglevel=logging.DEBUG
        )

        _wait_for_completion(conn, data, get_wait_timeout(vm_),
                             'create_server')
    except PBError as exc:
        log.error(
            'Error creating %s on ProfitBricks\n\n'
            'The following exception was thrown by the profitbricks library '
            'when trying to run the initial deployment: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False
    except Exception as exc:  # pylint: disable=W0703
        log.error(
            'Error creating %s \n\nError: \n%s',
            vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
        )
        return False

    vm_['server_id'] = data['id']

    def __query_node_data(vm_, data):
        '''
        Query node data until node becomes available.
        '''
        running = False
        try:
            data = show_instance(vm_['name'], 'action')
            if not data:
                return False
            log.debug(
                'Loaded node data for %s:\nname: %s\nstate: %s',
                vm_['name'], pprint.pformat(data['name']), data['state']
            )
        except Exception as err:
            log.error(
                'Failed to get nodes list: %s', err,
                # Show the trackback if the debug logging level is enabled
                exc_info_on_loglevel=logging.DEBUG
            )
            # Trigger a failure in the wait for IP function
            return False

        running = data['state'] == 'RUNNING'
        if not running:
            # Still not running, trigger another iteration
            return

        if ssh_interface(vm_) == 'private_lan' and data['private_ips']:
            vm_['ssh_host'] = data['private_ips'][0]

        if ssh_interface(vm_) != 'private_lan' and data['public_ips']:
            vm_['ssh_host'] = data['public_ips'][0]

        return data

    try:
        data = salt.utils.cloud.wait_for_ip(
            __query_node_data,
            update_args=(vm_, data),
            timeout=config.get_cloud_config_value(
                'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value(
                'wait_for_ip_interval', vm_, __opts__, default=10),
        )
    except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
        try:
            # It might be already up, let's destroy it!
            destroy(vm_['name'])
        except SaltCloudSystemExit:
            pass
        finally:
            raise SaltCloudSystemExit(six.text_type(exc.message))

    log.debug('VM is now running')
    log.info('Created Cloud VM %s', vm_)
    log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))

    signal_event(vm_, 'created', 'created instance')

    if 'ssh_host' in vm_:
        vm_['key_filename'] = get_key_filename(vm_)
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)
        ret.update(data)
        return ret
    else:
        raise SaltCloudSystemExit('A valid IP address was not found.')
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
359178
def create(name, host):
    '''
    '''
    with Session() as session:
        try:
            result = session.VFolder.create(name, host)
            print('Virtual folder "{0}" is created.'.format(result['name']))
        except Exception as e:
            print_error(e)
            sys.exit(1)
1039043
def add_machine(vm, options = {})
      sys_desc = vm.interface.export(interface, path)
      options.each do |key, value|
        sys_desc.add_description(key, value, value)
      end
    end
468895
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 'proxmox',
                                                           vm_['profile'],
                                                           vm_=vm_) is False:
            return False
    except AttributeError:
        pass

    ret = {}

    __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'])

    if 'use_dns' in vm_ and 'ip_address' not in vm_:
        use_dns = vm_['use_dns']
        if use_dns:
            from socket import gethostbyname, gaierror
            try:
                ip_address = gethostbyname(six.text_type(vm_['name']))
            except gaierror:
                log.debug('Resolving of %s failed', vm_['name'])
            else:
                vm_['ip_address'] = six.text_type(ip_address)

    try:
        newid = _get_next_vmid()
        data = create_node(vm_, newid)
    except Exception as exc:
        log.error(
            'Error creating %s on PROXMOX\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

    ret['creation_data'] = data
    name = vm_['name']        # hostname which we know
    if 'clone' in vm_ and vm_['clone'] is True:
        vmid = newid
    else:
        vmid = data['vmid']       # vmid which we have received
    host = data['node']       # host which we have received
    nodeType = data['technology']  # VM tech (Qemu / OpenVZ)

    if 'agent_get_ip' not in vm_ or vm_['agent_get_ip'] == 0:
        # Determine which IP to use in order of preference:
        if 'ip_address' in vm_:
            ip_address = six.text_type(vm_['ip_address'])
        elif 'public_ips' in data:
            ip_address = six.text_type(data['public_ips'][0])  # first IP
        elif 'private_ips' in data:
            ip_address = six.text_type(data['private_ips'][0])  # first IP
        else:
            raise SaltCloudExecutionFailure("Could not determine an IP address to use")

    # wait until the vm has been created so we can start it
    if not wait_for_created(data['upid'], timeout=300):
        return {'Error': 'Unable to create {0}, command timed out'.format(name)}

    if 'clone' in vm_ and vm_['clone'] is True and vm_['technology'] == 'qemu':
        # If we cloned a machine, see if we need to reconfigure any of the options such as net0,
        # ide2, etc. This enables us to have a different cloud-init ISO mounted for each VM that's
        # brought up

        log.info('Configuring cloned VM')

        # Modify the settings for the VM one at a time so we can see any problems with the values
        # as quickly as possible
        for setting in 'sockets', 'cores', 'cpulimit', 'memory', 'onboot', 'agent':
            if setting in vm_:  # if the property is set, use it for the VM request
                postParams = {}
                postParams[setting] = vm_[setting]
                query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams)

        # cloud-init settings
        for setting in 'ciuser', 'cipassword', 'sshkeys', 'nameserver', 'searchdomain':
            if setting in vm_:  # if the property is set, use it for the VM request
                postParams = {}
                postParams[setting] = vm_[setting]
                query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams)

        for setting_number in range(3):
            setting = 'ide{0}'.format(setting_number)
            if setting in vm_:
                postParams = {}
                postParams[setting] = vm_[setting]
                query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams)

        for setting_number in range(5):
            setting = 'sata{0}'.format(setting_number)
            if setting in vm_:
                vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid))
                if setting in vm_config:
                    setting_params = vm_[setting]
                    setting_storage = setting_params.split(':')[0]
                    setting_size = _stringlist_to_dictionary(setting_params)['size']
                    vm_disk_params = vm_config[setting]
                    vm_disk_storage = vm_disk_params.split(':')[0]
                    vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size']
                    # if storage is different, move the disk
                    if setting_storage != vm_disk_storage:
                        postParams = {}
                        postParams['disk'] = setting
                        postParams['storage'] = setting_storage
                        postParams['delete'] = 1
                        node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format(
                            vm_['host'], vmid), postParams)
                        data = _parse_proxmox_upid(node, vm_)
                        # wait until the disk has been moved
                        if not wait_for_task(data['upid'], timeout=300):
                            return {'Error': 'Unable to move disk {0}, command timed out'.format(
                                setting)}
                    # if storage is different, move the disk
                    if setting_size != vm_disk_size:
                        postParams = {}
                        postParams['disk'] = setting
                        postParams['size'] = setting_size
                        query('put', 'nodes/{0}/qemu/{1}/resize'.format(
                            vm_['host'], vmid), postParams)
                else:
                    postParams = {}
                    postParams[setting] = vm_[setting]
                    query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams)

        for setting_number in range(13):
            setting = 'scsi{0}'.format(setting_number)
            if setting in vm_:
                vm_config = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid))
                if setting in vm_config:
                    setting_params = vm_[setting]
                    setting_storage = setting_params.split(':')[0]
                    setting_size = _stringlist_to_dictionary(setting_params)['size']
                    vm_disk_params = vm_config[setting]
                    vm_disk_storage = vm_disk_params.split(':')[0]
                    vm_disk_size = _stringlist_to_dictionary(vm_disk_params)['size']
                    # if storage is different, move the disk
                    if setting_storage != vm_disk_storage:
                        postParams = {}
                        postParams['disk'] = setting
                        postParams['storage'] = setting_storage
                        postParams['delete'] = 1
                        node = query('post', 'nodes/{0}/qemu/{1}/move_disk'.format(
                            vm_['host'], vmid), postParams)
                        data = _parse_proxmox_upid(node, vm_)
                        # wait until the disk has been moved
                        if not wait_for_task(data['upid'], timeout=300):
                            return {'Error': 'Unable to move disk {0}, command timed out'.format(
                                setting)}
                    # if storage is different, move the disk
                    if setting_size != vm_disk_size:
                        postParams = {}
                        postParams['disk'] = setting
                        postParams['size'] = setting_size
                        query('put', 'nodes/{0}/qemu/{1}/resize'.format(
                            vm_['host'], vmid), postParams)
                else:
                    postParams = {}
                    postParams[setting] = vm_[setting]
                    query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams)

        # net strings are a list of comma seperated settings. We need to merge the settings so that
        # the setting in the profile only changes the settings it touches and the other settings
        # are left alone. An example of why this is necessary is because the MAC address is set
        # in here and generally you don't want to alter or have to know the MAC address of the new
        # instance, but you may want to set the VLAN bridge for example
        for setting_number in range(20):
            setting = 'net{0}'.format(setting_number)
            if setting in vm_:
                data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid))

                # Generate a dictionary of settings from the existing string
                new_setting = {}
                if setting in data:
                    new_setting.update(_stringlist_to_dictionary(data[setting]))

                # Merge the new settings (as a dictionary) into the existing dictionary to get the
                # new merged settings
                new_setting.update(_stringlist_to_dictionary(vm_[setting]))

                # Convert the dictionary back into a string list
                postParams = {setting: _dictionary_to_stringlist(new_setting)}
                query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams)

        for setting_number in range(20):
            setting = 'ipconfig{0}'.format(setting_number)
            if setting in vm_:
                data = query('get', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid))

                # Generate a dictionary of settings from the existing string
                new_setting = {}
                if setting in data:
                    new_setting.update(_stringlist_to_dictionary(data[setting]))

                # Merge the new settings (as a dictionary) into the existing dictionary to get the
                # new merged settings
                if setting_number == 0 and 'ip_address' in vm_:
                    if 'gw' in _stringlist_to_dictionary(vm_[setting]):
                        new_setting.update(_stringlist_to_dictionary(
                            'ip={0}/24,gw={1}'.format(
                                vm_['ip_address'], _stringlist_to_dictionary(vm_[setting])['gw'])))
                    else:
                        new_setting.update(
                            _stringlist_to_dictionary('ip={0}/24'.format(vm_['ip_address'])))
                else:
                    new_setting.update(_stringlist_to_dictionary(vm_[setting]))

                # Convert the dictionary back into a string list
                postParams = {setting: _dictionary_to_stringlist(new_setting)}
                query('post', 'nodes/{0}/qemu/{1}/config'.format(vm_['host'], vmid), postParams)

    # VM has been created. Starting..
    if not start(name, vmid, call='action'):
        log.error('Node %s (%s) failed to start!', name, vmid)
        raise SaltCloudExecutionFailure

    # Wait until the VM has fully started
    log.debug('Waiting for state "running" for vm %s on %s', vmid, host)
    if not wait_for_state(vmid, 'running'):
        return {'Error': 'Unable to start {0}, command timed out'.format(name)}

    # For QEMU VMs, we can get the IP Address from qemu-agent
    if 'agent_get_ip' in vm_ and vm_['agent_get_ip'] == 1:
        def __find_agent_ip(vm_):
            log.debug("Waiting for qemu-agent to start...")
            endpoint = 'nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(vm_['host'], vmid)
            interfaces = query('get', endpoint)
            # If we get a result from the agent, parse it
            if 'result' in interfaces:
                for interface in interfaces['result']:
                    if_name = interface['name']
                    # Only check ethernet type interfaces, as they are not returned in any order
                    if if_name.startswith('eth') or if_name.startswith('ens'):
                        for if_addr in interface['ip-addresses']:
                            ip_addr = if_addr['ip-address']
                            # Ensure interface has a valid IPv4 address
                            if if_addr['ip-address-type'] == 'ipv4' and ip_addr is not None:
                                return six.text_type(ip_addr)
            raise SaltCloudExecutionFailure

        # We have to wait for a bit for qemu-agent to start
        try:
            ip_address = __utils__['cloud.wait_for_fun'](
                __find_agent_ip,
                vm_=vm_
            )
        except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
            try:
                # If VM was created but we can't connect, destroy it.
                destroy(vm_['name'])
            except SaltCloudSystemExit:
                pass
            finally:
                raise SaltCloudSystemExit(six.text_type(exc))

    log.debug('Using IP address %s', ip_address)

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

    ret['ip_address'] = ip_address
    ret['username'] = ssh_username
    ret['password'] = ssh_password

    vm_['ssh_host'] = ip_address
    vm_['password'] = ssh_password
    ret = __utils__['cloud.bootstrap'](vm_, __opts__)

    # Report success!
    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'],
    )

    return ret
729148
def new():
    """"""
    dir_path = os.path.dirname(os.path.realpath(__file__))
    cookiecutter(os.path.join(dir_path, 'historical-cookiecutter/'))
1129919
def create(vm_):
    '''
    
    '''
    clone_strategy = vm_.get('clone_strategy') or 'full'

    if clone_strategy not in ('quick', 'full'):
        raise SaltCloudSystemExit("'clone_strategy' must be one of quick or full. Got '{0}'".format(clone_strategy))

    ip_source = vm_.get('ip_source') or 'ip-learning'

    if ip_source not in ('ip-learning', 'qemu-agent'):
        raise SaltCloudSystemExit("'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'".format(ip_source))

    validate_xml = vm_.get('validate_xml') if vm_.get('validate_xml') is not None else True

    log.info("Cloning '%s' with strategy '%s' validate_xml='%s'", vm_['name'], clone_strategy, validate_xml)

    try:
        # Check for required profile parameters before sending any API calls.
        if vm_['profile'] and config.is_profile_configured(__opts__,
                                                           __active_provider_name__ or 'libvirt',
                                                           vm_['profile']) is False:
            return False
    except AttributeError:
        pass

    # TODO: check name qemu/libvirt will choke on some characters (like '/')?
    name = vm_['name']

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

    key_filename = config.get_cloud_config_value(
        'private_key', vm_, __opts__, search_global=False, default=None
    )
    if key_filename is not None and not os.path.isfile(key_filename):
        raise SaltCloudConfigError(
            'The defined key_filename \'{0}\' does not exist'.format(
                key_filename
            )
        )
    vm_['key_filename'] = key_filename
    # wait_for_instance requires private_key
    vm_['private_key'] = key_filename

    cleanup = []
    try:
        # clone the vm
        base = vm_['base_domain']
        conn = __get_conn(vm_['url'])

        try:
            # for idempotency the salt-bootstrap needs -F argument
            #  script_args: -F
            clone_domain = conn.lookupByName(name)
        except libvirtError as e:
            domain = conn.lookupByName(base)
            # TODO: ensure base is shut down before cloning
            xml = domain.XMLDesc(0)

            kwargs = {
                'name': name,
                'base_domain': base,
            }

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

            log.debug("Source machine XML '%s'", xml)

            domain_xml = ElementTree.fromstring(xml)
            domain_xml.find('./name').text = name
            if domain_xml.find('./description') is None:
                description_elem = ElementTree.Element('description')
                domain_xml.insert(0, description_elem)
            description = domain_xml.find('./description')
            description.text = "Cloned from {0}".format(base)
            domain_xml.remove(domain_xml.find('./uuid'))

            for iface_xml in domain_xml.findall('./devices/interface'):
                iface_xml.remove(iface_xml.find('./mac'))
                # enable IP learning, this might be a default behaviour...
                # Don't always enable since it can cause problems through libvirt-4.5
                if ip_source == 'ip-learning' and iface_xml.find("./filterref/parameter[@name='CTRL_IP_LEARNING']") is None:
                    iface_xml.append(ElementTree.fromstring(IP_LEARNING_XML))

            # If a qemu agent is defined we need to fix the path to its socket
            # <channel type='unix'>
            #   <source mode='bind' path='/var/lib/libvirt/qemu/channel/target/domain-<dom-name>/org.qemu.guest_agent.0'/>
            #   <target type='virtio' name='org.qemu.guest_agent.0'/>
            #   <address type='virtio-serial' controller='0' bus='0' port='2'/>
            # </channel>
            for agent_xml in domain_xml.findall("""./devices/channel[@type='unix']"""):
                #  is org.qemu.guest_agent.0 an option?
                if agent_xml.find("""./target[@type='virtio'][@name='org.qemu.guest_agent.0']""") is not None:
                    source_element = agent_xml.find("""./source[@mode='bind']""")
                    # see if there is a path element that needs rewriting
                    if source_element and 'path' in source_element.attrib:
                        path = source_element.attrib['path']
                        new_path = path.replace('/domain-{0}/'.format(base), '/domain-{0}/'.format(name))
                        log.debug("Rewriting agent socket path to %s", new_path)
                        source_element.attrib['path'] = new_path

            for disk in domain_xml.findall("""./devices/disk[@device='disk'][@type='file']"""):
                # print "Disk: ", ElementTree.tostring(disk)
                # check if we can clone
                driver = disk.find("./driver[@name='qemu']")
                if driver is None:
                    # Err on the safe side
                    raise SaltCloudExecutionFailure("Non qemu driver disk encountered bailing out.")
                disk_type = driver.attrib.get('type')
                log.info("disk attributes %s", disk.attrib)
                if disk_type == 'qcow2':
                    source = disk.find("./source").attrib['file']
                    pool, volume = find_pool_and_volume(conn, source)
                    if clone_strategy == 'quick':
                        new_volume = pool.createXML(create_volume_with_backing_store_xml(volume), 0)
                    else:
                        new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
                    cleanup.append({'what': 'volume', 'item': new_volume})

                    disk.find("./source").attrib['file'] = new_volume.path()
                elif disk_type == 'raw':
                    source = disk.find("./source").attrib['file']
                    pool, volume = find_pool_and_volume(conn, source)
                    # TODO: more control on the cloned disk type
                    new_volume = pool.createXMLFrom(create_volume_xml(volume), volume, 0)
                    cleanup.append({'what': 'volume', 'item': new_volume})

                    disk.find("./source").attrib['file'] = new_volume.path()
                else:
                    raise SaltCloudExecutionFailure("Disk type '{0}' not supported".format(disk_type))

            clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml))
            log.debug("Clone XML '%s'", clone_xml)

            validate_flags = libvirt.VIR_DOMAIN_DEFINE_VALIDATE if validate_xml else 0
            clone_domain = conn.defineXMLFlags(clone_xml, validate_flags)

            cleanup.append({'what': 'domain', 'item': clone_domain})
            clone_domain.createWithFlags(libvirt.VIR_DOMAIN_START_FORCE_BOOT)

        log.debug("VM '%s'", vm_)

        if ip_source == 'qemu-agent':
            ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT
        elif ip_source == 'ip-learning':
            ip_source = libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE

        address = salt.utils.cloud.wait_for_ip(
            get_domain_ip,
            update_args=(clone_domain, 0, ip_source),
            timeout=config.get_cloud_config_value('wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
            interval=config.get_cloud_config_value('wait_for_ip_interval', vm_, __opts__, default=10),
            interval_multiplier=config.get_cloud_config_value('wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
        )

        log.info('Address = %s', address)

        vm_['ssh_host'] = address

        # the bootstrap script needs to be installed first in /etc/salt/cloud.deploy.d/
        # salt-cloud -u is your friend
        ret = __utils__['cloud.bootstrap'](vm_, __opts__)

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

        return ret
    except Exception as e:  # pylint: disable=broad-except
        do_cleanup(cleanup)
        # throw the root cause after cleanup
        raise e
1180796
def create(self):
        """"""
        self.server_attrs = self.consul.create_server(
                "%s-%s" % (self.stack.name, self.name),
                self.disk_image_id,
                self.instance_type,
                self.ssh_key_name,
                tags=self.tags,
                availability_zone=self.availability_zone,
                timeout_s=self.launch_timeout_s,
                security_groups=self.security_groups,
                **self.provider_extras
                )
        log.debug('Post launch delay: %d s' % self.post_launch_delay_s)
        time.sleep(self.post_launch_delay_s)
77077
def add(self):
        """"""

        yield self.client.create(self.path)
        yield self.client.create(self.path + "/type", self.name)
        yield self.client.create(self.path + "/state")
        yield self.client.create(self.path + "/machines", "[]")

        log.debug("registered service '%s' at %s." % (self.name, self.path))
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
448184
def create(self):
        """"""
        self._storage_broker.create_structure()
        self._storage_broker.put_admin_metadata(self._admin_metadata)
432768
def create(vm_=None, call=None):
    '''
    
    '''
    if call:
        raise SaltCloudSystemExit(
            'You cannot create an instance with -a or -f.'
        )

    node_info = request_instance(vm_)
    if isinstance(node_info, bool):
        raise SaltCloudSystemExit(
            'There was an error creating the GCE instance.'
        )
    node_dict = node_info[0]
    node_data = node_info[1]

    ssh_user, ssh_key = __get_ssh_credentials(vm_)
    vm_['ssh_host'] = __get_host(node_data, vm_)
    vm_['key_filename'] = ssh_key

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

    ret.update(node_dict)

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

    __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
946452
def create(self):
        """"""
        # url('datastores')
        content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH']))
        content = content.decode('utf8')
        content = simplejson.loads(content)
        new = DataStore(content['name'],
                        content['type'],
                        content['ogrstring'])
        results = meta.Session.add(new)
        meta.Session.commit()
        response.status = 201