Create a single VM from a data dict

    CLI Example:

    .. code-block:: bash

        salt-cloud -p proxmox-ubuntu vmhostname

def create(vm_):
    '''
    Create a single VM from a data dict

    CLI Example:

    .. code-block:: bash

        salt-cloud -p proxmox-ubuntu vmhostname
    '''
    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